@catamorphic/ai-sdk 0.0.0-stage → 0.1.0-alpha.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.txt +202 -0
- package/NOTICE.txt +32 -0
- package/README.md +73 -2
- package/dist/adapter.d.ts +86 -0
- package/dist/adapter.d.ts.map +1 -0
- package/dist/errors.d.ts +18 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2166 -0
- package/dist/index.js.map +15 -0
- package/dist/shell.d.ts +88 -0
- package/dist/shell.d.ts.map +1 -0
- package/dist/telemetry.d.ts +22 -0
- package/dist/telemetry.d.ts.map +1 -0
- package/dist/testing/index.d.ts +123 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +211 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/thread.d.ts +71 -0
- package/dist/thread.d.ts.map +1 -0
- package/dist/tools.d.ts +148 -0
- package/dist/tools.d.ts.map +1 -0
- package/package.json +67 -4
- package/src/adapter.ts +1378 -0
- package/src/errors.ts +83 -0
- package/src/index.ts +23 -0
- package/src/shell.ts +470 -0
- package/src/telemetry.ts +295 -0
- package/src/testing/index.ts +349 -0
- package/src/thread.ts +209 -0
- package/src/tools.ts +740 -0
package/src/errors.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { AgentErrorKind } from "@catamorphic/agent-protocol";
|
|
2
|
+
import { APICallError, RetryError } from "ai";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Failure signatures in provider messages, for errors that carry no status
|
|
6
|
+
* code (a stream `error` part, a transport failure). Auth first: an invalid
|
|
7
|
+
* key can also produce the 4xx phrasings below.
|
|
8
|
+
*/
|
|
9
|
+
const KIND_SIGNATURES: Array<{ kind: AgentErrorKind; pattern: RegExp }> = [
|
|
10
|
+
{ kind: "auth", pattern: /\buser not found\b/i }, // OpenRouter 401
|
|
11
|
+
{ kind: "auth", pattern: /\binvalid x-api-key\b/i }, // Anthropic
|
|
12
|
+
{ kind: "auth", pattern: /\bauthentication[_ ]error\b/i },
|
|
13
|
+
{ kind: "auth", pattern: /\bincorrect api key\b/i }, // OpenAI
|
|
14
|
+
{ kind: "auth", pattern: /\binvalid api key\b/i },
|
|
15
|
+
{ kind: "auth", pattern: /\bno auth credentials\b/i },
|
|
16
|
+
{ kind: "auth", pattern: /\bunauthorized\b/i },
|
|
17
|
+
// Mid-conversation model switches: reasoning output is signed by the
|
|
18
|
+
// producing model; another model rejects the history.
|
|
19
|
+
{ kind: "model_incompat", pattern: /\bsignature\b/i },
|
|
20
|
+
{ kind: "model_incompat", pattern: /\bthinking.{0,40}block/i },
|
|
21
|
+
{ kind: "model_incompat", pattern: /\bencrypted.{0,20}(reasoning|content)/i },
|
|
22
|
+
{ kind: "model_incompat", pattern: /\breasoning.{0,40}not supported/i },
|
|
23
|
+
{ kind: "rate_limit", pattern: /\brate.?limit/i },
|
|
24
|
+
{ kind: "rate_limit", pattern: /\btoo many requests\b/i },
|
|
25
|
+
{ kind: "rate_limit", pattern: /\bquota\b/i },
|
|
26
|
+
{ kind: "unavailable", pattern: /\boverloaded\b/i },
|
|
27
|
+
{ kind: "unavailable", pattern: /\bservice unavailable\b/i },
|
|
28
|
+
{ kind: "unavailable", pattern: /\binternal server error\b/i },
|
|
29
|
+
{ kind: "unavailable", pattern: /\bECONN(RESET|REFUSED)\b/ },
|
|
30
|
+
{ kind: "unavailable", pattern: /\bETIMEDOUT\b|\bENOTFOUND\b/ },
|
|
31
|
+
{ kind: "unavailable", pattern: /\bfetch failed\b/i },
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
export interface ClassifiedError {
|
|
35
|
+
message: string;
|
|
36
|
+
kind?: AgentErrorKind;
|
|
37
|
+
/**
|
|
38
|
+
* The model provider answered the request with a refusal (a status code,
|
|
39
|
+
* or a recognized provider failure): nothing ran on its side.
|
|
40
|
+
*/
|
|
41
|
+
providerRejected: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Classify a failed model call (ADR 0057's error kinds): `auth` offers a
|
|
46
|
+
* re-connect path, `rate_limit` and `unavailable` explain an outage,
|
|
47
|
+
* `model_incompat` retries with sanitized reasoning history.
|
|
48
|
+
*/
|
|
49
|
+
export function classifyModelError(error: unknown): ClassifiedError {
|
|
50
|
+
const cause = RetryError.isInstance(error) ? error.lastError : error;
|
|
51
|
+
const message = errorMessage(cause);
|
|
52
|
+
if (APICallError.isInstance(cause)) {
|
|
53
|
+
const text = `${cause.message}\n${cause.responseBody ?? ""}`;
|
|
54
|
+
const kind = statusKind(cause.statusCode) ?? signatureKind(text);
|
|
55
|
+
return { message, ...(kind ? { kind } : {}), providerRejected: true };
|
|
56
|
+
}
|
|
57
|
+
const kind = signatureKind(message);
|
|
58
|
+
return {
|
|
59
|
+
message,
|
|
60
|
+
...(kind ? { kind } : {}),
|
|
61
|
+
providerRejected: Boolean(kind),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function statusKind(status: number | undefined): AgentErrorKind | undefined {
|
|
66
|
+
if (status === 401 || status === 403) return "auth";
|
|
67
|
+
if (status === 429) return "rate_limit";
|
|
68
|
+
if (
|
|
69
|
+
status === 408 ||
|
|
70
|
+
status === 529 ||
|
|
71
|
+
(status !== undefined && status >= 500)
|
|
72
|
+
)
|
|
73
|
+
return "unavailable";
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function signatureKind(text: string): AgentErrorKind | undefined {
|
|
78
|
+
return KIND_SIGNATURES.find(({ pattern }) => pattern.test(text))?.kind;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function errorMessage(error: unknown): string {
|
|
82
|
+
return error instanceof Error ? error.message : String(error);
|
|
83
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export {
|
|
2
|
+
AI_SDK_HARNESS,
|
|
3
|
+
type AiSdkAdapterOptions,
|
|
4
|
+
type AiSdkLocal,
|
|
5
|
+
createAiSdkAdapter,
|
|
6
|
+
type McpConnector,
|
|
7
|
+
} from "./adapter.js";
|
|
8
|
+
export { classifyModelError } from "./errors.js";
|
|
9
|
+
export {
|
|
10
|
+
type ShellState,
|
|
11
|
+
stopBackgroundCommands,
|
|
12
|
+
} from "./shell.js";
|
|
13
|
+
export {
|
|
14
|
+
entriesThroughTurn,
|
|
15
|
+
foldThread,
|
|
16
|
+
parseThreadEntries,
|
|
17
|
+
type ThreadEntry,
|
|
18
|
+
} from "./thread.js";
|
|
19
|
+
export {
|
|
20
|
+
type AiSdkSandboxProvider,
|
|
21
|
+
mcpModelToolName,
|
|
22
|
+
pruneEmptyOptionalArgs,
|
|
23
|
+
} from "./tools.js";
|
package/src/shell.ts
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
type FollowProcessResult,
|
|
4
|
+
followProcess,
|
|
5
|
+
type SandboxProcessProvider,
|
|
6
|
+
type SandboxProvider,
|
|
7
|
+
STOPPED_WAITING_NOTE,
|
|
8
|
+
} from "@catamorphic/sandbox";
|
|
9
|
+
import { type Tool, tool } from "ai";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
|
|
12
|
+
/** Foreground commands wait this long unless the agent asks for more. */
|
|
13
|
+
export const SHELL_DEFAULT_TIMEOUT_MS = 120_000;
|
|
14
|
+
/**
|
|
15
|
+
* The longest a foreground command may run when its Environment sets no
|
|
16
|
+
* `commandTimeoutSeconds` budget (ADR 0174).
|
|
17
|
+
*/
|
|
18
|
+
export const SHELL_DEFAULT_BUDGET_SECONDS = 600;
|
|
19
|
+
/** Model-facing output budget: the start and the end of long output survive. */
|
|
20
|
+
export const SHELL_OUTPUT_LIMIT = 30_000;
|
|
21
|
+
/** How long starting a background command waits so quick failures show. */
|
|
22
|
+
const START_SETTLE_MS = 3_000;
|
|
23
|
+
/** How long a stopped command gets to exit before it is killed. */
|
|
24
|
+
const STOP_GRACE_MS = 2_000;
|
|
25
|
+
|
|
26
|
+
export type ShellProvider = Pick<SandboxProvider, "executeCommand"> &
|
|
27
|
+
Partial<Pick<SandboxProvider, "processes">>;
|
|
28
|
+
|
|
29
|
+
/** Per-session shell state. */
|
|
30
|
+
export interface ShellState {
|
|
31
|
+
/** The directory the last command left behind. */
|
|
32
|
+
cwd?: string;
|
|
33
|
+
/** This chat's background commands and where their next read starts. */
|
|
34
|
+
background?: Map<string, { cursor: number }>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The lines that start a command from the project folder: load the
|
|
39
|
+
* session's environment files (ADRs 0206, 0212) while still there, then
|
|
40
|
+
* move to `cwd`. The command starts in the root already; a root only the
|
|
41
|
+
* provider can map (a virtual `/workspace`) stays where the provider put
|
|
42
|
+
* it.
|
|
43
|
+
*/
|
|
44
|
+
function commandPrelude(input: {
|
|
45
|
+
root: string;
|
|
46
|
+
cwd: string;
|
|
47
|
+
envFiles?: readonly string[];
|
|
48
|
+
}): string[] {
|
|
49
|
+
return [
|
|
50
|
+
...(input.envFiles ?? []).map(
|
|
51
|
+
(file) => `if [ -f ${quote(file)} ]; then . ${quote(file)}; fi`,
|
|
52
|
+
),
|
|
53
|
+
`cd ${quote(input.cwd)} 2>/dev/null || cd ${quote(input.root)} 2>/dev/null`,
|
|
54
|
+
];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Run one foreground command the way a terminal user expects: in the
|
|
59
|
+
* directory the previous command left (so `cd` persists between calls),
|
|
60
|
+
* with stdout and stderr together, bounded in time, and cancellable. Where
|
|
61
|
+
* the sandbox runs background processes, the command is one the shell waits
|
|
62
|
+
* on (ADR 0174): no transport has to hold a request open for as long as it
|
|
63
|
+
* runs, so the bound is the Environment's budget, not a queue's.
|
|
64
|
+
*/
|
|
65
|
+
export async function runShell(input: {
|
|
66
|
+
provider: ShellProvider;
|
|
67
|
+
sandboxId: string;
|
|
68
|
+
/** The session's project folder: the starting directory and the fallback. */
|
|
69
|
+
root: string;
|
|
70
|
+
state: ShellState;
|
|
71
|
+
command: string;
|
|
72
|
+
timeoutMs?: number;
|
|
73
|
+
/** The Environment's budget for one command; ten minutes by default. */
|
|
74
|
+
budgetSeconds?: number;
|
|
75
|
+
signal?: AbortSignal;
|
|
76
|
+
/**
|
|
77
|
+
* The session's environment files (ADRs 0206, 0212), from the project
|
|
78
|
+
* folder or absolute: each loaded before the command when it exists.
|
|
79
|
+
*/
|
|
80
|
+
envFiles?: readonly string[];
|
|
81
|
+
}): Promise<{ exitCode: number; output: string }> {
|
|
82
|
+
const marker = `__catamorphic_cwd_${crypto.randomUUID().replaceAll("-", "")}__`;
|
|
83
|
+
const cwd = input.state.cwd ?? input.root;
|
|
84
|
+
const script = [
|
|
85
|
+
...commandPrelude({
|
|
86
|
+
root: input.root,
|
|
87
|
+
cwd,
|
|
88
|
+
...(input.envFiles ? { envFiles: input.envFiles } : {}),
|
|
89
|
+
}),
|
|
90
|
+
input.command,
|
|
91
|
+
"__catamorphic_status=$?",
|
|
92
|
+
`printf '\\n${marker}%s\\n' "$PWD"`,
|
|
93
|
+
"exit $__catamorphic_status",
|
|
94
|
+
].join("\n");
|
|
95
|
+
const budgetMs =
|
|
96
|
+
(input.budgetSeconds ?? SHELL_DEFAULT_BUDGET_SECONDS) * 1_000;
|
|
97
|
+
const timeoutMs = Math.min(
|
|
98
|
+
Math.max(input.timeoutMs ?? SHELL_DEFAULT_TIMEOUT_MS, 1_000),
|
|
99
|
+
budgetMs,
|
|
100
|
+
);
|
|
101
|
+
const processes = input.provider.processes;
|
|
102
|
+
const result = processes
|
|
103
|
+
? await waitedCommand({
|
|
104
|
+
processes,
|
|
105
|
+
sandboxId: input.sandboxId,
|
|
106
|
+
root: input.root,
|
|
107
|
+
script,
|
|
108
|
+
timeoutMs,
|
|
109
|
+
...(input.signal ? { signal: input.signal } : {}),
|
|
110
|
+
})
|
|
111
|
+
: await input.provider
|
|
112
|
+
.executeCommand(input.sandboxId, script, {
|
|
113
|
+
cwd: input.root,
|
|
114
|
+
timeout: Math.ceil(timeoutMs / 1000),
|
|
115
|
+
...(input.signal ? { signal: input.signal } : {}),
|
|
116
|
+
})
|
|
117
|
+
.then((executed) => ({
|
|
118
|
+
exitCode: executed.exitCode,
|
|
119
|
+
output: truncateOutput(executed.result),
|
|
120
|
+
note: undefined,
|
|
121
|
+
}));
|
|
122
|
+
const at = result.output.lastIndexOf(marker);
|
|
123
|
+
if (at !== -1) {
|
|
124
|
+
const directory = result.output.slice(at + marker.length).split("\n", 1)[0];
|
|
125
|
+
if (directory) input.state.cwd = directory;
|
|
126
|
+
}
|
|
127
|
+
const output = (
|
|
128
|
+
at === -1 ? result.output : result.output.slice(0, at)
|
|
129
|
+
).replace(/\n+$/, "");
|
|
130
|
+
return {
|
|
131
|
+
exitCode: result.exitCode,
|
|
132
|
+
output: result.note ? `${output}\n${result.note}`.trimStart() : output,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** A foreground command as a process the shell waits on (ADR 0174). */
|
|
137
|
+
async function waitedCommand(args: {
|
|
138
|
+
processes: SandboxProcessProvider;
|
|
139
|
+
sandboxId: string;
|
|
140
|
+
root: string;
|
|
141
|
+
script: string;
|
|
142
|
+
timeoutMs: number;
|
|
143
|
+
signal?: AbortSignal;
|
|
144
|
+
}): Promise<{ exitCode: number; output: string; note?: string }> {
|
|
145
|
+
const started = await args.processes.startProcess({
|
|
146
|
+
sandboxId: args.sandboxId,
|
|
147
|
+
command: args.script,
|
|
148
|
+
cwd: args.root,
|
|
149
|
+
});
|
|
150
|
+
const followed = await followProcess({
|
|
151
|
+
processes: args.processes,
|
|
152
|
+
sandboxId: args.sandboxId,
|
|
153
|
+
processId: started.processId,
|
|
154
|
+
cursor: 0,
|
|
155
|
+
timeoutMs: args.timeoutMs,
|
|
156
|
+
outputLimit: SHELL_OUTPUT_LIMIT,
|
|
157
|
+
...(args.signal ? { signal: args.signal } : {}),
|
|
158
|
+
});
|
|
159
|
+
if (!followed.timedOut && !followed.aborted)
|
|
160
|
+
return { exitCode: followed.exitCode ?? 1, output: followed.output };
|
|
161
|
+
// Out of time or cancelled: the command stops with everything it started.
|
|
162
|
+
const stopped = await stopProcess({
|
|
163
|
+
processes: args.processes,
|
|
164
|
+
sandboxId: args.sandboxId,
|
|
165
|
+
processId: started.processId,
|
|
166
|
+
cursor: followed.cursor,
|
|
167
|
+
}).catch(() => undefined);
|
|
168
|
+
return {
|
|
169
|
+
exitCode: followed.timedOut ? 124 : 130,
|
|
170
|
+
output: followed.output + (stopped?.output ?? ""),
|
|
171
|
+
note: followed.timedOut
|
|
172
|
+
? `Command timed out after ${Math.round(args.timeoutMs / 1000)}s and was stopped. Use run_background_command for longer work.`
|
|
173
|
+
: "Command was cancelled.",
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Interrupt, give it a moment, then kill whatever remains of its group. */
|
|
178
|
+
async function stopProcess(args: {
|
|
179
|
+
processes: SandboxProcessProvider;
|
|
180
|
+
sandboxId: string;
|
|
181
|
+
processId: string;
|
|
182
|
+
cursor: number;
|
|
183
|
+
}): Promise<FollowProcessResult> {
|
|
184
|
+
await args.processes.signalProcess({
|
|
185
|
+
sandboxId: args.sandboxId,
|
|
186
|
+
processId: args.processId,
|
|
187
|
+
signal: "SIGTERM",
|
|
188
|
+
});
|
|
189
|
+
const settled = await followProcess({
|
|
190
|
+
processes: args.processes,
|
|
191
|
+
sandboxId: args.sandboxId,
|
|
192
|
+
processId: args.processId,
|
|
193
|
+
cursor: args.cursor,
|
|
194
|
+
timeoutMs: STOP_GRACE_MS,
|
|
195
|
+
outputLimit: SHELL_OUTPUT_LIMIT,
|
|
196
|
+
pollMs: 500,
|
|
197
|
+
});
|
|
198
|
+
if (settled.status === "exited") return settled;
|
|
199
|
+
await args.processes.signalProcess({
|
|
200
|
+
sandboxId: args.sandboxId,
|
|
201
|
+
processId: args.processId,
|
|
202
|
+
signal: "SIGKILL",
|
|
203
|
+
});
|
|
204
|
+
const killed = await followProcess({
|
|
205
|
+
processes: args.processes,
|
|
206
|
+
sandboxId: args.sandboxId,
|
|
207
|
+
processId: args.processId,
|
|
208
|
+
cursor: settled.cursor,
|
|
209
|
+
timeoutMs: STOP_GRACE_MS,
|
|
210
|
+
outputLimit: SHELL_OUTPUT_LIMIT,
|
|
211
|
+
pollMs: 500,
|
|
212
|
+
});
|
|
213
|
+
return { ...killed, output: settled.output + killed.output };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Keep the first and last parts of long output; errors usually sit at the end. */
|
|
217
|
+
export function truncateOutput(
|
|
218
|
+
output: string,
|
|
219
|
+
limit = SHELL_OUTPUT_LIMIT,
|
|
220
|
+
): string {
|
|
221
|
+
if (output.length <= limit) return output;
|
|
222
|
+
const head = Math.floor(limit / 3);
|
|
223
|
+
const tail = limit - head;
|
|
224
|
+
const omitted = output.length - head - tail;
|
|
225
|
+
return `${output.slice(0, head)}\n[… ${omitted} characters omitted …]\n${output.slice(-tail)}`;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export interface ShellToolContext {
|
|
229
|
+
provider: ShellProvider;
|
|
230
|
+
sandboxId: string;
|
|
231
|
+
/** The session's project folder, read at each call (checkouts move). */
|
|
232
|
+
root(): string;
|
|
233
|
+
state: ShellState;
|
|
234
|
+
/** The Environment's budget for one foreground command, in seconds. */
|
|
235
|
+
budgetSeconds?: number;
|
|
236
|
+
/**
|
|
237
|
+
* The session's environment files (ADRs 0206, 0212), from the project
|
|
238
|
+
* folder or absolute: every command loads each that exists first.
|
|
239
|
+
*/
|
|
240
|
+
envFiles?: readonly string[];
|
|
241
|
+
/**
|
|
242
|
+
* Fires when the agent should stop waiting (ADR 0264): a message was
|
|
243
|
+
* steered into its turn. Read at each call: it is replaced as it fires.
|
|
244
|
+
*/
|
|
245
|
+
stopWaiting(): AbortSignal;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
type BackgroundStatus = "running" | "finished" | "stopped";
|
|
249
|
+
|
|
250
|
+
function backgroundStatus(result: {
|
|
251
|
+
status: "running" | "exited";
|
|
252
|
+
signal: string | null;
|
|
253
|
+
}): BackgroundStatus {
|
|
254
|
+
if (result.status === "running") return "running";
|
|
255
|
+
return result.signal ? "stopped" : "finished";
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* The shell tools of the built-in harness: `bash`, and where the sandbox
|
|
260
|
+
* runs background processes, the background commands every Work harness
|
|
261
|
+
* knows (ADR 0155): run_background_command, read_background_output and
|
|
262
|
+
* stop_background_command. On the desktop the host supplies those as
|
|
263
|
+
* workspace tools in visible terminals instead (ADR 0174).
|
|
264
|
+
*/
|
|
265
|
+
export function shellTools(context: ShellToolContext): Record<string, Tool> {
|
|
266
|
+
const budgetSeconds = context.budgetSeconds ?? SHELL_DEFAULT_BUDGET_SECONDS;
|
|
267
|
+
const budgetMs = budgetSeconds * 1_000;
|
|
268
|
+
const processes = context.provider.processes;
|
|
269
|
+
const bash = tool({
|
|
270
|
+
description: `Run a shell command and wait for it to finish. The working directory persists between calls (a \`cd\` carries over); it starts in the project folder. Output combines stdout and stderr; long output keeps its start and end. Default timeout ${SHELL_DEFAULT_TIMEOUT_MS / 1000}s, at most ${budgetSeconds}s; a command that runs out of time is stopped. For servers, watchers and anything long-lived, use run_background_command instead${processes ? "" : " when it is available"}. Quote paths with spaces. Prefer read/edit/write for files.`,
|
|
271
|
+
inputSchema: z.object({
|
|
272
|
+
command: z.string().describe("The command to run"),
|
|
273
|
+
description: z
|
|
274
|
+
.string()
|
|
275
|
+
.optional()
|
|
276
|
+
.describe(
|
|
277
|
+
"What this command does in 5-10 plain words, e.g. 'Run the test suite'. Shown to the person as what you're doing.",
|
|
278
|
+
),
|
|
279
|
+
timeout: z
|
|
280
|
+
.number()
|
|
281
|
+
.int()
|
|
282
|
+
.positive()
|
|
283
|
+
.max(budgetMs)
|
|
284
|
+
.optional()
|
|
285
|
+
.describe(`Milliseconds (max ${budgetMs})`),
|
|
286
|
+
}),
|
|
287
|
+
execute: async ({ command, timeout }, { abortSignal }) =>
|
|
288
|
+
runShell({
|
|
289
|
+
provider: context.provider,
|
|
290
|
+
sandboxId: context.sandboxId,
|
|
291
|
+
root: context.root(),
|
|
292
|
+
state: context.state,
|
|
293
|
+
command,
|
|
294
|
+
budgetSeconds,
|
|
295
|
+
...(timeout !== undefined ? { timeoutMs: timeout } : {}),
|
|
296
|
+
...(abortSignal ? { signal: abortSignal } : {}),
|
|
297
|
+
...(context.envFiles ? { envFiles: context.envFiles } : {}),
|
|
298
|
+
}),
|
|
299
|
+
});
|
|
300
|
+
if (!processes) return { bash };
|
|
301
|
+
|
|
302
|
+
const background = () => {
|
|
303
|
+
context.state.background ??= new Map();
|
|
304
|
+
return context.state.background;
|
|
305
|
+
};
|
|
306
|
+
const owned = (id: string) => {
|
|
307
|
+
const entry = background().get(id);
|
|
308
|
+
if (!entry)
|
|
309
|
+
throw new Error(
|
|
310
|
+
`No background command '${id}' in this chat. Start one with run_background_command.`,
|
|
311
|
+
);
|
|
312
|
+
return entry;
|
|
313
|
+
};
|
|
314
|
+
const report = (followed: FollowProcessResult) => ({
|
|
315
|
+
status: backgroundStatus(followed),
|
|
316
|
+
exitCode: followed.exitCode,
|
|
317
|
+
output: followed.output,
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
return {
|
|
321
|
+
bash,
|
|
322
|
+
run_background_command: tool({
|
|
323
|
+
description:
|
|
324
|
+
"Start a long-running command (a dev server, a watcher, a slow build or test run, anything you would otherwise wait on) in the background and keep working. It runs in this chat's workspace, keeps running after this turn, and is stopped when the chat is closed. Returns its id, status, and first output (a quick failure shows up here). Follow it with read_background_output, which can wait for it to finish or print a line; end it with stop_background_command. Use bash for quick commands.",
|
|
325
|
+
inputSchema: z.object({
|
|
326
|
+
command: z.string().describe("The shell command to run"),
|
|
327
|
+
description: z
|
|
328
|
+
.string()
|
|
329
|
+
.describe(
|
|
330
|
+
"What it does in 3-8 plain words, e.g. 'Start the dev server'. Shown to the person.",
|
|
331
|
+
),
|
|
332
|
+
}),
|
|
333
|
+
execute: async ({ command, description }, { abortSignal }) => {
|
|
334
|
+
if (!command.trim()) throw new Error("Empty command.");
|
|
335
|
+
const root = context.root();
|
|
336
|
+
// Started in the project folder, so it loads the secrets from
|
|
337
|
+
// there, then where the shell is.
|
|
338
|
+
const started = await processes.startProcess({
|
|
339
|
+
sandboxId: context.sandboxId,
|
|
340
|
+
command: [
|
|
341
|
+
...commandPrelude({
|
|
342
|
+
root,
|
|
343
|
+
cwd: context.state.cwd ?? root,
|
|
344
|
+
...(context.envFiles ? { envFiles: context.envFiles } : {}),
|
|
345
|
+
}),
|
|
346
|
+
command,
|
|
347
|
+
].join("\n"),
|
|
348
|
+
cwd: root,
|
|
349
|
+
...(description.trim() ? { name: description.trim() } : {}),
|
|
350
|
+
});
|
|
351
|
+
background().set(started.processId, { cursor: 0 });
|
|
352
|
+
const settled = await followProcess({
|
|
353
|
+
processes,
|
|
354
|
+
sandboxId: context.sandboxId,
|
|
355
|
+
processId: started.processId,
|
|
356
|
+
cursor: 0,
|
|
357
|
+
timeoutMs: START_SETTLE_MS,
|
|
358
|
+
outputLimit: SHELL_OUTPUT_LIMIT,
|
|
359
|
+
pollMs: 1_000,
|
|
360
|
+
...(abortSignal ? { signal: abortSignal } : {}),
|
|
361
|
+
});
|
|
362
|
+
owned(started.processId).cursor = settled.cursor;
|
|
363
|
+
return { id: started.processId, ...report(settled) };
|
|
364
|
+
},
|
|
365
|
+
}),
|
|
366
|
+
read_background_output: tool({
|
|
367
|
+
description: `Read a background command's output since your last read, with its status (running, finished, stopped) and exit code. Pass wait_seconds to block until it prints something new or finishes, when you have nothing else to do meanwhile. Add wait_for, a regular expression, to keep waiting until an output line matches (e.g. 'ready on|listening|error'); matched returns that line. Waits last at most ${budgetSeconds}s, and end early when a message reaches you; wait again for work that takes longer.`,
|
|
368
|
+
inputSchema: z.object({
|
|
369
|
+
id: z.string().describe("The id run_background_command returned"),
|
|
370
|
+
wait_seconds: z
|
|
371
|
+
.number()
|
|
372
|
+
.int()
|
|
373
|
+
.min(0)
|
|
374
|
+
.max(budgetSeconds)
|
|
375
|
+
.optional()
|
|
376
|
+
.describe("Block up to this long for new output or the end"),
|
|
377
|
+
wait_for: z
|
|
378
|
+
.string()
|
|
379
|
+
.optional()
|
|
380
|
+
.describe(
|
|
381
|
+
"A regular expression; with wait_seconds, wait until an output line matches",
|
|
382
|
+
),
|
|
383
|
+
}),
|
|
384
|
+
execute: async ({ id, wait_seconds, wait_for }, { abortSignal }) => {
|
|
385
|
+
const entry = owned(id);
|
|
386
|
+
const until = wait_for ? pattern(wait_for) : "output";
|
|
387
|
+
const followed = await followProcess({
|
|
388
|
+
processes,
|
|
389
|
+
sandboxId: context.sandboxId,
|
|
390
|
+
processId: id,
|
|
391
|
+
cursor: entry.cursor,
|
|
392
|
+
timeoutMs: (wait_seconds ?? 0) * 1_000,
|
|
393
|
+
until,
|
|
394
|
+
outputLimit: SHELL_OUTPUT_LIMIT,
|
|
395
|
+
signal: abortSignal
|
|
396
|
+
? AbortSignal.any([abortSignal, context.stopWaiting()])
|
|
397
|
+
: context.stopWaiting(),
|
|
398
|
+
});
|
|
399
|
+
entry.cursor = followed.cursor;
|
|
400
|
+
return {
|
|
401
|
+
...report(followed),
|
|
402
|
+
...(followed.matched !== undefined
|
|
403
|
+
? { matched: followed.matched }
|
|
404
|
+
: {}),
|
|
405
|
+
...(followed.aborted && !abortSignal?.aborted
|
|
406
|
+
? { note: STOPPED_WAITING_NOTE }
|
|
407
|
+
: {}),
|
|
408
|
+
};
|
|
409
|
+
},
|
|
410
|
+
}),
|
|
411
|
+
stop_background_command: tool({
|
|
412
|
+
description:
|
|
413
|
+
"Stop a background command (interrupt, then kill whatever it left running) and return its last output.",
|
|
414
|
+
inputSchema: z.object({
|
|
415
|
+
id: z.string().describe("The id run_background_command returned"),
|
|
416
|
+
}),
|
|
417
|
+
execute: async ({ id }) => {
|
|
418
|
+
const entry = owned(id);
|
|
419
|
+
const stopped = await stopProcess({
|
|
420
|
+
processes,
|
|
421
|
+
sandboxId: context.sandboxId,
|
|
422
|
+
processId: id,
|
|
423
|
+
cursor: entry.cursor,
|
|
424
|
+
});
|
|
425
|
+
entry.cursor = stopped.cursor;
|
|
426
|
+
return report(stopped);
|
|
427
|
+
},
|
|
428
|
+
}),
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* End every background command this chat still runs: a closed chat leaves
|
|
434
|
+
* nothing behind, even before its sandbox is destroyed. Best effort.
|
|
435
|
+
*/
|
|
436
|
+
export async function stopBackgroundCommands(args: {
|
|
437
|
+
provider: ShellProvider;
|
|
438
|
+
sandboxId: string;
|
|
439
|
+
state: ShellState;
|
|
440
|
+
}): Promise<void> {
|
|
441
|
+
const processes = args.provider.processes;
|
|
442
|
+
const ids = [...(args.state.background?.keys() ?? [])];
|
|
443
|
+
args.state.background?.clear();
|
|
444
|
+
if (!processes || ids.length === 0) return;
|
|
445
|
+
await Promise.all(
|
|
446
|
+
ids.map((processId) =>
|
|
447
|
+
processes
|
|
448
|
+
.signalProcess({
|
|
449
|
+
sandboxId: args.sandboxId,
|
|
450
|
+
processId,
|
|
451
|
+
signal: "SIGKILL",
|
|
452
|
+
})
|
|
453
|
+
.catch(() => undefined),
|
|
454
|
+
),
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function pattern(source: string): RegExp {
|
|
459
|
+
try {
|
|
460
|
+
return new RegExp(source);
|
|
461
|
+
} catch (error) {
|
|
462
|
+
throw new Error(
|
|
463
|
+
`wait_for is not a valid regular expression: ${error instanceof Error ? error.message : String(error)}`,
|
|
464
|
+
);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function quote(value: string): string {
|
|
469
|
+
return `'${value.replaceAll("'", `'\\''`)}'`;
|
|
470
|
+
}
|