Repository navigation
Expand file tree
/
Copy patherror.ts
More file actions
333 lines (321 loc) · 12.7 KB
/
Copy patherror.ts
File metadata and controls
333 lines (321 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import {
Database,
ModelCatalog,
Plugin,
Runner,
SandboxError,
SessionStore,
Settings,
} from "@codeworksh/harness/effect";
import { SandboxProvider } from "@codeworksh/harness/sandbox";
import { Duration, Effect, Schema } from "effect";
import * as Client from "../server/client.ts";
import { writeError } from "./output.ts";
/** Bad flag or argument combinations the parser cannot express on its own. */
export class InvalidInputError extends Schema.TaggedError<InvalidInputError>()("CLI.InvalidInputError", {
message: Schema.String,
}) {}
export class OAuthError extends Schema.TaggedError<OAuthError>()("CLI.OAuthError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {}
/**
* Every failure a command handler may surface to the runtime. Harness failures are
* rendered inside the handler that owns them, so only the CLI's own errors reach
* the top-level renderer.
*/
export type CommandError = InvalidInputError | OAuthError;
const isInvalidInputError = Schema.is(InvalidInputError);
const isOAuthError = Schema.is(OAuthError);
const isProviderError = Schema.is(Runner.ProviderError);
const isModelCatalogError = Schema.is(Runner.ModelCatalogError);
const isModelCatalogRefreshError = Schema.is(ModelCatalog.RefreshError);
const isModelNotFoundError = Schema.is(Runner.ModelNotFoundError);
const isNoModelError = Schema.is(Runner.NoModelError);
const isLLMStreamError = Schema.is(Runner.LLMStreamError);
const isSandboxProviderError = Schema.is(SandboxProvider.SandboxProviderError);
const isPluginInstallError = Schema.is(Plugin.InstallError);
const isPluginSourceError = Schema.is(Plugin.SourceError);
const isPluginStoreError = Schema.is(Plugin.StoreError);
const isPluginLoadError = Schema.is(Plugin.LoadError);
const isSessionNotLinkedError = Schema.is(SessionStore.SessionNotLinkedError);
const isSettingsError = Schema.is(Settings.SettingsError);
const isSandboxDriverNotRegisteredError = Schema.is(SandboxError.SandboxDriverNotRegisteredError);
const isSandboxDriverRegistrationError = Schema.is(SandboxError.SandboxDriverRegistrationError);
const isExecutionError = Schema.is(Client.ExecutionError);
const isDatabaseOutdatedError = Schema.is(Database.OutdatedError);
const credentialHint = (provider: string): string => {
switch (provider) {
case "openrouter":
return "set OPENROUTER_API_KEY and retry";
case "openai":
return "set OPENAI_API_KEY and retry";
case "openai-codex":
return "run `codework auth login --openai-codex` and retry";
case "github-copilot":
return "run `codework auth login --github-copilot` and retry";
case "anthropic":
return "set ANTHROPIC_API_KEY and retry";
case "google":
return "set GOOGLE_GENERATIVE_AI_API_KEY and retry";
case "xai":
return "set XAI_API_KEY and retry";
default:
return `configure credentials for provider "${provider}" and retry`;
}
};
const providerHint = (error: Runner.ProviderError): string | undefined => {
switch (error.reason._tag) {
case "Runner.ProviderAuthenticationError":
return error.reason.authentication === "missing"
? credentialHint(error.provider)
: `check the credentials configured for provider "${error.provider}"`;
case "Runner.ProviderAuthorizationError":
return "check that the credential can access this model and endpoint";
case "Runner.ProviderModelUnavailableError":
return "check the provider model ID and whether your account can access it";
case "Runner.ProviderRateLimitError":
return error.reason.retryAfter === undefined
? "retry after the provider rate-limit window resets"
: `retry in about ${Math.ceil(Duration.toMillis(error.reason.retryAfter) / 1_000)} seconds`;
case "Runner.ProviderQuotaError":
return "check the provider account quota or billing balance";
case "Runner.ProviderTimeoutError":
case "Runner.ProviderTransportError":
case "Runner.ProviderUnavailableError":
return error.isRetryable ? "this failure is retryable" : undefined;
default:
return undefined;
}
};
const unknownMessage = (error: unknown): string => {
if (error instanceof Error && error.message.trim().length > 0) return error.message;
if (typeof error === "string" && error.trim().length > 0) return error;
if (typeof error === "object" && error !== null && "_tag" in error) {
// A bare tag such as `ServeError` hides the reason; its cause carries it (`EADDRINUSE`).
const cause = "cause" in error ? error.cause : undefined;
return cause instanceof Error ? `${String(error._tag)}: ${cause.message}` : String(error._tag);
}
return "the command failed for an unknown reason";
};
/**
* What the reader can do about a reference that failed to prepare. A plugin list is
* usually hand-written in a settings file, so the phase is worth translating.
*/
/** One hint per reason. Lowercase, like everything else a plugin failure prints. */
const providerCategory = (reason: Runner.ProviderFailureReason): string => {
switch (reason._tag) {
case "Runner.ProviderAuthenticationError":
return "provider-authentication-error";
case "Runner.ProviderConfigurationError":
return "provider-configuration-error";
case "Runner.ProviderAuthorizationError":
return "provider-authorization-error";
case "Runner.ProviderModelUnavailableError":
return "provider-model-unavailable-error";
case "Runner.ProviderRateLimitError":
return "provider-rate-limit-error";
case "Runner.ProviderQuotaError":
return "provider-quota-error";
case "Runner.ProviderInvalidRequestError":
return "provider-invalid-request-error";
case "Runner.ProviderContentPolicyError":
return "provider-content-filter-error";
case "Runner.ProviderTimeoutError":
return "provider-timeout-error";
case "Runner.ProviderTransportError":
return "provider-transport-error";
case "Runner.ProviderUnavailableError":
return "provider-unavailable-error";
case "Runner.ProviderInvalidResponseError":
return "provider-invalid-response-error";
case "Runner.ProviderUnknownError":
return "provider-unknown-error";
}
};
const pluginReasonHint = (
reason:
| Plugin.SourceError["reason"]
| Plugin.InstallError["reason"]
| Plugin.StoreError["reason"]
| Plugin.LoadError["reason"],
): string => {
switch (reason) {
case "plugin-unsupported-source":
return "a path entry starts with `./`, `../`, `~/` or `/`; anything else is a package or a git spec, and a remote tarball is not supported";
case "plugin-not-found":
return "the path does not exist; check the spelling, remembering it anchors to the settings file that declares it";
case "plugin-escapes-root":
return "a plugin path must stay inside the project it is declared in";
case "plugin-resolve-failed":
return "check that the registry or git remote is reachable, and that your credentials are current";
case "plugin-fetch-failed":
return "check the package name and version, and that the registry is reachable";
case "plugin-no-commit":
return "the git source installed but no commit could be recovered; name a branch, tag or commit explicitly";
case "plugin-no-entrypoint":
return "the package installed but exports no module to import; check its `exports` and `main`";
case "plugin-not-installed":
return "run `codework plugin install` to fetch what the settings files name";
case "plugin-lock-timeout":
return "another install is holding this entry; wait for it to finish, or remove the stale `.lock` directory";
case "plugin-marker-invalid":
case "plugin-index-invalid":
return "the store entry is damaged; remove it and install again";
case "plugin-collect-failed":
return "the store could not be tidied; check the permissions on the plugin cache";
case "plugin-import-failed":
return "the module failed to load; import it directly to see its own error";
case "plugin-missing-dependency":
return "the plugin's own dependencies are missing; install them where the plugin lives";
case "plugin-not-compiled":
return "a plugin installed from git or npm must ship compiled javascript; build it and commit or publish the output";
case "plugin-invalid-definition":
return "a plugin module must default-export one object with a `setup` and a `vendor.domain.name` id";
}
};
const settingsHint = (reason: Settings.SettingsError["reason"]): string => {
switch (reason) {
case "read":
return "the file exists but could not be read; check that it is a file and readable";
case "write":
return "the file could not be written; check that its directory is writable";
case "parse":
return "the file is not valid JSON; the location above is where parsing stopped";
case "decode":
return "the key above holds a value this setting does not accept";
}
};
/** Render typed SDK errors for humans without exposing Effect causes or provider payloads. */
export const renderError = (error: unknown): string => {
if (isSandboxDriverNotRegisteredError(error)) {
return `error: sandbox driver "${error.driver}" is not registered (available: ${error.registered?.join(", ") ?? "none"})\n`;
}
if (isSandboxDriverRegistrationError(error)) {
return `error: ${error.reason}\n`;
}
if (isInvalidInputError(error)) {
return `error: ${error.message}\n`;
}
if (isDatabaseOutdatedError(error)) {
return `error[database-outdated]: ${error.message}\n`;
}
if (isOAuthError(error)) {
return (
[
`error[oauth-credential-error]: ${error.message}`,
...(error.cause === undefined ? [] : [`detail: ${unknownMessage(error.cause)}`]),
].join("\n") + "\n"
);
}
if (isSandboxProviderError(error)) {
return (
[
`error: SandboxProviderError - ${error.sanitized.message}`,
`driver: ${error.driver}`,
`operation: ${error.operation}`,
...(error.sanitized.code === undefined ? [] : [`code: ${error.sanitized.code}`]),
...(error.stack === undefined ? [] : ["traceback:", error.stack]),
].join("\n") + "\n"
);
}
if (isSessionNotLinkedError(error)) {
return (
[
`error[${error.reason}]: ${error.message}`,
`session: ${error.sessionId}`,
"hint: run `codework session link <session-id>` from the directory to anchor it to",
].join("\n") + "\n"
);
}
if (isSettingsError(error)) {
return (
[
`error[settings-${error.reason}-failed]: ${error.path}`,
`detail: ${error.detail}`,
`hint: ${settingsHint(error.reason)}`,
].join("\n") + "\n"
);
}
// One shape for all three plugin domains: the reason is the slug, the message is the sentence,
// and the reference is the string the person recognises from their settings file.
if (
isPluginSourceError(error) ||
isPluginInstallError(error) ||
isPluginStoreError(error) ||
isPluginLoadError(error)
) {
return (
[
`error[${error.reason}]: ${error.message}`,
...(error.reference === "" ? [] : [`reference: ${error.reference}`]),
...(error.file === undefined ? [] : [`declared in: ${error.file}`]),
...(isPluginLoadError(error) && error.id !== undefined ? [`id: ${error.id}`] : []),
`hint: ${pluginReasonHint(error.reason)}`,
].join("\n") + "\n"
);
}
if (isProviderError(error)) {
const hint = providerHint(error);
return (
[
`error[${providerCategory(error.reason)}]: ${error.message}`,
`provider: ${error.provider}`,
`model: ${error.model}`,
...(error.reason.requestId === undefined ? [] : [`request: ${error.reason.requestId}`]),
...(hint === undefined ? [] : [`hint: ${hint}`]),
].join("\n") + "\n"
);
}
if (isModelCatalogError(error)) {
return (
[`error[model-catalog-${error.reason}]: ${error.message}`, "hint: run `codework models refresh`"].join("\n") +
"\n"
);
}
if (isModelCatalogRefreshError(error)) {
return (
[`error[catalog-refresh-failed]: ${error.message}`, "hint: check the network connection and retry"].join(
"\n",
) + "\n"
);
}
if (isModelNotFoundError(error)) {
return (
[
`error[model-not-found-error]: ${error.message}`,
"hint: check the provider/model IDs in models.gen.json or regenerate the catalog",
].join("\n") + "\n"
);
}
if (isNoModelError(error)) {
return (
[
`error[no-model-error]: ${error.message}`,
"hint: set a provider API key, run `codework auth login`, or set model.provider and model.id in settings",
].join("\n") + "\n"
);
}
if (isLLMStreamError(error)) {
return `error[llm-stream-error]: ${error.message}\n`;
}
// A remote run has only the category the server published; render it the same
// way a local typed error is rendered, minus the detail that stayed server-side.
if (isExecutionError(error)) {
return (
[
error.type === "aborted" ? `error: ${error.message}` : `error[${error.type}]: ${error.message}`,
...(error.status === undefined ? [] : [`status: ${error.status}`]),
].join("\n") + "\n"
);
}
return `error: ${unknownMessage(error)}\n`;
};
export const reportFailure = (error: unknown) =>
writeError(renderError(error)).pipe(
Effect.andThen(
Effect.sync(() => {
process.exitCode = 1;
}),
),
);