@catamorphic/ai-sdk 0.0.0-stage → 0.1.0-alpha.31
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/dist/index.js
ADDED
|
@@ -0,0 +1,2166 @@
|
|
|
1
|
+
// src/adapter.ts
|
|
2
|
+
import path2 from "node:path";
|
|
3
|
+
import {
|
|
4
|
+
RequestClosedError
|
|
5
|
+
} from "@catamorphic/agent-protocol/runner";
|
|
6
|
+
import {
|
|
7
|
+
connectMcpServer
|
|
8
|
+
} from "@catamorphic/mcp";
|
|
9
|
+
import {
|
|
10
|
+
isMediaAttachment,
|
|
11
|
+
positiveTokenCount,
|
|
12
|
+
reasoningHeading,
|
|
13
|
+
renderUserMessage
|
|
14
|
+
} from "@catamorphic/sandbox";
|
|
15
|
+
import {
|
|
16
|
+
stepCountIs,
|
|
17
|
+
ToolLoopAgent
|
|
18
|
+
} from "ai";
|
|
19
|
+
import { z as z4 } from "zod";
|
|
20
|
+
|
|
21
|
+
// src/errors.ts
|
|
22
|
+
import { APICallError, RetryError } from "ai";
|
|
23
|
+
var KIND_SIGNATURES = [
|
|
24
|
+
{ kind: "auth", pattern: /\buser not found\b/i },
|
|
25
|
+
{ kind: "auth", pattern: /\binvalid x-api-key\b/i },
|
|
26
|
+
{ kind: "auth", pattern: /\bauthentication[_ ]error\b/i },
|
|
27
|
+
{ kind: "auth", pattern: /\bincorrect api key\b/i },
|
|
28
|
+
{ kind: "auth", pattern: /\binvalid api key\b/i },
|
|
29
|
+
{ kind: "auth", pattern: /\bno auth credentials\b/i },
|
|
30
|
+
{ kind: "auth", pattern: /\bunauthorized\b/i },
|
|
31
|
+
{ kind: "model_incompat", pattern: /\bsignature\b/i },
|
|
32
|
+
{ kind: "model_incompat", pattern: /\bthinking.{0,40}block/i },
|
|
33
|
+
{ kind: "model_incompat", pattern: /\bencrypted.{0,20}(reasoning|content)/i },
|
|
34
|
+
{ kind: "model_incompat", pattern: /\breasoning.{0,40}not supported/i },
|
|
35
|
+
{ kind: "rate_limit", pattern: /\brate.?limit/i },
|
|
36
|
+
{ kind: "rate_limit", pattern: /\btoo many requests\b/i },
|
|
37
|
+
{ kind: "rate_limit", pattern: /\bquota\b/i },
|
|
38
|
+
{ kind: "unavailable", pattern: /\boverloaded\b/i },
|
|
39
|
+
{ kind: "unavailable", pattern: /\bservice unavailable\b/i },
|
|
40
|
+
{ kind: "unavailable", pattern: /\binternal server error\b/i },
|
|
41
|
+
{ kind: "unavailable", pattern: /\bECONN(RESET|REFUSED)\b/ },
|
|
42
|
+
{ kind: "unavailable", pattern: /\bETIMEDOUT\b|\bENOTFOUND\b/ },
|
|
43
|
+
{ kind: "unavailable", pattern: /\bfetch failed\b/i }
|
|
44
|
+
];
|
|
45
|
+
function classifyModelError(error) {
|
|
46
|
+
const cause = RetryError.isInstance(error) ? error.lastError : error;
|
|
47
|
+
const message = errorMessage(cause);
|
|
48
|
+
if (APICallError.isInstance(cause)) {
|
|
49
|
+
const text = `${cause.message}
|
|
50
|
+
${cause.responseBody ?? ""}`;
|
|
51
|
+
const kind = statusKind(cause.statusCode) ?? signatureKind(text);
|
|
52
|
+
return { message, ...kind ? { kind } : {}, providerRejected: true };
|
|
53
|
+
}
|
|
54
|
+
const kind = signatureKind(message);
|
|
55
|
+
return {
|
|
56
|
+
message,
|
|
57
|
+
...kind ? { kind } : {},
|
|
58
|
+
providerRejected: Boolean(kind)
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function statusKind(status) {
|
|
62
|
+
if (status === 401 || status === 403)
|
|
63
|
+
return "auth";
|
|
64
|
+
if (status === 429)
|
|
65
|
+
return "rate_limit";
|
|
66
|
+
if (status === 408 || status === 529 || status !== undefined && status >= 500)
|
|
67
|
+
return "unavailable";
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
function signatureKind(text) {
|
|
71
|
+
return KIND_SIGNATURES.find(({ pattern }) => pattern.test(text))?.kind;
|
|
72
|
+
}
|
|
73
|
+
function errorMessage(error) {
|
|
74
|
+
return error instanceof Error ? error.message : String(error);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// src/telemetry.ts
|
|
78
|
+
import {
|
|
79
|
+
emitLog,
|
|
80
|
+
getMeter,
|
|
81
|
+
getTracer,
|
|
82
|
+
SeverityNumber
|
|
83
|
+
} from "@catamorphic/otel";
|
|
84
|
+
import {
|
|
85
|
+
context,
|
|
86
|
+
SpanKind,
|
|
87
|
+
SpanStatusCode,
|
|
88
|
+
trace
|
|
89
|
+
} from "@opentelemetry/api";
|
|
90
|
+
var scope = "@catamorphic/ai-sdk";
|
|
91
|
+
var durationBuckets = [
|
|
92
|
+
0.01,
|
|
93
|
+
0.02,
|
|
94
|
+
0.04,
|
|
95
|
+
0.08,
|
|
96
|
+
0.16,
|
|
97
|
+
0.32,
|
|
98
|
+
0.64,
|
|
99
|
+
1.28,
|
|
100
|
+
2.56,
|
|
101
|
+
5.12,
|
|
102
|
+
10.24,
|
|
103
|
+
20.48,
|
|
104
|
+
40.96,
|
|
105
|
+
81.92
|
|
106
|
+
];
|
|
107
|
+
function agentTelemetry(args) {
|
|
108
|
+
const tracer = getTracer(scope);
|
|
109
|
+
const model = typeof args.model === "string" ? args.model : args.model.modelId;
|
|
110
|
+
const provider = typeof args.model === "string" ? undefined : args.model.provider.split(".")[0];
|
|
111
|
+
const agentAttributes = {
|
|
112
|
+
"gen_ai.operation.name": "invoke_agent",
|
|
113
|
+
"gen_ai.agent.name": "ai-sdk",
|
|
114
|
+
"gen_ai.request.model": model,
|
|
115
|
+
...provider ? { "gen_ai.provider.name": provider } : {}
|
|
116
|
+
};
|
|
117
|
+
const root = tracer.startSpan("invoke_agent ai-sdk", {
|
|
118
|
+
attributes: {
|
|
119
|
+
...agentAttributes,
|
|
120
|
+
...args.userId ? { "user.id": args.userId } : {},
|
|
121
|
+
"gen_ai.conversation.id": args.sessionId,
|
|
122
|
+
"catamorphic.agent.session.id": args.sessionId,
|
|
123
|
+
...args.projectId ? { "catamorphic.project.id": args.projectId } : {},
|
|
124
|
+
...args.turnId ? { "catamorphic.agent.turn.id": args.turnId } : {}
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
const rootContext = trace.setSpan(context.active(), root);
|
|
128
|
+
const meter = context.with(rootContext, () => getMeter(scope));
|
|
129
|
+
const histogram = (name, unit = "s", boundaries = durationBuckets) => meter.createHistogram(name, {
|
|
130
|
+
unit,
|
|
131
|
+
advice: { explicitBucketBoundaries: boundaries }
|
|
132
|
+
});
|
|
133
|
+
const durations = histogram("gen_ai.client.operation.duration");
|
|
134
|
+
const tokens = histogram("gen_ai.client.token.usage", "{token}", [
|
|
135
|
+
1,
|
|
136
|
+
4,
|
|
137
|
+
16,
|
|
138
|
+
64,
|
|
139
|
+
256,
|
|
140
|
+
1024,
|
|
141
|
+
4096,
|
|
142
|
+
16384,
|
|
143
|
+
65536,
|
|
144
|
+
262144,
|
|
145
|
+
1048576,
|
|
146
|
+
4194304,
|
|
147
|
+
16777216,
|
|
148
|
+
67108864
|
|
149
|
+
]);
|
|
150
|
+
const firstChunk = histogram("gen_ai.client.operation.time_to_first_chunk");
|
|
151
|
+
const toolDurations = histogram("gen_ai.execute_tool.duration");
|
|
152
|
+
const invocationDuration = histogram("gen_ai.invoke_agent.duration");
|
|
153
|
+
const began = performance.now();
|
|
154
|
+
const calls = new Map;
|
|
155
|
+
const tools = new Map;
|
|
156
|
+
let failure;
|
|
157
|
+
let ended = false;
|
|
158
|
+
let modelCalls = 0;
|
|
159
|
+
let toolCalls = 0;
|
|
160
|
+
const fail = (span, error) => {
|
|
161
|
+
const type = error instanceof Error ? error.name : "_OTHER";
|
|
162
|
+
span.setAttribute("error.type", type);
|
|
163
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
164
|
+
return type;
|
|
165
|
+
};
|
|
166
|
+
const finishPending = (pending, metric, error) => {
|
|
167
|
+
if (error) {
|
|
168
|
+
pending.span.setAttribute("error.type", error);
|
|
169
|
+
pending.span.setStatus({ code: SpanStatusCode.ERROR });
|
|
170
|
+
}
|
|
171
|
+
context.with(trace.setSpan(rootContext, pending.span), () => metric.record((performance.now() - pending.started) / 1000, {
|
|
172
|
+
...pending.attributes,
|
|
173
|
+
...error ? { "error.type": error } : {}
|
|
174
|
+
}));
|
|
175
|
+
pending.span.end();
|
|
176
|
+
};
|
|
177
|
+
const integration = {
|
|
178
|
+
onLanguageModelCallStart(event) {
|
|
179
|
+
const attributes = {
|
|
180
|
+
"gen_ai.operation.name": "chat",
|
|
181
|
+
"gen_ai.provider.name": event.provider.split(".")[0] ?? event.provider,
|
|
182
|
+
"gen_ai.request.model": event.modelId
|
|
183
|
+
};
|
|
184
|
+
modelCalls += 1;
|
|
185
|
+
calls.set(event.callId, {
|
|
186
|
+
span: tracer.startSpan(`chat ${event.modelId}`, { kind: SpanKind.CLIENT, attributes }, rootContext),
|
|
187
|
+
started: performance.now(),
|
|
188
|
+
attributes
|
|
189
|
+
});
|
|
190
|
+
},
|
|
191
|
+
async executeLanguageModelCall({ callId, execute }) {
|
|
192
|
+
const pending = calls.get(callId);
|
|
193
|
+
try {
|
|
194
|
+
return await context.with(pending ? trace.setSpan(rootContext, pending.span) : rootContext, execute);
|
|
195
|
+
} catch (error) {
|
|
196
|
+
if (pending && calls.delete(callId)) {
|
|
197
|
+
finishPending(pending, durations, error instanceof Error && error.name === "AbortError" ? undefined : fail(pending.span, error));
|
|
198
|
+
}
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
},
|
|
202
|
+
onLanguageModelCallEnd(event) {
|
|
203
|
+
const pending = calls.get(event.callId);
|
|
204
|
+
if (!pending)
|
|
205
|
+
return;
|
|
206
|
+
calls.delete(event.callId);
|
|
207
|
+
pending.span.setAttributes({
|
|
208
|
+
"gen_ai.response.id": event.responseId,
|
|
209
|
+
"gen_ai.response.finish_reasons": [event.finishReason]
|
|
210
|
+
});
|
|
211
|
+
context.with(trace.setSpan(rootContext, pending.span), () => {
|
|
212
|
+
for (const [kind, count] of [
|
|
213
|
+
["input", event.usage.inputTokens],
|
|
214
|
+
["output", event.usage.outputTokens]
|
|
215
|
+
]) {
|
|
216
|
+
if (typeof count !== "number" || !Number.isFinite(count) || count < 0)
|
|
217
|
+
continue;
|
|
218
|
+
pending.span.setAttribute(`gen_ai.usage.${kind}_tokens`, count);
|
|
219
|
+
tokens.record(count, {
|
|
220
|
+
...pending.attributes,
|
|
221
|
+
"gen_ai.token.type": kind
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
for (const [attribute, count] of [
|
|
225
|
+
[
|
|
226
|
+
"gen_ai.usage.cache_read.input_tokens",
|
|
227
|
+
event.usage.inputTokenDetails.cacheReadTokens
|
|
228
|
+
],
|
|
229
|
+
[
|
|
230
|
+
"gen_ai.usage.cache_write.input_tokens",
|
|
231
|
+
event.usage.inputTokenDetails.cacheWriteTokens
|
|
232
|
+
],
|
|
233
|
+
[
|
|
234
|
+
"gen_ai.usage.reasoning.output_tokens",
|
|
235
|
+
event.usage.outputTokenDetails.reasoningTokens
|
|
236
|
+
]
|
|
237
|
+
]) {
|
|
238
|
+
if (typeof count === "number" && Number.isFinite(count) && count >= 0)
|
|
239
|
+
pending.span.setAttribute(attribute, count);
|
|
240
|
+
}
|
|
241
|
+
const first = event.performance.timeToFirstOutputMs;
|
|
242
|
+
if (first !== undefined && Number.isFinite(first) && first >= 0)
|
|
243
|
+
firstChunk.record(first / 1000, pending.attributes);
|
|
244
|
+
});
|
|
245
|
+
finishPending(pending, durations);
|
|
246
|
+
},
|
|
247
|
+
onToolExecutionStart(event) {
|
|
248
|
+
toolCalls += 1;
|
|
249
|
+
const attributes = {
|
|
250
|
+
"gen_ai.tool.name": event.toolCall.toolName,
|
|
251
|
+
"gen_ai.tool.type": "function",
|
|
252
|
+
"gen_ai.agent.name": "ai-sdk"
|
|
253
|
+
};
|
|
254
|
+
tools.set(event.toolCall.toolCallId, {
|
|
255
|
+
span: tracer.startSpan(`execute_tool ${event.toolCall.toolName}`, {
|
|
256
|
+
attributes: {
|
|
257
|
+
...attributes,
|
|
258
|
+
"gen_ai.operation.name": "execute_tool",
|
|
259
|
+
"gen_ai.tool.call.id": event.toolCall.toolCallId
|
|
260
|
+
}
|
|
261
|
+
}, rootContext),
|
|
262
|
+
started: performance.now(),
|
|
263
|
+
attributes
|
|
264
|
+
});
|
|
265
|
+
},
|
|
266
|
+
executeTool({ toolCallId, execute }) {
|
|
267
|
+
const span = tools.get(toolCallId)?.span;
|
|
268
|
+
return context.with(span ? trace.setSpan(rootContext, span) : rootContext, execute);
|
|
269
|
+
},
|
|
270
|
+
onToolExecutionEnd(event) {
|
|
271
|
+
const pending = tools.get(event.toolCall.toolCallId);
|
|
272
|
+
if (!pending)
|
|
273
|
+
return;
|
|
274
|
+
tools.delete(event.toolCall.toolCallId);
|
|
275
|
+
const error = event.toolOutput.type === "tool-error" ? fail(pending.span, event.toolOutput.error) : undefined;
|
|
276
|
+
finishPending(pending, toolDurations, error);
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
return {
|
|
280
|
+
settings: {
|
|
281
|
+
isEnabled: true,
|
|
282
|
+
recordInputs: false,
|
|
283
|
+
recordOutputs: false,
|
|
284
|
+
integrations: integration
|
|
285
|
+
},
|
|
286
|
+
run(fn) {
|
|
287
|
+
return context.with(rootContext, fn);
|
|
288
|
+
},
|
|
289
|
+
fail(error) {
|
|
290
|
+
failure = fail(root, error);
|
|
291
|
+
},
|
|
292
|
+
finish({ cancelled = false } = {}) {
|
|
293
|
+
if (ended)
|
|
294
|
+
return;
|
|
295
|
+
ended = true;
|
|
296
|
+
root.setAttribute("catamorphic.agent.outcome", cancelled ? "cancelled" : failure ? "error" : "completed");
|
|
297
|
+
for (const pending of calls.values())
|
|
298
|
+
finishPending(pending, durations, failure ?? (cancelled ? undefined : "_OTHER"));
|
|
299
|
+
for (const pending of tools.values())
|
|
300
|
+
finishPending(pending, toolDurations, failure ?? (cancelled ? undefined : "_OTHER"));
|
|
301
|
+
calls.clear();
|
|
302
|
+
tools.clear();
|
|
303
|
+
context.with(rootContext, () => {
|
|
304
|
+
emitLog({
|
|
305
|
+
scope,
|
|
306
|
+
body: "Agent turn settled",
|
|
307
|
+
severity: failure ? SeverityNumber.ERROR : SeverityNumber.INFO,
|
|
308
|
+
attributes: {
|
|
309
|
+
"catamorphic.agent.outcome": cancelled ? "cancelled" : failure ? "error" : "completed",
|
|
310
|
+
...failure ? { "error.type": failure } : {}
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
invocationDuration.record((performance.now() - began) / 1000, {
|
|
314
|
+
...agentAttributes,
|
|
315
|
+
...failure ? { "error.type": failure } : {}
|
|
316
|
+
});
|
|
317
|
+
histogram("gen_ai.invoke_agent.model_calls", "{call}", [1, 2, 4, 8, 16, 32, 64, 128]).record(modelCalls, { "gen_ai.agent.name": "ai-sdk" });
|
|
318
|
+
histogram("gen_ai.invoke_agent.tool_calls", "{call}", [1, 2, 4, 8, 16, 32, 64, 128]).record(toolCalls, { "gen_ai.agent.name": "ai-sdk" });
|
|
319
|
+
});
|
|
320
|
+
root.end();
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// src/thread.ts
|
|
326
|
+
import { modelMessageSchema } from "ai";
|
|
327
|
+
import { z } from "zod";
|
|
328
|
+
var entrySchema = z.discriminatedUnion("kind", [
|
|
329
|
+
z.object({
|
|
330
|
+
v: z.literal(1),
|
|
331
|
+
kind: z.literal("turn"),
|
|
332
|
+
ref: z.string(),
|
|
333
|
+
input: z.array(modelMessageSchema),
|
|
334
|
+
drop: z.number().int().min(0).optional()
|
|
335
|
+
}),
|
|
336
|
+
z.object({
|
|
337
|
+
v: z.literal(1),
|
|
338
|
+
kind: z.literal("step"),
|
|
339
|
+
model: z.string().optional(),
|
|
340
|
+
messages: z.array(modelMessageSchema)
|
|
341
|
+
}),
|
|
342
|
+
z.object({
|
|
343
|
+
v: z.literal(1),
|
|
344
|
+
kind: z.literal("turn_end"),
|
|
345
|
+
ref: z.string(),
|
|
346
|
+
status: z.enum(["completed", "failed", "interrupted"])
|
|
347
|
+
})
|
|
348
|
+
]);
|
|
349
|
+
function parseThreadEntries(entries) {
|
|
350
|
+
return entries.map((entry, index) => {
|
|
351
|
+
const parsed = entrySchema.safeParse(entry);
|
|
352
|
+
if (!parsed.success)
|
|
353
|
+
throw new Error(`The stored conversation has an entry this agent cannot read (entry ${index + 1}): ${parsed.error.message}`);
|
|
354
|
+
return parsed.data;
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
function storedEntries(entry) {
|
|
358
|
+
const encoded = toJsonValue(entry);
|
|
359
|
+
if (JSON.stringify(encoded).length <= STORED_ENTRY_CHARS)
|
|
360
|
+
return [encoded];
|
|
361
|
+
if (entry.kind === "step" && entry.messages.length > 1)
|
|
362
|
+
return entry.messages.flatMap((message) => storedEntries({ ...entry, messages: [message] }));
|
|
363
|
+
return [withoutLargeMedia(encoded)];
|
|
364
|
+
}
|
|
365
|
+
var STORED_ENTRY_CHARS = 256 * 1024;
|
|
366
|
+
var STORED_MEDIA_CHARS = 64 * 1024;
|
|
367
|
+
var MEDIA_PART_TYPES = new Set(["image", "file", "image-data", "file-data"]);
|
|
368
|
+
function withoutLargeMedia(value) {
|
|
369
|
+
if (Array.isArray(value))
|
|
370
|
+
return value.map(withoutLargeMedia);
|
|
371
|
+
if (value === null || typeof value !== "object")
|
|
372
|
+
return value;
|
|
373
|
+
if (typeof value.type === "string" && MEDIA_PART_TYPES.has(value.type) && JSON.stringify(value).length > STORED_MEDIA_CHARS)
|
|
374
|
+
return {
|
|
375
|
+
type: "text",
|
|
376
|
+
text: "[Media omitted from the stored conversation: it was too large to keep.]"
|
|
377
|
+
};
|
|
378
|
+
const object = {};
|
|
379
|
+
for (const [key, field] of Object.entries(value))
|
|
380
|
+
object[key] = withoutLargeMedia(field);
|
|
381
|
+
return object;
|
|
382
|
+
}
|
|
383
|
+
function foldThread(input) {
|
|
384
|
+
const messages = [];
|
|
385
|
+
let lastTurnInputEnd;
|
|
386
|
+
for (const entry of input.entries) {
|
|
387
|
+
if (entry.kind === "turn") {
|
|
388
|
+
if (entry.drop)
|
|
389
|
+
messages.splice(messages.length - entry.drop);
|
|
390
|
+
messages.push(...entry.input);
|
|
391
|
+
lastTurnInputEnd = messages.length;
|
|
392
|
+
} else if (entry.kind === "step") {
|
|
393
|
+
const foreign = input.sanitize === true || input.model !== undefined && entry.model !== undefined && entry.model !== input.model;
|
|
394
|
+
messages.push(...foreign ? stripReasoning(entry.messages) : entry.messages);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return {
|
|
398
|
+
messages,
|
|
399
|
+
...lastTurnInputEnd === undefined ? {} : { lastTurnInputEnd }
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
function entriesThroughTurn(entries, ref) {
|
|
403
|
+
for (let end = entries.length - 1;end >= 0; end -= 1) {
|
|
404
|
+
const entry = entries[end];
|
|
405
|
+
if (entry?.kind === "turn_end" && entry.ref === ref)
|
|
406
|
+
return entries.slice(0, end + 1);
|
|
407
|
+
}
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
function stripReasoning(messages) {
|
|
411
|
+
return messages.map((message) => {
|
|
412
|
+
if (message.role !== "assistant" || !Array.isArray(message.content))
|
|
413
|
+
return message;
|
|
414
|
+
return {
|
|
415
|
+
...message,
|
|
416
|
+
content: message.content.filter((part) => part.type !== "reasoning" && part.type !== "reasoning-file")
|
|
417
|
+
};
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
function toJsonValue(value) {
|
|
421
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
422
|
+
return value;
|
|
423
|
+
if (typeof value === "number")
|
|
424
|
+
return Number.isFinite(value) ? value : null;
|
|
425
|
+
if (value instanceof Uint8Array)
|
|
426
|
+
return Buffer.from(value).toString("base64");
|
|
427
|
+
if (value instanceof ArrayBuffer)
|
|
428
|
+
return Buffer.from(new Uint8Array(value)).toString("base64");
|
|
429
|
+
if (value instanceof URL)
|
|
430
|
+
return value.href;
|
|
431
|
+
if (value instanceof Date)
|
|
432
|
+
return value.toISOString();
|
|
433
|
+
if (Array.isArray(value))
|
|
434
|
+
return value.map(toJsonValue);
|
|
435
|
+
if (typeof value === "object") {
|
|
436
|
+
const object = {};
|
|
437
|
+
for (const [key, field] of Object.entries(value)) {
|
|
438
|
+
if (field === undefined || typeof field === "function")
|
|
439
|
+
continue;
|
|
440
|
+
object[key] = toJsonValue(field);
|
|
441
|
+
}
|
|
442
|
+
return object;
|
|
443
|
+
}
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// src/tools.ts
|
|
448
|
+
import { createHash } from "node:crypto";
|
|
449
|
+
import path from "node:path";
|
|
450
|
+
import {
|
|
451
|
+
flattenToolResult
|
|
452
|
+
} from "@catamorphic/mcp";
|
|
453
|
+
import {
|
|
454
|
+
agentQuestionInputSchema,
|
|
455
|
+
agentToolResult,
|
|
456
|
+
extraToolResult
|
|
457
|
+
} from "@catamorphic/sandbox";
|
|
458
|
+
import { dynamicTool, jsonSchema, tool as tool2 } from "ai";
|
|
459
|
+
import { z as z3 } from "zod";
|
|
460
|
+
|
|
461
|
+
// src/shell.ts
|
|
462
|
+
import crypto from "node:crypto";
|
|
463
|
+
import {
|
|
464
|
+
followProcess,
|
|
465
|
+
STOPPED_WAITING_NOTE
|
|
466
|
+
} from "@catamorphic/sandbox";
|
|
467
|
+
import { tool } from "ai";
|
|
468
|
+
import { z as z2 } from "zod";
|
|
469
|
+
var SHELL_DEFAULT_TIMEOUT_MS = 120000;
|
|
470
|
+
var SHELL_DEFAULT_BUDGET_SECONDS = 600;
|
|
471
|
+
var SHELL_OUTPUT_LIMIT = 30000;
|
|
472
|
+
var START_SETTLE_MS = 3000;
|
|
473
|
+
var STOP_GRACE_MS = 2000;
|
|
474
|
+
function commandPrelude(input) {
|
|
475
|
+
return [
|
|
476
|
+
...(input.envFiles ?? []).map((file) => `if [ -f ${quote(file)} ]; then . ${quote(file)}; fi`),
|
|
477
|
+
`cd ${quote(input.cwd)} 2>/dev/null || cd ${quote(input.root)} 2>/dev/null`
|
|
478
|
+
];
|
|
479
|
+
}
|
|
480
|
+
async function runShell(input) {
|
|
481
|
+
const marker = `__catamorphic_cwd_${crypto.randomUUID().replaceAll("-", "")}__`;
|
|
482
|
+
const cwd = input.state.cwd ?? input.root;
|
|
483
|
+
const script = [
|
|
484
|
+
...commandPrelude({
|
|
485
|
+
root: input.root,
|
|
486
|
+
cwd,
|
|
487
|
+
...input.envFiles ? { envFiles: input.envFiles } : {}
|
|
488
|
+
}),
|
|
489
|
+
input.command,
|
|
490
|
+
"__catamorphic_status=$?",
|
|
491
|
+
`printf '\\n${marker}%s\\n' "$PWD"`,
|
|
492
|
+
"exit $__catamorphic_status"
|
|
493
|
+
].join(`
|
|
494
|
+
`);
|
|
495
|
+
const budgetMs = (input.budgetSeconds ?? SHELL_DEFAULT_BUDGET_SECONDS) * 1000;
|
|
496
|
+
const timeoutMs = Math.min(Math.max(input.timeoutMs ?? SHELL_DEFAULT_TIMEOUT_MS, 1000), budgetMs);
|
|
497
|
+
const processes = input.provider.processes;
|
|
498
|
+
const result = processes ? await waitedCommand({
|
|
499
|
+
processes,
|
|
500
|
+
sandboxId: input.sandboxId,
|
|
501
|
+
root: input.root,
|
|
502
|
+
script,
|
|
503
|
+
timeoutMs,
|
|
504
|
+
...input.signal ? { signal: input.signal } : {}
|
|
505
|
+
}) : await input.provider.executeCommand(input.sandboxId, script, {
|
|
506
|
+
cwd: input.root,
|
|
507
|
+
timeout: Math.ceil(timeoutMs / 1000),
|
|
508
|
+
...input.signal ? { signal: input.signal } : {}
|
|
509
|
+
}).then((executed) => ({
|
|
510
|
+
exitCode: executed.exitCode,
|
|
511
|
+
output: truncateOutput(executed.result),
|
|
512
|
+
note: undefined
|
|
513
|
+
}));
|
|
514
|
+
const at = result.output.lastIndexOf(marker);
|
|
515
|
+
if (at !== -1) {
|
|
516
|
+
const directory = result.output.slice(at + marker.length).split(`
|
|
517
|
+
`, 1)[0];
|
|
518
|
+
if (directory)
|
|
519
|
+
input.state.cwd = directory;
|
|
520
|
+
}
|
|
521
|
+
const output = (at === -1 ? result.output : result.output.slice(0, at)).replace(/\n+$/, "");
|
|
522
|
+
return {
|
|
523
|
+
exitCode: result.exitCode,
|
|
524
|
+
output: result.note ? `${output}
|
|
525
|
+
${result.note}`.trimStart() : output
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
async function waitedCommand(args) {
|
|
529
|
+
const started = await args.processes.startProcess({
|
|
530
|
+
sandboxId: args.sandboxId,
|
|
531
|
+
command: args.script,
|
|
532
|
+
cwd: args.root
|
|
533
|
+
});
|
|
534
|
+
const followed = await followProcess({
|
|
535
|
+
processes: args.processes,
|
|
536
|
+
sandboxId: args.sandboxId,
|
|
537
|
+
processId: started.processId,
|
|
538
|
+
cursor: 0,
|
|
539
|
+
timeoutMs: args.timeoutMs,
|
|
540
|
+
outputLimit: SHELL_OUTPUT_LIMIT,
|
|
541
|
+
...args.signal ? { signal: args.signal } : {}
|
|
542
|
+
});
|
|
543
|
+
if (!followed.timedOut && !followed.aborted)
|
|
544
|
+
return { exitCode: followed.exitCode ?? 1, output: followed.output };
|
|
545
|
+
const stopped = await stopProcess({
|
|
546
|
+
processes: args.processes,
|
|
547
|
+
sandboxId: args.sandboxId,
|
|
548
|
+
processId: started.processId,
|
|
549
|
+
cursor: followed.cursor
|
|
550
|
+
}).catch(() => {
|
|
551
|
+
return;
|
|
552
|
+
});
|
|
553
|
+
return {
|
|
554
|
+
exitCode: followed.timedOut ? 124 : 130,
|
|
555
|
+
output: followed.output + (stopped?.output ?? ""),
|
|
556
|
+
note: followed.timedOut ? `Command timed out after ${Math.round(args.timeoutMs / 1000)}s and was stopped. Use run_background_command for longer work.` : "Command was cancelled."
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
async function stopProcess(args) {
|
|
560
|
+
await args.processes.signalProcess({
|
|
561
|
+
sandboxId: args.sandboxId,
|
|
562
|
+
processId: args.processId,
|
|
563
|
+
signal: "SIGTERM"
|
|
564
|
+
});
|
|
565
|
+
const settled = await followProcess({
|
|
566
|
+
processes: args.processes,
|
|
567
|
+
sandboxId: args.sandboxId,
|
|
568
|
+
processId: args.processId,
|
|
569
|
+
cursor: args.cursor,
|
|
570
|
+
timeoutMs: STOP_GRACE_MS,
|
|
571
|
+
outputLimit: SHELL_OUTPUT_LIMIT,
|
|
572
|
+
pollMs: 500
|
|
573
|
+
});
|
|
574
|
+
if (settled.status === "exited")
|
|
575
|
+
return settled;
|
|
576
|
+
await args.processes.signalProcess({
|
|
577
|
+
sandboxId: args.sandboxId,
|
|
578
|
+
processId: args.processId,
|
|
579
|
+
signal: "SIGKILL"
|
|
580
|
+
});
|
|
581
|
+
const killed = await followProcess({
|
|
582
|
+
processes: args.processes,
|
|
583
|
+
sandboxId: args.sandboxId,
|
|
584
|
+
processId: args.processId,
|
|
585
|
+
cursor: settled.cursor,
|
|
586
|
+
timeoutMs: STOP_GRACE_MS,
|
|
587
|
+
outputLimit: SHELL_OUTPUT_LIMIT,
|
|
588
|
+
pollMs: 500
|
|
589
|
+
});
|
|
590
|
+
return { ...killed, output: settled.output + killed.output };
|
|
591
|
+
}
|
|
592
|
+
function truncateOutput(output, limit = SHELL_OUTPUT_LIMIT) {
|
|
593
|
+
if (output.length <= limit)
|
|
594
|
+
return output;
|
|
595
|
+
const head = Math.floor(limit / 3);
|
|
596
|
+
const tail = limit - head;
|
|
597
|
+
const omitted = output.length - head - tail;
|
|
598
|
+
return `${output.slice(0, head)}
|
|
599
|
+
[… ${omitted} characters omitted …]
|
|
600
|
+
${output.slice(-tail)}`;
|
|
601
|
+
}
|
|
602
|
+
function backgroundStatus(result) {
|
|
603
|
+
if (result.status === "running")
|
|
604
|
+
return "running";
|
|
605
|
+
return result.signal ? "stopped" : "finished";
|
|
606
|
+
}
|
|
607
|
+
function shellTools(context) {
|
|
608
|
+
const budgetSeconds = context.budgetSeconds ?? SHELL_DEFAULT_BUDGET_SECONDS;
|
|
609
|
+
const budgetMs = budgetSeconds * 1000;
|
|
610
|
+
const processes = context.provider.processes;
|
|
611
|
+
const bash = tool({
|
|
612
|
+
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.`,
|
|
613
|
+
inputSchema: z2.object({
|
|
614
|
+
command: z2.string().describe("The command to run"),
|
|
615
|
+
description: z2.string().optional().describe("What this command does in 5-10 plain words, e.g. 'Run the test suite'. Shown to the person as what you're doing."),
|
|
616
|
+
timeout: z2.number().int().positive().max(budgetMs).optional().describe(`Milliseconds (max ${budgetMs})`)
|
|
617
|
+
}),
|
|
618
|
+
execute: async ({ command, timeout }, { abortSignal }) => runShell({
|
|
619
|
+
provider: context.provider,
|
|
620
|
+
sandboxId: context.sandboxId,
|
|
621
|
+
root: context.root(),
|
|
622
|
+
state: context.state,
|
|
623
|
+
command,
|
|
624
|
+
budgetSeconds,
|
|
625
|
+
...timeout !== undefined ? { timeoutMs: timeout } : {},
|
|
626
|
+
...abortSignal ? { signal: abortSignal } : {},
|
|
627
|
+
...context.envFiles ? { envFiles: context.envFiles } : {}
|
|
628
|
+
})
|
|
629
|
+
});
|
|
630
|
+
if (!processes)
|
|
631
|
+
return { bash };
|
|
632
|
+
const background = () => {
|
|
633
|
+
context.state.background ??= new Map;
|
|
634
|
+
return context.state.background;
|
|
635
|
+
};
|
|
636
|
+
const owned = (id) => {
|
|
637
|
+
const entry = background().get(id);
|
|
638
|
+
if (!entry)
|
|
639
|
+
throw new Error(`No background command '${id}' in this chat. Start one with run_background_command.`);
|
|
640
|
+
return entry;
|
|
641
|
+
};
|
|
642
|
+
const report = (followed) => ({
|
|
643
|
+
status: backgroundStatus(followed),
|
|
644
|
+
exitCode: followed.exitCode,
|
|
645
|
+
output: followed.output
|
|
646
|
+
});
|
|
647
|
+
return {
|
|
648
|
+
bash,
|
|
649
|
+
run_background_command: tool({
|
|
650
|
+
description: "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.",
|
|
651
|
+
inputSchema: z2.object({
|
|
652
|
+
command: z2.string().describe("The shell command to run"),
|
|
653
|
+
description: z2.string().describe("What it does in 3-8 plain words, e.g. 'Start the dev server'. Shown to the person.")
|
|
654
|
+
}),
|
|
655
|
+
execute: async ({ command, description }, { abortSignal }) => {
|
|
656
|
+
if (!command.trim())
|
|
657
|
+
throw new Error("Empty command.");
|
|
658
|
+
const root = context.root();
|
|
659
|
+
const started = await processes.startProcess({
|
|
660
|
+
sandboxId: context.sandboxId,
|
|
661
|
+
command: [
|
|
662
|
+
...commandPrelude({
|
|
663
|
+
root,
|
|
664
|
+
cwd: context.state.cwd ?? root,
|
|
665
|
+
...context.envFiles ? { envFiles: context.envFiles } : {}
|
|
666
|
+
}),
|
|
667
|
+
command
|
|
668
|
+
].join(`
|
|
669
|
+
`),
|
|
670
|
+
cwd: root,
|
|
671
|
+
...description.trim() ? { name: description.trim() } : {}
|
|
672
|
+
});
|
|
673
|
+
background().set(started.processId, { cursor: 0 });
|
|
674
|
+
const settled = await followProcess({
|
|
675
|
+
processes,
|
|
676
|
+
sandboxId: context.sandboxId,
|
|
677
|
+
processId: started.processId,
|
|
678
|
+
cursor: 0,
|
|
679
|
+
timeoutMs: START_SETTLE_MS,
|
|
680
|
+
outputLimit: SHELL_OUTPUT_LIMIT,
|
|
681
|
+
pollMs: 1000,
|
|
682
|
+
...abortSignal ? { signal: abortSignal } : {}
|
|
683
|
+
});
|
|
684
|
+
owned(started.processId).cursor = settled.cursor;
|
|
685
|
+
return { id: started.processId, ...report(settled) };
|
|
686
|
+
}
|
|
687
|
+
}),
|
|
688
|
+
read_background_output: tool({
|
|
689
|
+
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.`,
|
|
690
|
+
inputSchema: z2.object({
|
|
691
|
+
id: z2.string().describe("The id run_background_command returned"),
|
|
692
|
+
wait_seconds: z2.number().int().min(0).max(budgetSeconds).optional().describe("Block up to this long for new output or the end"),
|
|
693
|
+
wait_for: z2.string().optional().describe("A regular expression; with wait_seconds, wait until an output line matches")
|
|
694
|
+
}),
|
|
695
|
+
execute: async ({ id, wait_seconds, wait_for }, { abortSignal }) => {
|
|
696
|
+
const entry = owned(id);
|
|
697
|
+
const until = wait_for ? pattern(wait_for) : "output";
|
|
698
|
+
const followed = await followProcess({
|
|
699
|
+
processes,
|
|
700
|
+
sandboxId: context.sandboxId,
|
|
701
|
+
processId: id,
|
|
702
|
+
cursor: entry.cursor,
|
|
703
|
+
timeoutMs: (wait_seconds ?? 0) * 1000,
|
|
704
|
+
until,
|
|
705
|
+
outputLimit: SHELL_OUTPUT_LIMIT,
|
|
706
|
+
signal: abortSignal ? AbortSignal.any([abortSignal, context.stopWaiting()]) : context.stopWaiting()
|
|
707
|
+
});
|
|
708
|
+
entry.cursor = followed.cursor;
|
|
709
|
+
return {
|
|
710
|
+
...report(followed),
|
|
711
|
+
...followed.matched !== undefined ? { matched: followed.matched } : {},
|
|
712
|
+
...followed.aborted && !abortSignal?.aborted ? { note: STOPPED_WAITING_NOTE } : {}
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
}),
|
|
716
|
+
stop_background_command: tool({
|
|
717
|
+
description: "Stop a background command (interrupt, then kill whatever it left running) and return its last output.",
|
|
718
|
+
inputSchema: z2.object({
|
|
719
|
+
id: z2.string().describe("The id run_background_command returned")
|
|
720
|
+
}),
|
|
721
|
+
execute: async ({ id }) => {
|
|
722
|
+
const entry = owned(id);
|
|
723
|
+
const stopped = await stopProcess({
|
|
724
|
+
processes,
|
|
725
|
+
sandboxId: context.sandboxId,
|
|
726
|
+
processId: id,
|
|
727
|
+
cursor: entry.cursor
|
|
728
|
+
});
|
|
729
|
+
entry.cursor = stopped.cursor;
|
|
730
|
+
return report(stopped);
|
|
731
|
+
}
|
|
732
|
+
})
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
async function stopBackgroundCommands(args) {
|
|
736
|
+
const processes = args.provider.processes;
|
|
737
|
+
const ids = [...args.state.background?.keys() ?? []];
|
|
738
|
+
args.state.background?.clear();
|
|
739
|
+
if (!processes || ids.length === 0)
|
|
740
|
+
return;
|
|
741
|
+
await Promise.all(ids.map((processId) => processes.signalProcess({
|
|
742
|
+
sandboxId: args.sandboxId,
|
|
743
|
+
processId,
|
|
744
|
+
signal: "SIGKILL"
|
|
745
|
+
}).catch(() => {
|
|
746
|
+
return;
|
|
747
|
+
})));
|
|
748
|
+
}
|
|
749
|
+
function pattern(source) {
|
|
750
|
+
try {
|
|
751
|
+
return new RegExp(source);
|
|
752
|
+
} catch (error) {
|
|
753
|
+
throw new Error(`wait_for is not a valid regular expression: ${error instanceof Error ? error.message : String(error)}`);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
function quote(value) {
|
|
757
|
+
return `'${value.replaceAll("'", `'\\''`)}'`;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// src/tools.ts
|
|
761
|
+
var MAX_TOOL_OUTPUT_LENGTH = 1e5;
|
|
762
|
+
var EXA_MCP_URL = "https://mcp.exa.ai/mcp";
|
|
763
|
+
var WEBFETCH_MAX_BYTES = 5 * 1024 * 1024;
|
|
764
|
+
var WEBFETCH_TIMEOUT_MS = 30000;
|
|
765
|
+
var ASK_USER_DESCRIPTION = `Ask the user one or more questions. When the tool allows blocking=false, use it to continue independent work while awaiting answers. ALWAYS use this tool instead of writing questions as plain text whenever you are asking the user something and their answer shapes what you do next. Use it when (1) you are blocked on a decision that is genuinely the user's to make, one you cannot resolve from the request, the project, or sensible defaults, e.g. choosing between data sources, schedules, external services, or destructive vs. safe variants of an operation; or (2) the user asks you to interview them, gather their preferences, or otherwise requests that you ask them questions. A request like "ask me some questions" should go through this tool, batching up to 4 questions per call and calling it again for follow-ups. For routine implementation choices, pick a sensible default and state it instead of asking. Each option needs a concise label and a description explaining its effects, implications, or trade-offs; for open-ended questions offer plausible example answers as options. The user can always answer with free text instead of picking one. If you recommend an option, make it the first one and append " (Recommended)" to its label. Do not use it to ask "should I proceed?" or to confirm work you already described.`;
|
|
766
|
+
var SET_TITLE_DESCRIPTION = "Set the title of this conversation as shown in the user's chat list and tabs. Call it once near the start of a new conversation with a concise, specific title (2-5 words, sentence case, no trailing punctuation) describing what the conversation is about. Call it again whenever the current title no longer describes the conversation: the topic moved on, the scope changed, or the original title turned out to be wrong. Don't re-title for minor detours. Examples: 'Daily sales report workflow', 'Drafting onboarding doc', 'Fixing checkout bug', 'Getting to know you'.";
|
|
767
|
+
function conversationTools(input) {
|
|
768
|
+
return {
|
|
769
|
+
tools: {
|
|
770
|
+
set_title: tool2({
|
|
771
|
+
description: SET_TITLE_DESCRIPTION,
|
|
772
|
+
inputSchema: z3.object({
|
|
773
|
+
title: z3.string().min(1).max(80).describe("The new conversation title (2-5 words)")
|
|
774
|
+
}),
|
|
775
|
+
execute: async ({ title }) => `Conversation titled: ${title}`
|
|
776
|
+
}),
|
|
777
|
+
ask_user: tool2({
|
|
778
|
+
description: ASK_USER_DESCRIPTION,
|
|
779
|
+
inputSchema: agentQuestionInputSchema,
|
|
780
|
+
execute: ({ questions, blocking }, { toolCallId, abortSignal }) => input.ask({
|
|
781
|
+
questions,
|
|
782
|
+
blocking,
|
|
783
|
+
toolCallId,
|
|
784
|
+
...abortSignal ? { abortSignal } : {}
|
|
785
|
+
})
|
|
786
|
+
}),
|
|
787
|
+
websearch: tool2({
|
|
788
|
+
description: "Search the web and return results with content excerpts optimized for reading. Use it for up-to-date information, documentation, or anything outside the project.",
|
|
789
|
+
inputSchema: z3.object({
|
|
790
|
+
query: z3.string().describe("Web search query"),
|
|
791
|
+
numResults: z3.number().int().positive().max(20).optional().describe("Number of results to return (default 8)")
|
|
792
|
+
}),
|
|
793
|
+
execute: async ({ query, numResults }) => truncateToolOutput(await exaWebSearch(query, numResults ?? 8))
|
|
794
|
+
}),
|
|
795
|
+
webfetch: tool2({
|
|
796
|
+
description: "Fetch a URL and return its content as text. Use it to read pages found via websearch or URLs provided by the user.",
|
|
797
|
+
inputSchema: z3.object({
|
|
798
|
+
url: z3.string().describe("The http(s) URL to fetch")
|
|
799
|
+
}),
|
|
800
|
+
execute: async ({ url }) => truncateToolOutput(await webFetch(url))
|
|
801
|
+
})
|
|
802
|
+
},
|
|
803
|
+
meta: new Map([
|
|
804
|
+
["set_title", { kind: "title" }],
|
|
805
|
+
["ask_user", { kind: "ask" }],
|
|
806
|
+
["websearch", { kind: "tool", server: null, source: "builtin" }],
|
|
807
|
+
["webfetch", { kind: "tool", server: null, source: "builtin" }]
|
|
808
|
+
])
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
function workspaceTools(context) {
|
|
812
|
+
let mutationQueue = Promise.resolve();
|
|
813
|
+
const serializeMutation = async (operation) => {
|
|
814
|
+
const result = mutationQueue.then(operation, operation);
|
|
815
|
+
mutationQueue = result.then(() => {
|
|
816
|
+
return;
|
|
817
|
+
}, () => {
|
|
818
|
+
return;
|
|
819
|
+
});
|
|
820
|
+
return result;
|
|
821
|
+
};
|
|
822
|
+
const resolveReadablePath = (filePath) => {
|
|
823
|
+
const resolved = path.posix.resolve(path.posix.resolve(context.workingDirectory), filePath);
|
|
824
|
+
if (context.readableRoots.some((root) => within(resolved, root)))
|
|
825
|
+
return resolved;
|
|
826
|
+
return resolveProjectPath(context.workingDirectory, filePath);
|
|
827
|
+
};
|
|
828
|
+
const relative = (absolutePath) => path.posix.relative(context.workingDirectory, absolutePath);
|
|
829
|
+
const shell = shellTools({
|
|
830
|
+
provider: context.provider,
|
|
831
|
+
sandboxId: context.sandboxId,
|
|
832
|
+
root: () => context.workingDirectory,
|
|
833
|
+
state: context.shell,
|
|
834
|
+
...context.budgetSeconds ? { budgetSeconds: context.budgetSeconds } : {},
|
|
835
|
+
...context.envFiles ? { envFiles: context.envFiles } : {},
|
|
836
|
+
stopWaiting: context.stopWaiting
|
|
837
|
+
});
|
|
838
|
+
const tools = {
|
|
839
|
+
read: tool2({
|
|
840
|
+
description: "Read a UTF-8 text file from the project, or a file the user attached by its absolute path.",
|
|
841
|
+
inputSchema: z3.object({
|
|
842
|
+
path: z3.string().describe("Project-relative or absolute file path")
|
|
843
|
+
}),
|
|
844
|
+
execute: async ({ path: filePath }) => truncateToolOutput(await context.provider.downloadFile(context.sandboxId, resolveReadablePath(filePath)))
|
|
845
|
+
}),
|
|
846
|
+
write: tool2({
|
|
847
|
+
description: "Create or replace a UTF-8 text file in the project.",
|
|
848
|
+
inputSchema: z3.object({
|
|
849
|
+
path: z3.string().describe("Project-relative or absolute file path"),
|
|
850
|
+
content: z3.string()
|
|
851
|
+
}),
|
|
852
|
+
execute: async ({ path: filePath, content }) => serializeMutation(async () => {
|
|
853
|
+
const relativePath = relative(resolveProjectPath(context.workingDirectory, filePath));
|
|
854
|
+
await context.provider.uploadFiles(context.sandboxId, { [relativePath]: content }, context.workingDirectory);
|
|
855
|
+
return `Wrote ${relativePath}`;
|
|
856
|
+
})
|
|
857
|
+
}),
|
|
858
|
+
edit: tool2({
|
|
859
|
+
description: "Replace one exact string occurrence in a project file.",
|
|
860
|
+
inputSchema: z3.object({
|
|
861
|
+
path: z3.string().describe("Project-relative or absolute file path"),
|
|
862
|
+
oldText: z3.string().describe("Exact text to replace"),
|
|
863
|
+
newText: z3.string().describe("Replacement text")
|
|
864
|
+
}),
|
|
865
|
+
execute: async ({ path: filePath, oldText, newText }) => serializeMutation(async () => {
|
|
866
|
+
const absolutePath = resolveProjectPath(context.workingDirectory, filePath);
|
|
867
|
+
const content = await context.provider.downloadFile(context.sandboxId, absolutePath);
|
|
868
|
+
const first = content.indexOf(oldText);
|
|
869
|
+
if (first === -1)
|
|
870
|
+
throw new Error(`Text not found in ${filePath}`);
|
|
871
|
+
if (content.indexOf(oldText, first + oldText.length) !== -1)
|
|
872
|
+
throw new Error(`Text occurs more than once in ${filePath}`);
|
|
873
|
+
const updated = `${content.slice(0, first)}${newText}${content.slice(first + oldText.length)}`;
|
|
874
|
+
const relativePath = relative(absolutePath);
|
|
875
|
+
await context.provider.uploadFiles(context.sandboxId, { [relativePath]: updated }, context.workingDirectory);
|
|
876
|
+
return `Edited ${relativePath}`;
|
|
877
|
+
})
|
|
878
|
+
}),
|
|
879
|
+
...shell
|
|
880
|
+
};
|
|
881
|
+
const meta = new Map([
|
|
882
|
+
["read", { kind: "tool", server: null, source: "builtin" }],
|
|
883
|
+
["write", { kind: "file", change: null }],
|
|
884
|
+
["edit", { kind: "file", change: "modified" }],
|
|
885
|
+
["bash", { kind: "command" }]
|
|
886
|
+
]);
|
|
887
|
+
for (const name of Object.keys(shell))
|
|
888
|
+
if (!meta.has(name))
|
|
889
|
+
meta.set(name, { kind: "tool", server: null, source: "builtin" });
|
|
890
|
+
return { tools, meta };
|
|
891
|
+
}
|
|
892
|
+
function resolveProjectPath(workingDirectory, filePath) {
|
|
893
|
+
const root = path.posix.resolve(workingDirectory);
|
|
894
|
+
const resolved = path.posix.resolve(root, filePath);
|
|
895
|
+
if (!within(resolved, root))
|
|
896
|
+
throw new Error(`Path escapes the project working directory: ${filePath}`);
|
|
897
|
+
return resolved;
|
|
898
|
+
}
|
|
899
|
+
function within(resolved, directory) {
|
|
900
|
+
const root = path.posix.resolve(directory);
|
|
901
|
+
return resolved === root || resolved.startsWith(`${root}/`);
|
|
902
|
+
}
|
|
903
|
+
function hostTools(input) {
|
|
904
|
+
const tools = {};
|
|
905
|
+
const meta = new Map;
|
|
906
|
+
for (const descriptor of input.descriptors) {
|
|
907
|
+
tools[descriptor.name] = dynamicTool({
|
|
908
|
+
description: descriptor.description,
|
|
909
|
+
inputSchema: toolInputSchema(descriptor.inputSchema),
|
|
910
|
+
toModelOutput: ({ output }) => hostModelOutput(output),
|
|
911
|
+
execute: (args, { toolCallId, abortSignal }) => input.call({
|
|
912
|
+
name: descriptor.name,
|
|
913
|
+
input: args,
|
|
914
|
+
toolCallId,
|
|
915
|
+
...abortSignal ? { abortSignal } : {}
|
|
916
|
+
})
|
|
917
|
+
});
|
|
918
|
+
meta.set(descriptor.name, {
|
|
919
|
+
kind: "tool",
|
|
920
|
+
server: descriptor.server ?? "workspace",
|
|
921
|
+
source: "host"
|
|
922
|
+
});
|
|
923
|
+
}
|
|
924
|
+
return { tools, meta };
|
|
925
|
+
}
|
|
926
|
+
var hostToolResultSchema = z3.object({
|
|
927
|
+
content: z3.array(z3.discriminatedUnion("type", [
|
|
928
|
+
z3.object({ type: z3.literal("text"), text: z3.string() }),
|
|
929
|
+
z3.object({
|
|
930
|
+
type: z3.literal("image"),
|
|
931
|
+
data: z3.string(),
|
|
932
|
+
mimeType: z3.string()
|
|
933
|
+
})
|
|
934
|
+
])),
|
|
935
|
+
structured: z3.unknown().optional(),
|
|
936
|
+
isError: z3.boolean().optional()
|
|
937
|
+
});
|
|
938
|
+
function parseHostToolResult(output) {
|
|
939
|
+
const parsed = hostToolResultSchema.safeParse(output);
|
|
940
|
+
return parsed.success ? parsed.data : undefined;
|
|
941
|
+
}
|
|
942
|
+
function hostModelOutput(output) {
|
|
943
|
+
const result = parseHostToolResult(output);
|
|
944
|
+
if (!result)
|
|
945
|
+
return { type: "text", value: JSON.stringify(output ?? null) };
|
|
946
|
+
const text = result.content.filter((part) => part.type === "text").map((part) => part.text).join(`
|
|
947
|
+
`);
|
|
948
|
+
if (result.isError)
|
|
949
|
+
return { type: "error-text", value: text };
|
|
950
|
+
return {
|
|
951
|
+
type: "content",
|
|
952
|
+
value: [
|
|
953
|
+
...result.content.map((part) => part.type === "image" ? {
|
|
954
|
+
type: "file",
|
|
955
|
+
data: { type: "data", data: part.data },
|
|
956
|
+
mediaType: part.mimeType
|
|
957
|
+
} : { type: "text", text: truncateToolOutput(part.text) }),
|
|
958
|
+
...result.structured !== undefined && !result.content.some((part) => part.type === "text") ? [{ type: "text", text: JSON.stringify(result.structured) }] : []
|
|
959
|
+
]
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
var MODEL_TOOL_NAME_MAX = 64;
|
|
963
|
+
function mcpModelToolName(args) {
|
|
964
|
+
const safeServer = args.server.replace(/[^A-Za-z0-9-]+/g, "_");
|
|
965
|
+
const safeTool = args.tool.replace(/[^A-Za-z0-9_-]+/g, "_");
|
|
966
|
+
const name = `mcp__${safeServer}__${safeTool}`;
|
|
967
|
+
if (name.length <= MODEL_TOOL_NAME_MAX && !Object.hasOwn(args.taken, name))
|
|
968
|
+
return name;
|
|
969
|
+
const hash = createHash("sha256").update(`${args.server}\x00${args.tool}`).digest("hex").slice(0, 8);
|
|
970
|
+
return `${name.slice(0, MODEL_TOOL_NAME_MAX - hash.length - 1)}_${hash}`;
|
|
971
|
+
}
|
|
972
|
+
function mcpTools(input) {
|
|
973
|
+
const tools = {};
|
|
974
|
+
const meta = new Map;
|
|
975
|
+
for (const [serverName, server] of input.servers) {
|
|
976
|
+
for (const info of server.tools) {
|
|
977
|
+
const name = mcpModelToolName({
|
|
978
|
+
server: serverName,
|
|
979
|
+
tool: info.name,
|
|
980
|
+
taken: { ...input.taken, ...tools }
|
|
981
|
+
});
|
|
982
|
+
meta.set(name, { kind: "tool", server: serverName, source: "mcp" });
|
|
983
|
+
tools[name] = dynamicTool({
|
|
984
|
+
description: info.description,
|
|
985
|
+
inputSchema: toolInputSchema(info.inputSchema),
|
|
986
|
+
toModelOutput: ({ output }) => mediaModelOutput(output),
|
|
987
|
+
execute: async (args, { toolCallId, abortSignal }) => {
|
|
988
|
+
const pruned = pruneEmptyOptionalArgs(isRecord(args) ? args : {}, info.inputSchema);
|
|
989
|
+
await input.authorize({
|
|
990
|
+
server: serverName,
|
|
991
|
+
tool: info,
|
|
992
|
+
input: pruned,
|
|
993
|
+
toolCallId,
|
|
994
|
+
...abortSignal ? { abortSignal } : {}
|
|
995
|
+
});
|
|
996
|
+
abortSignal?.throwIfAborted();
|
|
997
|
+
return mcpCallResult(await server.callToolRaw(info.name, pruned));
|
|
998
|
+
}
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
return { tools, meta };
|
|
1003
|
+
}
|
|
1004
|
+
function mcpCallResult(raw) {
|
|
1005
|
+
const blocks = z3.array(z3.unknown()).parse(raw.content ?? []);
|
|
1006
|
+
const media = blocks.flatMap((block) => {
|
|
1007
|
+
const image = z3.object({
|
|
1008
|
+
type: z3.literal("image"),
|
|
1009
|
+
data: z3.string(),
|
|
1010
|
+
mimeType: z3.enum([
|
|
1011
|
+
"image/png",
|
|
1012
|
+
"image/jpeg",
|
|
1013
|
+
"image/webp",
|
|
1014
|
+
"image/gif"
|
|
1015
|
+
])
|
|
1016
|
+
}).safeParse(block);
|
|
1017
|
+
return image.success ? [image.data] : [];
|
|
1018
|
+
});
|
|
1019
|
+
const isError = raw.isError === true;
|
|
1020
|
+
if (media.length > 0 && !isError) {
|
|
1021
|
+
const text = blocks.flatMap((block) => {
|
|
1022
|
+
const part = z3.object({ type: z3.literal("text"), text: z3.string() }).safeParse(block);
|
|
1023
|
+
return part.success ? [{ type: "text", text: truncateToolOutput(part.data.text) }] : [];
|
|
1024
|
+
});
|
|
1025
|
+
if (raw.structuredContent !== undefined)
|
|
1026
|
+
text.push({ type: "text", text: JSON.stringify(raw.structuredContent) });
|
|
1027
|
+
return agentToolResult({ content: [...text, ...media] });
|
|
1028
|
+
}
|
|
1029
|
+
if (raw.structuredContent !== undefined && !isError)
|
|
1030
|
+
return raw.structuredContent;
|
|
1031
|
+
return truncateToolOutput(flattenToolResult({
|
|
1032
|
+
content: blocks.filter(isRecord),
|
|
1033
|
+
...raw.structuredContent !== undefined ? { structuredContent: raw.structuredContent } : {},
|
|
1034
|
+
isError
|
|
1035
|
+
}));
|
|
1036
|
+
}
|
|
1037
|
+
function toolInputSchema(schema) {
|
|
1038
|
+
return jsonSchema(schema);
|
|
1039
|
+
}
|
|
1040
|
+
function pruneEmptyOptionalArgs(input, schema) {
|
|
1041
|
+
const required = new Set(Array.isArray(schema.required) ? schema.required.filter((key) => typeof key === "string") : []);
|
|
1042
|
+
const properties = isRecord(schema.properties) ? schema.properties : {};
|
|
1043
|
+
const pruned = {};
|
|
1044
|
+
for (const [key, value] of Object.entries(input)) {
|
|
1045
|
+
if (required.has(key) || value !== "" && value !== null) {
|
|
1046
|
+
pruned[key] = value;
|
|
1047
|
+
continue;
|
|
1048
|
+
}
|
|
1049
|
+
const property = properties[key];
|
|
1050
|
+
const schemaOf = isRecord(property) ? property : undefined;
|
|
1051
|
+
const meaningful = value === null ? schemaAdmitsNull(schemaOf) : schemaAdmitsEmptyString(schemaOf);
|
|
1052
|
+
if (meaningful)
|
|
1053
|
+
pruned[key] = value;
|
|
1054
|
+
}
|
|
1055
|
+
return pruned;
|
|
1056
|
+
}
|
|
1057
|
+
function schemaAdmitsNull(property) {
|
|
1058
|
+
if (!property)
|
|
1059
|
+
return false;
|
|
1060
|
+
if (property.nullable === true)
|
|
1061
|
+
return true;
|
|
1062
|
+
const type = property.type;
|
|
1063
|
+
if (type === "null" || Array.isArray(type) && type.includes("null"))
|
|
1064
|
+
return true;
|
|
1065
|
+
if (Array.isArray(property.enum) && property.enum.includes(null))
|
|
1066
|
+
return true;
|
|
1067
|
+
for (const branchKey of ["anyOf", "oneOf"]) {
|
|
1068
|
+
const branches = property[branchKey];
|
|
1069
|
+
if (Array.isArray(branches) && branches.some((branch) => schemaAdmitsNull(isRecord(branch) ? branch : undefined)))
|
|
1070
|
+
return true;
|
|
1071
|
+
}
|
|
1072
|
+
return false;
|
|
1073
|
+
}
|
|
1074
|
+
function schemaAdmitsEmptyString(property) {
|
|
1075
|
+
if (!property)
|
|
1076
|
+
return false;
|
|
1077
|
+
const type = property.type;
|
|
1078
|
+
const isString = type === "string" || Array.isArray(type) && type.includes("string");
|
|
1079
|
+
if (!isString)
|
|
1080
|
+
return false;
|
|
1081
|
+
if (Array.isArray(property.enum))
|
|
1082
|
+
return property.enum.includes("");
|
|
1083
|
+
if (typeof property.minLength === "number" && property.minLength > 0)
|
|
1084
|
+
return false;
|
|
1085
|
+
if (property.format !== undefined || property.pattern !== undefined)
|
|
1086
|
+
return false;
|
|
1087
|
+
return true;
|
|
1088
|
+
}
|
|
1089
|
+
function isRecord(value) {
|
|
1090
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1091
|
+
}
|
|
1092
|
+
function truncateToolOutput(output) {
|
|
1093
|
+
if (output.length <= MAX_TOOL_OUTPUT_LENGTH)
|
|
1094
|
+
return output;
|
|
1095
|
+
return `${output.slice(0, MAX_TOOL_OUTPUT_LENGTH)}
|
|
1096
|
+
...[output truncated]`;
|
|
1097
|
+
}
|
|
1098
|
+
function transcriptToolResult(output) {
|
|
1099
|
+
if (!isRecord(output) || output.kind !== "agent-tool-result") {
|
|
1100
|
+
const host = parseHostToolResult(output);
|
|
1101
|
+
if (!host)
|
|
1102
|
+
return output;
|
|
1103
|
+
return {
|
|
1104
|
+
content: host.content.map((part) => part.type === "image" ? { type: "image", mimeType: part.mimeType } : part),
|
|
1105
|
+
...host.structured !== undefined ? { structured: host.structured } : {},
|
|
1106
|
+
...host.isError ? { isError: true } : {}
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1109
|
+
return {
|
|
1110
|
+
content: extraToolResult(output).content.map((part) => part.type === "image" ? { type: "image", mimeType: part.mimeType } : part)
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
function mediaModelOutput(output) {
|
|
1114
|
+
const result = extraToolResult(output);
|
|
1115
|
+
if (result.isError)
|
|
1116
|
+
return {
|
|
1117
|
+
type: "error-text",
|
|
1118
|
+
value: result.content.filter((part) => part.type === "text").map((part) => part.text).join(`
|
|
1119
|
+
`)
|
|
1120
|
+
};
|
|
1121
|
+
return {
|
|
1122
|
+
type: "content",
|
|
1123
|
+
value: result.content.map((part) => part.type === "image" ? {
|
|
1124
|
+
type: "file",
|
|
1125
|
+
data: { type: "data", data: part.data },
|
|
1126
|
+
mediaType: part.mimeType
|
|
1127
|
+
} : part)
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
async function exaWebSearch(query, numResults) {
|
|
1131
|
+
const response = await fetch(EXA_MCP_URL, {
|
|
1132
|
+
method: "POST",
|
|
1133
|
+
headers: {
|
|
1134
|
+
"Content-Type": "application/json",
|
|
1135
|
+
Accept: "application/json, text/event-stream"
|
|
1136
|
+
},
|
|
1137
|
+
body: JSON.stringify({
|
|
1138
|
+
jsonrpc: "2.0",
|
|
1139
|
+
id: 1,
|
|
1140
|
+
method: "tools/call",
|
|
1141
|
+
params: {
|
|
1142
|
+
name: "web_search_exa",
|
|
1143
|
+
arguments: { query, numResults, type: "auto", livecrawl: "fallback" }
|
|
1144
|
+
}
|
|
1145
|
+
}),
|
|
1146
|
+
signal: AbortSignal.timeout(WEBFETCH_TIMEOUT_MS)
|
|
1147
|
+
});
|
|
1148
|
+
if (!response.ok)
|
|
1149
|
+
throw new Error(`Web search failed with status ${response.status}`);
|
|
1150
|
+
const result = parseMcpToolResult(await response.text());
|
|
1151
|
+
return result ?? "No search results found. Try a different query.";
|
|
1152
|
+
}
|
|
1153
|
+
var mcpTextResultSchema = z3.object({
|
|
1154
|
+
result: z3.object({
|
|
1155
|
+
content: z3.array(z3.object({ text: z3.string().optional() })).optional()
|
|
1156
|
+
})
|
|
1157
|
+
});
|
|
1158
|
+
function parseMcpToolResult(body) {
|
|
1159
|
+
const payloads = body.trim().startsWith("{") ? [body.trim()] : body.split(`
|
|
1160
|
+
`).filter((line) => line.startsWith("data: ")).map((line) => line.slice(6));
|
|
1161
|
+
for (const payload of payloads) {
|
|
1162
|
+
try {
|
|
1163
|
+
const data = mcpTextResultSchema.safeParse(JSON.parse(payload));
|
|
1164
|
+
const text = data.success ? data.data.result.content?.find((item) => item.text)?.text : undefined;
|
|
1165
|
+
if (text)
|
|
1166
|
+
return text;
|
|
1167
|
+
} catch {}
|
|
1168
|
+
}
|
|
1169
|
+
return;
|
|
1170
|
+
}
|
|
1171
|
+
async function webFetch(url) {
|
|
1172
|
+
if (!url.startsWith("http://") && !url.startsWith("https://"))
|
|
1173
|
+
throw new Error("URL must start with http:// or https://");
|
|
1174
|
+
const response = await fetch(url, {
|
|
1175
|
+
headers: {
|
|
1176
|
+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",
|
|
1177
|
+
Accept: "text/markdown;q=1.0, text/plain;q=0.9, text/html;q=0.8, */*;q=0.1",
|
|
1178
|
+
"Accept-Language": "en-US,en;q=0.9"
|
|
1179
|
+
},
|
|
1180
|
+
signal: AbortSignal.timeout(WEBFETCH_TIMEOUT_MS),
|
|
1181
|
+
redirect: "follow"
|
|
1182
|
+
});
|
|
1183
|
+
if (!response.ok)
|
|
1184
|
+
throw new Error(`Fetch failed with status ${response.status}`);
|
|
1185
|
+
const contentLength = response.headers.get("content-length");
|
|
1186
|
+
if (contentLength && Number.parseInt(contentLength, 10) > WEBFETCH_MAX_BYTES)
|
|
1187
|
+
throw new Error("Response too large (exceeds 5MB limit)");
|
|
1188
|
+
const buffer = await response.arrayBuffer();
|
|
1189
|
+
if (buffer.byteLength > WEBFETCH_MAX_BYTES)
|
|
1190
|
+
throw new Error("Response too large (exceeds 5MB limit)");
|
|
1191
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
1192
|
+
if (contentType && !/text|json|xml|javascript|markdown|html/i.test(contentType))
|
|
1193
|
+
throw new Error(`Unsupported content type: ${contentType}`);
|
|
1194
|
+
const text = new TextDecoder().decode(buffer);
|
|
1195
|
+
return contentType.includes("html") ? htmlToText(text) : text;
|
|
1196
|
+
}
|
|
1197
|
+
function htmlToText(html) {
|
|
1198
|
+
return html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<!--[\s\S]*?-->/g, "").replace(/<br\s*\/?>/gi, `
|
|
1199
|
+
`).replace(/<\/(p|div|h[1-6]|li|tr|section|article|blockquote|pre)>/gi, `
|
|
1200
|
+
`).replace(/<[^>]+>/g, " ").replace(/ /g, " ").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/[ \t]+/g, " ").replace(/\n{3,}/g, `
|
|
1201
|
+
|
|
1202
|
+
`).trim();
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
// src/adapter.ts
|
|
1206
|
+
var AI_SDK_HARNESS = "ai-sdk";
|
|
1207
|
+
var DEFAULT_INSTRUCTIONS = `You are an agent working with a person in their project folder, which can hold any kind of work: documents, notes, data, code, automations, apps.
|
|
1208
|
+
Use the provided tools to inspect and edit the project in your working directory.
|
|
1209
|
+
Read AGENTS.md and relevant .work/skills/*/SKILL.md and .agents/skills/*/SKILL.md files, when they exist, before making substantial changes.
|
|
1210
|
+
Keep changes focused, run relevant checks, and do not commit changes.
|
|
1211
|
+
At the start of a new conversation, once the topic is clear from the first user message, call set_title with a concise conversation title; update it whenever the current title no longer fits the conversation, but not for minor detours.`;
|
|
1212
|
+
var DEFAULT_MAX_STEPS = 150;
|
|
1213
|
+
var CAPABILITIES = {
|
|
1214
|
+
steer: true,
|
|
1215
|
+
interrupt: true,
|
|
1216
|
+
retry: true,
|
|
1217
|
+
fork: true,
|
|
1218
|
+
rollback: false,
|
|
1219
|
+
questions: true,
|
|
1220
|
+
approvals: true,
|
|
1221
|
+
elicitations: true,
|
|
1222
|
+
toolSearch: false,
|
|
1223
|
+
subagents: false,
|
|
1224
|
+
streamsText: true,
|
|
1225
|
+
streamsReasoning: true,
|
|
1226
|
+
nativeState: "store",
|
|
1227
|
+
ids: { thread: "strong", turn: "strong", item: "none" }
|
|
1228
|
+
};
|
|
1229
|
+
function createAiSdkAdapter(options) {
|
|
1230
|
+
return {
|
|
1231
|
+
id: AI_SDK_HARNESS,
|
|
1232
|
+
capabilities: () => CAPABILITIES,
|
|
1233
|
+
start: (attempt, host, local) => new AiSdkAttempt(options, attempt, host, readLocal(local)).control()
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
class AiSdkAttempt {
|
|
1238
|
+
options;
|
|
1239
|
+
attempt;
|
|
1240
|
+
host;
|
|
1241
|
+
local;
|
|
1242
|
+
abort = new AbortController;
|
|
1243
|
+
failure = new AbortController;
|
|
1244
|
+
failureCause;
|
|
1245
|
+
steers = [];
|
|
1246
|
+
waits = new AbortController;
|
|
1247
|
+
accepting = true;
|
|
1248
|
+
workStarted = false;
|
|
1249
|
+
announced = new Map;
|
|
1250
|
+
text;
|
|
1251
|
+
reasoning = new Map;
|
|
1252
|
+
heading;
|
|
1253
|
+
toolItems = new Map;
|
|
1254
|
+
segments = 0;
|
|
1255
|
+
requests = 0;
|
|
1256
|
+
usage = new UsageTally;
|
|
1257
|
+
model;
|
|
1258
|
+
modelId;
|
|
1259
|
+
workingDirectory;
|
|
1260
|
+
threadRef;
|
|
1261
|
+
turnRef;
|
|
1262
|
+
constructor(options, attempt, host, local) {
|
|
1263
|
+
this.options = options;
|
|
1264
|
+
this.attempt = attempt;
|
|
1265
|
+
this.host = host;
|
|
1266
|
+
this.local = local;
|
|
1267
|
+
this.model = attempt.model && options.resolveModel ? options.resolveModel(attempt.model) : options.model;
|
|
1268
|
+
this.modelId = modelIdOf(this.model);
|
|
1269
|
+
this.workingDirectory = local.sandbox?.workingDirectory ?? attempt.workingDirectory;
|
|
1270
|
+
this.threadRef = attempt.thread.mode === "resume" || attempt.thread.mode === "restore" ? attempt.thread.nativeRef : { id: attempt.thread.providerThreadId, strength: "strong" };
|
|
1271
|
+
this.turnRef = { id: attempt.attemptId, strength: "strong" };
|
|
1272
|
+
if (host.signal.aborted)
|
|
1273
|
+
this.abort.abort();
|
|
1274
|
+
else
|
|
1275
|
+
host.signal.addEventListener("abort", () => this.abort.abort(), {
|
|
1276
|
+
once: true
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
control() {
|
|
1280
|
+
return {
|
|
1281
|
+
steer: async (input) => {
|
|
1282
|
+
if (!this.accepting || this.abort.signal.aborted)
|
|
1283
|
+
return false;
|
|
1284
|
+
this.steers.push(input);
|
|
1285
|
+
this.waits.abort();
|
|
1286
|
+
this.waits = new AbortController;
|
|
1287
|
+
return true;
|
|
1288
|
+
},
|
|
1289
|
+
interrupt: () => this.abort.abort(),
|
|
1290
|
+
finished: this.run()
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
emit(event) {
|
|
1294
|
+
if (event.type === "item.started")
|
|
1295
|
+
this.workStarted = true;
|
|
1296
|
+
this.host.emit(event);
|
|
1297
|
+
}
|
|
1298
|
+
async run() {
|
|
1299
|
+
this.emit({ type: "thread", ref: this.threadRef });
|
|
1300
|
+
const telemetry = agentTelemetry({
|
|
1301
|
+
model: this.model,
|
|
1302
|
+
sessionId: this.attempt.sessionId,
|
|
1303
|
+
projectId: this.attempt.projectId,
|
|
1304
|
+
turnId: this.attempt.turnId,
|
|
1305
|
+
...this.local.userId ? { userId: this.local.userId } : {}
|
|
1306
|
+
});
|
|
1307
|
+
let servers = new Map;
|
|
1308
|
+
let turnStored = false;
|
|
1309
|
+
let status = "completed";
|
|
1310
|
+
let error;
|
|
1311
|
+
try {
|
|
1312
|
+
const folded = await this.history();
|
|
1313
|
+
const turn = this.turnInput(folded);
|
|
1314
|
+
await this.append([turn.entry]);
|
|
1315
|
+
turnStored = true;
|
|
1316
|
+
this.emit({ type: "turn.started", ref: this.turnRef });
|
|
1317
|
+
servers = await this.connectMcp();
|
|
1318
|
+
await this.loop({
|
|
1319
|
+
messages: turn.messages,
|
|
1320
|
+
tools: this.tools(servers),
|
|
1321
|
+
telemetry
|
|
1322
|
+
});
|
|
1323
|
+
if (this.abort.signal.aborted)
|
|
1324
|
+
status = "interrupted";
|
|
1325
|
+
} catch (cause) {
|
|
1326
|
+
if (this.abort.signal.aborted)
|
|
1327
|
+
status = "interrupted";
|
|
1328
|
+
else {
|
|
1329
|
+
status = "failed";
|
|
1330
|
+
const failed = this.failure.signal.aborted ? this.failureCause : cause;
|
|
1331
|
+
telemetry.fail(failed);
|
|
1332
|
+
const classified = classifyModelError(failed);
|
|
1333
|
+
error = {
|
|
1334
|
+
message: classified.message,
|
|
1335
|
+
...classified.kind ? { kind: classified.kind } : {},
|
|
1336
|
+
...classified.providerRejected && !this.workStarted ? { retrySafe: true } : {}
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
this.accepting = false;
|
|
1341
|
+
this.settleAnnounced();
|
|
1342
|
+
this.closeOpenItems(status);
|
|
1343
|
+
telemetry.finish({ cancelled: status === "interrupted" });
|
|
1344
|
+
const usage = this.usage.toUsage(this.attempt.model ?? this.modelId);
|
|
1345
|
+
if (usage)
|
|
1346
|
+
this.emit({ type: "usage", usage });
|
|
1347
|
+
if (turnStored)
|
|
1348
|
+
await this.append([
|
|
1349
|
+
{ v: 1, kind: "turn_end", ref: this.turnRef.id, status }
|
|
1350
|
+
]).catch((cause) => this.emit({
|
|
1351
|
+
type: "diagnostic",
|
|
1352
|
+
level: "warn",
|
|
1353
|
+
message: `The end of this turn was not stored: ${errorMessage(cause)}`
|
|
1354
|
+
}));
|
|
1355
|
+
this.emit({
|
|
1356
|
+
type: "turn.completed",
|
|
1357
|
+
status,
|
|
1358
|
+
...error ? { error } : {},
|
|
1359
|
+
...turnStored ? { ref: this.turnRef } : {}
|
|
1360
|
+
});
|
|
1361
|
+
await Promise.all([...servers.values()].map((server) => server.close().catch(() => {})));
|
|
1362
|
+
}
|
|
1363
|
+
async history() {
|
|
1364
|
+
const thread = this.attempt.thread;
|
|
1365
|
+
const sanitize = this.attempt.options.sanitizeReasoning === true;
|
|
1366
|
+
const fold = (entries) => foldThread({
|
|
1367
|
+
entries,
|
|
1368
|
+
...this.attempt.model ?? this.modelId ? { model: this.attempt.model ?? this.modelId } : {},
|
|
1369
|
+
sanitize
|
|
1370
|
+
});
|
|
1371
|
+
if (thread.mode === "fresh")
|
|
1372
|
+
return { messages: [] };
|
|
1373
|
+
if (thread.mode === "fork") {
|
|
1374
|
+
const own = await this.load();
|
|
1375
|
+
if (own && own.length > 0)
|
|
1376
|
+
return fold(own);
|
|
1377
|
+
const source = await this.load(thread.source.id);
|
|
1378
|
+
if (!source)
|
|
1379
|
+
throw new Error("The conversation to fork from is not stored.");
|
|
1380
|
+
const through = thread.throughTurnRef ? entriesThroughTurn(source, thread.throughTurnRef.id) : source;
|
|
1381
|
+
if (!through)
|
|
1382
|
+
throw new Error("The turn to fork from is not in the stored conversation.");
|
|
1383
|
+
await this.append(through);
|
|
1384
|
+
return fold(through);
|
|
1385
|
+
}
|
|
1386
|
+
const entries = await this.load();
|
|
1387
|
+
if (!entries)
|
|
1388
|
+
throw new Error("This conversation's stored history is missing.");
|
|
1389
|
+
return fold(entries);
|
|
1390
|
+
}
|
|
1391
|
+
turnInput(folded) {
|
|
1392
|
+
const input = this.attempt.input;
|
|
1393
|
+
if (input) {
|
|
1394
|
+
const opening = [
|
|
1395
|
+
...this.attempt.context.trim() ? [{ role: "system", content: this.attempt.context }] : [],
|
|
1396
|
+
userMessage(input)
|
|
1397
|
+
];
|
|
1398
|
+
return {
|
|
1399
|
+
messages: [...folded.messages, ...opening],
|
|
1400
|
+
entry: { v: 1, kind: "turn", ref: this.turnRef.id, input: opening }
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1403
|
+
const end = folded.lastTurnInputEnd;
|
|
1404
|
+
if (end === undefined)
|
|
1405
|
+
throw new Error("There is no earlier turn to retry.");
|
|
1406
|
+
const messages = [...folded.messages];
|
|
1407
|
+
let drop = 0;
|
|
1408
|
+
while (messages.length > end && messages.at(-1)?.role === "assistant") {
|
|
1409
|
+
messages.pop();
|
|
1410
|
+
drop += 1;
|
|
1411
|
+
}
|
|
1412
|
+
return {
|
|
1413
|
+
messages,
|
|
1414
|
+
entry: {
|
|
1415
|
+
v: 1,
|
|
1416
|
+
kind: "turn",
|
|
1417
|
+
ref: this.turnRef.id,
|
|
1418
|
+
input: [],
|
|
1419
|
+
...drop ? { drop } : {}
|
|
1420
|
+
}
|
|
1421
|
+
};
|
|
1422
|
+
}
|
|
1423
|
+
async load(thread) {
|
|
1424
|
+
const entries = await untilAborted(this.host.nativeState.load(thread ? { thread } : {}), this.host.signal);
|
|
1425
|
+
return entries ? parseThreadEntries(entries) : null;
|
|
1426
|
+
}
|
|
1427
|
+
async append(entries) {
|
|
1428
|
+
if (this.host.signal.aborted)
|
|
1429
|
+
return;
|
|
1430
|
+
const stored = entries.flatMap(storedEntries);
|
|
1431
|
+
if (stored.length === 0)
|
|
1432
|
+
return;
|
|
1433
|
+
await untilAborted(this.host.nativeState.append({ entries: stored }), this.host.signal);
|
|
1434
|
+
}
|
|
1435
|
+
instructions() {
|
|
1436
|
+
const plugins = this.attempt.plugins.length ? [
|
|
1437
|
+
"Plugins installed for you (read their files with the read tool):",
|
|
1438
|
+
...this.attempt.plugins.map((plugin) => `- ${plugin.name}: ${plugin.path}`)
|
|
1439
|
+
].join(`
|
|
1440
|
+
`) : undefined;
|
|
1441
|
+
return [
|
|
1442
|
+
DEFAULT_INSTRUCTIONS,
|
|
1443
|
+
this.options.instructions,
|
|
1444
|
+
plugins,
|
|
1445
|
+
this.attempt.systemPrompt
|
|
1446
|
+
].filter((part) => Boolean(part?.trim())).join(`
|
|
1447
|
+
|
|
1448
|
+
`);
|
|
1449
|
+
}
|
|
1450
|
+
async loop(input) {
|
|
1451
|
+
let messages = input.messages;
|
|
1452
|
+
let stepsLeft = this.options.maxSteps ?? DEFAULT_MAX_STEPS;
|
|
1453
|
+
const effort = this.attempt.effort ?? this.options.effort;
|
|
1454
|
+
const signal = AbortSignal.any([this.abort.signal, this.failure.signal]);
|
|
1455
|
+
for (;; ) {
|
|
1456
|
+
let prepared = messages;
|
|
1457
|
+
const agent = new ToolLoopAgent({
|
|
1458
|
+
telemetry: input.telemetry.settings,
|
|
1459
|
+
model: this.model,
|
|
1460
|
+
instructions: this.instructions(),
|
|
1461
|
+
allowSystemInMessages: true,
|
|
1462
|
+
tools: input.tools,
|
|
1463
|
+
prepareStep: async ({ messages: stepMessages }) => {
|
|
1464
|
+
const fresh = this.steers.splice(0);
|
|
1465
|
+
const inserted = fresh.map(userMessage);
|
|
1466
|
+
prepared = [...stepMessages, ...inserted];
|
|
1467
|
+
if (fresh.length > 0) {
|
|
1468
|
+
try {
|
|
1469
|
+
await this.append([
|
|
1470
|
+
{
|
|
1471
|
+
v: 1,
|
|
1472
|
+
kind: "step",
|
|
1473
|
+
...this.modelId ? { model: this.modelId } : {},
|
|
1474
|
+
messages: inserted
|
|
1475
|
+
}
|
|
1476
|
+
]);
|
|
1477
|
+
this.emit({
|
|
1478
|
+
type: "input.consumed",
|
|
1479
|
+
itemIds: fresh.map((steer) => steer.itemId)
|
|
1480
|
+
});
|
|
1481
|
+
} catch (cause) {
|
|
1482
|
+
this.failureCause = cause;
|
|
1483
|
+
this.failure.abort();
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
return { messages: prepared };
|
|
1487
|
+
},
|
|
1488
|
+
onStepFinish: async (step) => {
|
|
1489
|
+
stepsLeft -= 1;
|
|
1490
|
+
messages = [...prepared, ...step.response.messages];
|
|
1491
|
+
const written = step.response.messages;
|
|
1492
|
+
try {
|
|
1493
|
+
await this.append([
|
|
1494
|
+
{
|
|
1495
|
+
v: 1,
|
|
1496
|
+
kind: "step",
|
|
1497
|
+
...this.modelId ? { model: this.modelId } : {},
|
|
1498
|
+
messages: written
|
|
1499
|
+
}
|
|
1500
|
+
]);
|
|
1501
|
+
} catch (cause) {
|
|
1502
|
+
this.failureCause = cause;
|
|
1503
|
+
this.failure.abort();
|
|
1504
|
+
}
|
|
1505
|
+
},
|
|
1506
|
+
stopWhen: stepCountIs(Math.max(1, stepsLeft)),
|
|
1507
|
+
...effort ? { providerOptions: effortProviderOptions(effort) } : {}
|
|
1508
|
+
});
|
|
1509
|
+
const result = await input.telemetry.run(() => agent.stream({ messages, abortSignal: signal }));
|
|
1510
|
+
try {
|
|
1511
|
+
for await (const part of result.stream)
|
|
1512
|
+
this.onPart(part);
|
|
1513
|
+
} finally {
|
|
1514
|
+
this.closeText();
|
|
1515
|
+
this.settleAnnounced();
|
|
1516
|
+
}
|
|
1517
|
+
if (this.failure.signal.aborted)
|
|
1518
|
+
throw this.failureCause;
|
|
1519
|
+
if (this.abort.signal.aborted)
|
|
1520
|
+
return;
|
|
1521
|
+
if (this.steers.length === 0 || stepsLeft <= 0) {
|
|
1522
|
+
this.accepting = false;
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
tools(servers) {
|
|
1528
|
+
const sets = [];
|
|
1529
|
+
const sandbox = this.local.sandbox;
|
|
1530
|
+
if (sandbox)
|
|
1531
|
+
sets.push(workspaceTools({
|
|
1532
|
+
provider: sandbox.provider,
|
|
1533
|
+
sandboxId: sandbox.sandboxId,
|
|
1534
|
+
workingDirectory: this.workingDirectory,
|
|
1535
|
+
readableRoots: [
|
|
1536
|
+
...this.local.readableRoots ?? [],
|
|
1537
|
+
...this.attempt.plugins.map((plugin) => plugin.path)
|
|
1538
|
+
],
|
|
1539
|
+
shell: this.local.shell ?? {},
|
|
1540
|
+
...sandbox.commandBudgetSeconds ? { budgetSeconds: sandbox.commandBudgetSeconds } : {},
|
|
1541
|
+
...sandbox.envFiles ? { envFiles: sandbox.envFiles } : {},
|
|
1542
|
+
stopWaiting: () => this.waits.signal
|
|
1543
|
+
}));
|
|
1544
|
+
sets.push(conversationTools({ ask: (args) => this.askUser(args) }), hostTools({
|
|
1545
|
+
descriptors: this.attempt.hostTools,
|
|
1546
|
+
call: (args) => this.callHostTool(args)
|
|
1547
|
+
}));
|
|
1548
|
+
const tools = {};
|
|
1549
|
+
const meta = new Map;
|
|
1550
|
+
const add = (set) => {
|
|
1551
|
+
for (const [name, entry] of Object.entries(set.tools)) {
|
|
1552
|
+
if (Object.hasOwn(tools, name))
|
|
1553
|
+
continue;
|
|
1554
|
+
tools[name] = this.announcedFirst(entry);
|
|
1555
|
+
const info = set.meta.get(name);
|
|
1556
|
+
if (info)
|
|
1557
|
+
meta.set(name, info);
|
|
1558
|
+
}
|
|
1559
|
+
};
|
|
1560
|
+
for (const set of sets)
|
|
1561
|
+
add(set);
|
|
1562
|
+
add(mcpTools({
|
|
1563
|
+
servers,
|
|
1564
|
+
taken: tools,
|
|
1565
|
+
authorize: (args) => this.authorizeMcp(args)
|
|
1566
|
+
}));
|
|
1567
|
+
this.toolMeta = meta;
|
|
1568
|
+
return tools;
|
|
1569
|
+
}
|
|
1570
|
+
toolMeta = new Map;
|
|
1571
|
+
announcedFirst(entry) {
|
|
1572
|
+
const execute = entry.execute;
|
|
1573
|
+
if (!execute)
|
|
1574
|
+
return entry;
|
|
1575
|
+
return {
|
|
1576
|
+
...entry,
|
|
1577
|
+
execute: async (args, options) => {
|
|
1578
|
+
await this.announcement(options.toolCallId).promise;
|
|
1579
|
+
options.abortSignal?.throwIfAborted();
|
|
1580
|
+
return execute(args, options);
|
|
1581
|
+
}
|
|
1582
|
+
};
|
|
1583
|
+
}
|
|
1584
|
+
announcement(toolCallId) {
|
|
1585
|
+
let entry = this.announced.get(toolCallId);
|
|
1586
|
+
if (!entry) {
|
|
1587
|
+
let resolve = () => {};
|
|
1588
|
+
const promise = new Promise((done) => {
|
|
1589
|
+
resolve = done;
|
|
1590
|
+
});
|
|
1591
|
+
entry = { promise, resolve };
|
|
1592
|
+
this.announced.set(toolCallId, entry);
|
|
1593
|
+
}
|
|
1594
|
+
return entry;
|
|
1595
|
+
}
|
|
1596
|
+
settleAnnounced() {
|
|
1597
|
+
for (const entry of this.announced.values())
|
|
1598
|
+
entry.resolve();
|
|
1599
|
+
}
|
|
1600
|
+
onPart(part) {
|
|
1601
|
+
switch (part.type) {
|
|
1602
|
+
case "text-delta":
|
|
1603
|
+
this.textDelta(part.text);
|
|
1604
|
+
return;
|
|
1605
|
+
case "reasoning-start":
|
|
1606
|
+
this.closeText();
|
|
1607
|
+
this.reasoningSegment(part.id);
|
|
1608
|
+
return;
|
|
1609
|
+
case "reasoning-delta":
|
|
1610
|
+
this.reasoningDelta(part.id, part.text);
|
|
1611
|
+
return;
|
|
1612
|
+
case "reasoning-end":
|
|
1613
|
+
this.reasoningEnd(part.id);
|
|
1614
|
+
return;
|
|
1615
|
+
case "tool-input-start":
|
|
1616
|
+
this.closeText();
|
|
1617
|
+
return;
|
|
1618
|
+
case "tool-call":
|
|
1619
|
+
this.closeText();
|
|
1620
|
+
this.toolCall({
|
|
1621
|
+
toolCallId: part.toolCallId,
|
|
1622
|
+
toolName: part.toolName,
|
|
1623
|
+
input: part.input
|
|
1624
|
+
});
|
|
1625
|
+
this.announcement(part.toolCallId).resolve();
|
|
1626
|
+
return;
|
|
1627
|
+
case "tool-result":
|
|
1628
|
+
this.toolResult(part.toolCallId, part.output);
|
|
1629
|
+
return;
|
|
1630
|
+
case "tool-error":
|
|
1631
|
+
this.toolFailed(part.toolCallId, errorMessage(part.error));
|
|
1632
|
+
return;
|
|
1633
|
+
case "tool-output-denied":
|
|
1634
|
+
this.toolFailed(part.toolCallId, "The tool call was denied.");
|
|
1635
|
+
return;
|
|
1636
|
+
case "finish-step":
|
|
1637
|
+
this.closeText();
|
|
1638
|
+
this.usage.add(part.usage);
|
|
1639
|
+
return;
|
|
1640
|
+
case "error":
|
|
1641
|
+
throw part.error;
|
|
1642
|
+
default:
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
textDelta(delta) {
|
|
1647
|
+
this.text ??= {
|
|
1648
|
+
key: `text:${++this.segments}`,
|
|
1649
|
+
text: "",
|
|
1650
|
+
started: false
|
|
1651
|
+
};
|
|
1652
|
+
const segment = this.text;
|
|
1653
|
+
segment.text += delta;
|
|
1654
|
+
if (!segment.started) {
|
|
1655
|
+
if (!segment.text.trim())
|
|
1656
|
+
return;
|
|
1657
|
+
segment.started = true;
|
|
1658
|
+
this.emit({
|
|
1659
|
+
type: "item.started",
|
|
1660
|
+
key: segment.key,
|
|
1661
|
+
item: { kind: "assistant_message", text: "", agentId: null }
|
|
1662
|
+
});
|
|
1663
|
+
this.emit({
|
|
1664
|
+
type: "item.delta",
|
|
1665
|
+
key: segment.key,
|
|
1666
|
+
field: "text",
|
|
1667
|
+
text: segment.text
|
|
1668
|
+
});
|
|
1669
|
+
return;
|
|
1670
|
+
}
|
|
1671
|
+
this.emit({
|
|
1672
|
+
type: "item.delta",
|
|
1673
|
+
key: segment.key,
|
|
1674
|
+
field: "text",
|
|
1675
|
+
text: delta
|
|
1676
|
+
});
|
|
1677
|
+
}
|
|
1678
|
+
closeText() {
|
|
1679
|
+
const segment = this.text;
|
|
1680
|
+
this.text = undefined;
|
|
1681
|
+
if (!segment?.started)
|
|
1682
|
+
return;
|
|
1683
|
+
this.emit({
|
|
1684
|
+
type: "item.completed",
|
|
1685
|
+
key: segment.key,
|
|
1686
|
+
status: "completed",
|
|
1687
|
+
item: { text: segment.text }
|
|
1688
|
+
});
|
|
1689
|
+
}
|
|
1690
|
+
reasoningSegment(id) {
|
|
1691
|
+
let segment = this.reasoning.get(id);
|
|
1692
|
+
if (!segment) {
|
|
1693
|
+
segment = {
|
|
1694
|
+
key: `reasoning:${++this.segments}`,
|
|
1695
|
+
text: "",
|
|
1696
|
+
started: false
|
|
1697
|
+
};
|
|
1698
|
+
this.reasoning.set(id, segment);
|
|
1699
|
+
}
|
|
1700
|
+
return segment;
|
|
1701
|
+
}
|
|
1702
|
+
reasoningDelta(id, delta) {
|
|
1703
|
+
const segment = this.reasoningSegment(id);
|
|
1704
|
+
segment.text += delta;
|
|
1705
|
+
if (!segment.started) {
|
|
1706
|
+
if (!segment.text.trim())
|
|
1707
|
+
return;
|
|
1708
|
+
segment.started = true;
|
|
1709
|
+
this.emit({
|
|
1710
|
+
type: "item.started",
|
|
1711
|
+
key: segment.key,
|
|
1712
|
+
item: { kind: "reasoning", text: "" }
|
|
1713
|
+
});
|
|
1714
|
+
this.emit({
|
|
1715
|
+
type: "item.delta",
|
|
1716
|
+
key: segment.key,
|
|
1717
|
+
field: "text",
|
|
1718
|
+
text: segment.text
|
|
1719
|
+
});
|
|
1720
|
+
return;
|
|
1721
|
+
}
|
|
1722
|
+
this.emit({
|
|
1723
|
+
type: "item.delta",
|
|
1724
|
+
key: segment.key,
|
|
1725
|
+
field: "text",
|
|
1726
|
+
text: delta
|
|
1727
|
+
});
|
|
1728
|
+
}
|
|
1729
|
+
reasoningEnd(id) {
|
|
1730
|
+
const segment = this.reasoning.get(id);
|
|
1731
|
+
this.reasoning.delete(id);
|
|
1732
|
+
if (!segment?.started)
|
|
1733
|
+
return;
|
|
1734
|
+
this.emit({
|
|
1735
|
+
type: "item.completed",
|
|
1736
|
+
key: segment.key,
|
|
1737
|
+
status: "completed",
|
|
1738
|
+
item: { text: segment.text }
|
|
1739
|
+
});
|
|
1740
|
+
const heading = reasoningHeading(segment.text);
|
|
1741
|
+
if (heading) {
|
|
1742
|
+
this.heading = heading;
|
|
1743
|
+
this.emit({ type: "status", text: heading });
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
toolCall(call) {
|
|
1747
|
+
const meta = this.toolMeta.get(call.toolName);
|
|
1748
|
+
const values = isRecord(call.input) ? call.input : {};
|
|
1749
|
+
const key = `tool:${call.toolCallId}`;
|
|
1750
|
+
const description = typeof values.description === "string" && values.description ? values.description : null;
|
|
1751
|
+
if (meta?.kind === "title") {
|
|
1752
|
+
if (typeof values.title === "string" && values.title.trim())
|
|
1753
|
+
this.emit({ type: "title", text: values.title.trim() });
|
|
1754
|
+
this.toolItems.set(call.toolCallId, { key: null, meta });
|
|
1755
|
+
return;
|
|
1756
|
+
}
|
|
1757
|
+
if (meta?.kind === "ask") {
|
|
1758
|
+
this.toolItems.set(call.toolCallId, { key: null, meta });
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
this.toolItems.set(call.toolCallId, { key, meta });
|
|
1762
|
+
if (meta?.kind === "command") {
|
|
1763
|
+
this.emit({
|
|
1764
|
+
type: "item.started",
|
|
1765
|
+
key,
|
|
1766
|
+
item: {
|
|
1767
|
+
kind: "command",
|
|
1768
|
+
command: typeof values.command === "string" ? values.command : "",
|
|
1769
|
+
description,
|
|
1770
|
+
output: "",
|
|
1771
|
+
exitCode: null
|
|
1772
|
+
},
|
|
1773
|
+
...this.said()
|
|
1774
|
+
});
|
|
1775
|
+
return;
|
|
1776
|
+
}
|
|
1777
|
+
if (meta?.kind === "file") {
|
|
1778
|
+
const filePath = typeof values.path === "string" ? values.path : "";
|
|
1779
|
+
this.emit({
|
|
1780
|
+
type: "item.started",
|
|
1781
|
+
key,
|
|
1782
|
+
item: {
|
|
1783
|
+
kind: "file_change",
|
|
1784
|
+
path: this.projectRelative(filePath),
|
|
1785
|
+
change: meta.change,
|
|
1786
|
+
previousPath: null
|
|
1787
|
+
},
|
|
1788
|
+
...this.said()
|
|
1789
|
+
});
|
|
1790
|
+
return;
|
|
1791
|
+
}
|
|
1792
|
+
this.emit({
|
|
1793
|
+
type: "item.started",
|
|
1794
|
+
key,
|
|
1795
|
+
item: {
|
|
1796
|
+
kind: "tool_call",
|
|
1797
|
+
tool: call.toolName,
|
|
1798
|
+
server: meta?.kind === "tool" ? meta.server : null,
|
|
1799
|
+
description,
|
|
1800
|
+
input: toJsonValue(call.input),
|
|
1801
|
+
result: null,
|
|
1802
|
+
error: null
|
|
1803
|
+
},
|
|
1804
|
+
...this.said()
|
|
1805
|
+
});
|
|
1806
|
+
}
|
|
1807
|
+
said() {
|
|
1808
|
+
return this.heading ? { activity: this.heading } : {};
|
|
1809
|
+
}
|
|
1810
|
+
projectRelative(filePath) {
|
|
1811
|
+
try {
|
|
1812
|
+
return path2.posix.relative(this.workingDirectory, resolveProjectPath(this.workingDirectory, filePath));
|
|
1813
|
+
} catch {
|
|
1814
|
+
return filePath;
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
toolResult(toolCallId, output) {
|
|
1818
|
+
const entry = this.toolItems.get(toolCallId);
|
|
1819
|
+
this.toolItems.delete(toolCallId);
|
|
1820
|
+
if (!entry?.key)
|
|
1821
|
+
return;
|
|
1822
|
+
if (entry.meta?.kind === "command") {
|
|
1823
|
+
const shell = shellResultSchema.safeParse(output);
|
|
1824
|
+
this.emit({
|
|
1825
|
+
type: "item.completed",
|
|
1826
|
+
key: entry.key,
|
|
1827
|
+
status: "completed",
|
|
1828
|
+
item: shell.success ? { output: shell.data.output, exitCode: shell.data.exitCode } : { output: typeof output === "string" ? output : "" }
|
|
1829
|
+
});
|
|
1830
|
+
return;
|
|
1831
|
+
}
|
|
1832
|
+
if (entry.meta?.kind === "file") {
|
|
1833
|
+
this.emit({
|
|
1834
|
+
type: "item.completed",
|
|
1835
|
+
key: entry.key,
|
|
1836
|
+
status: "completed"
|
|
1837
|
+
});
|
|
1838
|
+
return;
|
|
1839
|
+
}
|
|
1840
|
+
const host = parseHostToolResult(output);
|
|
1841
|
+
const result = toJsonValue(transcriptToolResult(output));
|
|
1842
|
+
if (entry.meta?.kind === "tool" && entry.meta.source === "host" && host?.isError) {
|
|
1843
|
+
this.emit({
|
|
1844
|
+
type: "item.completed",
|
|
1845
|
+
key: entry.key,
|
|
1846
|
+
status: "failed",
|
|
1847
|
+
item: {
|
|
1848
|
+
result,
|
|
1849
|
+
error: host.content.flatMap((part) => part.type === "text" ? [part.text] : []).join(`
|
|
1850
|
+
`)
|
|
1851
|
+
}
|
|
1852
|
+
});
|
|
1853
|
+
return;
|
|
1854
|
+
}
|
|
1855
|
+
this.emit({
|
|
1856
|
+
type: "item.completed",
|
|
1857
|
+
key: entry.key,
|
|
1858
|
+
status: "completed",
|
|
1859
|
+
item: { result }
|
|
1860
|
+
});
|
|
1861
|
+
}
|
|
1862
|
+
toolFailed(toolCallId, message) {
|
|
1863
|
+
const entry = this.toolItems.get(toolCallId);
|
|
1864
|
+
this.toolItems.delete(toolCallId);
|
|
1865
|
+
if (!entry?.key)
|
|
1866
|
+
return;
|
|
1867
|
+
this.emit({
|
|
1868
|
+
type: "item.completed",
|
|
1869
|
+
key: entry.key,
|
|
1870
|
+
status: "failed",
|
|
1871
|
+
item: entry.meta?.kind === "command" ? { output: message } : entry.meta?.kind === "file" ? {} : { error: message }
|
|
1872
|
+
});
|
|
1873
|
+
}
|
|
1874
|
+
closeOpenItems(status) {
|
|
1875
|
+
this.closeText();
|
|
1876
|
+
for (const id of [...this.reasoning.keys()])
|
|
1877
|
+
this.reasoningEnd(id);
|
|
1878
|
+
for (const [toolCallId, entry] of this.toolItems) {
|
|
1879
|
+
this.toolItems.delete(toolCallId);
|
|
1880
|
+
if (!entry.key)
|
|
1881
|
+
continue;
|
|
1882
|
+
this.emit({
|
|
1883
|
+
type: "item.completed",
|
|
1884
|
+
key: entry.key,
|
|
1885
|
+
status: status === "interrupted" ? "cancelled" : "failed"
|
|
1886
|
+
});
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
async request(key, draft) {
|
|
1890
|
+
try {
|
|
1891
|
+
return await untilAborted(this.host.request(key, draft), this.abort.signal);
|
|
1892
|
+
} catch (cause) {
|
|
1893
|
+
if (this.abort.signal.aborted && !(cause instanceof RequestClosedError))
|
|
1894
|
+
this.emit({ type: "request.closed", key, reason: "The turn stopped." });
|
|
1895
|
+
throw cause;
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
async askUser(args) {
|
|
1899
|
+
const key = `ask:${args.toolCallId}`;
|
|
1900
|
+
const first = args.questions[0];
|
|
1901
|
+
const draft = {
|
|
1902
|
+
kind: "question",
|
|
1903
|
+
blocking: args.blocking,
|
|
1904
|
+
title: args.questions.length === 1 && first ? first.question : `${args.questions.length} questions`,
|
|
1905
|
+
origin: { kind: "tool", id: "ask_user", displayName: "Ask User" },
|
|
1906
|
+
questions: args.questions
|
|
1907
|
+
};
|
|
1908
|
+
if (!args.blocking) {
|
|
1909
|
+
this.host.request(key, draft).catch(() => {});
|
|
1910
|
+
return "Asked. The answer arrives as a message when the person replies; keep working on what does not depend on it.";
|
|
1911
|
+
}
|
|
1912
|
+
try {
|
|
1913
|
+
const response = await this.request(key, draft);
|
|
1914
|
+
if (response.kind !== "question")
|
|
1915
|
+
return "The person did not answer.";
|
|
1916
|
+
return args.questions.map((question, index) => `${question.question}
|
|
1917
|
+
Answer: ${response.answers[index] ?? "(no answer)"}`).concat(response.answers.slice(args.questions.length)).join(`
|
|
1918
|
+
|
|
1919
|
+
`);
|
|
1920
|
+
} catch (cause) {
|
|
1921
|
+
if (cause instanceof RequestClosedError)
|
|
1922
|
+
return `The question was closed without an answer: ${cause.reason}`;
|
|
1923
|
+
throw cause;
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
async callHostTool(args) {
|
|
1927
|
+
return untilAborted(this.host.callTool({
|
|
1928
|
+
name: args.name,
|
|
1929
|
+
input: toJsonValue(args.input),
|
|
1930
|
+
itemKey: `tool:${args.toolCallId}`
|
|
1931
|
+
}), this.abort.signal);
|
|
1932
|
+
}
|
|
1933
|
+
async authorizeMcp(args) {
|
|
1934
|
+
if (!this.attempt.toolPolicies[args.server])
|
|
1935
|
+
return;
|
|
1936
|
+
const verdict = await untilAborted(this.host.authorize({
|
|
1937
|
+
server: args.server,
|
|
1938
|
+
tool: args.tool.name,
|
|
1939
|
+
input: toJsonValue(args.input),
|
|
1940
|
+
itemKey: `tool:${args.toolCallId}`
|
|
1941
|
+
}), this.abort.signal);
|
|
1942
|
+
if (!verdict.allowed)
|
|
1943
|
+
throw new Error(verdict.message);
|
|
1944
|
+
}
|
|
1945
|
+
async connectMcp() {
|
|
1946
|
+
const connect = this.options.connectMcp ?? (({ spec, onElicit }) => connectMcpServer(spec, { onElicit }));
|
|
1947
|
+
const entries = Object.entries(this.attempt.mcpServers);
|
|
1948
|
+
const connected = await Promise.all(entries.map(async ([name, spec]) => {
|
|
1949
|
+
try {
|
|
1950
|
+
return await connect({
|
|
1951
|
+
name,
|
|
1952
|
+
spec,
|
|
1953
|
+
onElicit: (request) => this.elicit(name, request)
|
|
1954
|
+
});
|
|
1955
|
+
} catch (cause) {
|
|
1956
|
+
this.emit({
|
|
1957
|
+
type: "diagnostic",
|
|
1958
|
+
level: "warn",
|
|
1959
|
+
message: `The MCP server "${name}" did not connect: ${errorMessage(cause)}`
|
|
1960
|
+
});
|
|
1961
|
+
return;
|
|
1962
|
+
}
|
|
1963
|
+
}));
|
|
1964
|
+
const servers = new Map;
|
|
1965
|
+
entries.forEach(([name], index) => {
|
|
1966
|
+
const server = connected[index];
|
|
1967
|
+
if (server)
|
|
1968
|
+
servers.set(name, server);
|
|
1969
|
+
});
|
|
1970
|
+
return servers;
|
|
1971
|
+
}
|
|
1972
|
+
async elicit(server, request) {
|
|
1973
|
+
const key = `elicitation:${server}:${++this.requests}`;
|
|
1974
|
+
try {
|
|
1975
|
+
const response = await this.request(key, {
|
|
1976
|
+
kind: "elicitation",
|
|
1977
|
+
blocking: true,
|
|
1978
|
+
title: `${server} needs your input`,
|
|
1979
|
+
description: request.message,
|
|
1980
|
+
origin: { kind: "mcp", id: server, displayName: server },
|
|
1981
|
+
elicitation: {
|
|
1982
|
+
server,
|
|
1983
|
+
message: request.message,
|
|
1984
|
+
...request.mode === "url" ? { url: request.url } : { schema: elicitationSchema(request.fields) }
|
|
1985
|
+
}
|
|
1986
|
+
});
|
|
1987
|
+
if (response.kind !== "elicitation")
|
|
1988
|
+
return { action: "cancel" };
|
|
1989
|
+
if (response.action === "accept")
|
|
1990
|
+
return {
|
|
1991
|
+
action: "accept",
|
|
1992
|
+
...isRecord(response.content) ? { content: response.content } : {}
|
|
1993
|
+
};
|
|
1994
|
+
return { action: response.action };
|
|
1995
|
+
} catch {
|
|
1996
|
+
return { action: "cancel" };
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
var shellResultSchema = z4.object({
|
|
2001
|
+
exitCode: z4.number(),
|
|
2002
|
+
output: z4.string()
|
|
2003
|
+
});
|
|
2004
|
+
function elicitationSchema(fields) {
|
|
2005
|
+
const properties = {};
|
|
2006
|
+
for (const field of fields) {
|
|
2007
|
+
const values = field.options?.map((option) => option.value);
|
|
2008
|
+
const base = {
|
|
2009
|
+
...field.title ? { title: field.title } : {},
|
|
2010
|
+
...field.description ? { description: field.description } : {},
|
|
2011
|
+
...field.format ? { format: field.format } : {},
|
|
2012
|
+
...field.default !== undefined ? { default: field.default } : {}
|
|
2013
|
+
};
|
|
2014
|
+
properties[field.name] = field.type === "enum" ? field.multiSelect ? {
|
|
2015
|
+
...base,
|
|
2016
|
+
type: "array",
|
|
2017
|
+
items: { type: "string", enum: values ?? [] }
|
|
2018
|
+
} : { ...base, type: "string", enum: values ?? [] } : { ...base, type: field.type };
|
|
2019
|
+
}
|
|
2020
|
+
return {
|
|
2021
|
+
type: "object",
|
|
2022
|
+
properties,
|
|
2023
|
+
required: fields.filter((field) => field.required).map((field) => field.name)
|
|
2024
|
+
};
|
|
2025
|
+
}
|
|
2026
|
+
function userMessage(input) {
|
|
2027
|
+
const text = renderUserMessage(input.text, input.attachments);
|
|
2028
|
+
const media = input.attachments.filter(isMediaAttachment);
|
|
2029
|
+
if (media.length === 0)
|
|
2030
|
+
return { role: "user", content: text };
|
|
2031
|
+
return {
|
|
2032
|
+
role: "user",
|
|
2033
|
+
content: [
|
|
2034
|
+
{ type: "text", text },
|
|
2035
|
+
...media.map((attachment) => attachment.kind === "image" ? {
|
|
2036
|
+
type: "image",
|
|
2037
|
+
image: attachment.dataBase64,
|
|
2038
|
+
mediaType: attachment.mediaType
|
|
2039
|
+
} : {
|
|
2040
|
+
type: "file",
|
|
2041
|
+
data: attachment.dataBase64,
|
|
2042
|
+
mediaType: attachment.mediaType,
|
|
2043
|
+
filename: attachment.name
|
|
2044
|
+
})
|
|
2045
|
+
]
|
|
2046
|
+
};
|
|
2047
|
+
}
|
|
2048
|
+
var ANTHROPIC_THINKING_BUDGETS = {
|
|
2049
|
+
low: 0,
|
|
2050
|
+
medium: 1e4,
|
|
2051
|
+
high: 32000,
|
|
2052
|
+
xhigh: 48000,
|
|
2053
|
+
max: 64000
|
|
2054
|
+
};
|
|
2055
|
+
function effortProviderOptions(effort) {
|
|
2056
|
+
return {
|
|
2057
|
+
anthropic: effort === "low" ? { thinking: { type: "disabled" } } : {
|
|
2058
|
+
thinking: {
|
|
2059
|
+
type: "enabled",
|
|
2060
|
+
budgetTokens: ANTHROPIC_THINKING_BUDGETS[effort]
|
|
2061
|
+
}
|
|
2062
|
+
},
|
|
2063
|
+
openai: {
|
|
2064
|
+
reasoningEffort: effort === "xhigh" || effort === "max" ? "high" : effort,
|
|
2065
|
+
reasoningSummary: "auto"
|
|
2066
|
+
}
|
|
2067
|
+
};
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
class UsageTally {
|
|
2071
|
+
input = 0;
|
|
2072
|
+
cached = 0;
|
|
2073
|
+
cacheCreation = 0;
|
|
2074
|
+
output = 0;
|
|
2075
|
+
reasoning = 0;
|
|
2076
|
+
context = 0;
|
|
2077
|
+
add(usage) {
|
|
2078
|
+
const input = positiveTokenCount(usage.inputTokens);
|
|
2079
|
+
const output = positiveTokenCount(usage.outputTokens);
|
|
2080
|
+
this.input += input;
|
|
2081
|
+
this.cached += positiveTokenCount(usage.inputTokenDetails?.cacheReadTokens);
|
|
2082
|
+
this.cacheCreation += positiveTokenCount(usage.inputTokenDetails?.cacheWriteTokens);
|
|
2083
|
+
this.output += output;
|
|
2084
|
+
this.reasoning += positiveTokenCount(usage.outputTokenDetails?.reasoningTokens);
|
|
2085
|
+
if (input + output > 0)
|
|
2086
|
+
this.context = input + output;
|
|
2087
|
+
}
|
|
2088
|
+
toUsage(model) {
|
|
2089
|
+
if (this.input + this.output === 0)
|
|
2090
|
+
return;
|
|
2091
|
+
return {
|
|
2092
|
+
...model ? { model } : {},
|
|
2093
|
+
inputTokens: Math.max(0, this.input - this.cached - this.cacheCreation),
|
|
2094
|
+
cachedInputTokens: this.cached,
|
|
2095
|
+
cacheCreationTokens: this.cacheCreation,
|
|
2096
|
+
outputTokens: this.output,
|
|
2097
|
+
reasoningTokens: Math.min(this.output, this.reasoning),
|
|
2098
|
+
...this.context ? { contextTokens: this.context } : {}
|
|
2099
|
+
};
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
function modelIdOf(model) {
|
|
2103
|
+
return typeof model === "string" ? model : model.modelId;
|
|
2104
|
+
}
|
|
2105
|
+
function untilAborted(promise, signal) {
|
|
2106
|
+
if (signal.aborted) {
|
|
2107
|
+
promise.catch(() => {});
|
|
2108
|
+
return Promise.reject(abortError());
|
|
2109
|
+
}
|
|
2110
|
+
return new Promise((resolve, reject) => {
|
|
2111
|
+
const onAbort = () => {
|
|
2112
|
+
promise.catch(() => {});
|
|
2113
|
+
reject(abortError());
|
|
2114
|
+
};
|
|
2115
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2116
|
+
promise.then((value) => {
|
|
2117
|
+
signal.removeEventListener("abort", onAbort);
|
|
2118
|
+
resolve(value);
|
|
2119
|
+
}, (cause) => {
|
|
2120
|
+
signal.removeEventListener("abort", onAbort);
|
|
2121
|
+
reject(cause);
|
|
2122
|
+
});
|
|
2123
|
+
});
|
|
2124
|
+
}
|
|
2125
|
+
function abortError() {
|
|
2126
|
+
const error = new Error("The turn stopped.");
|
|
2127
|
+
error.name = "AbortError";
|
|
2128
|
+
return error;
|
|
2129
|
+
}
|
|
2130
|
+
function readLocal(local) {
|
|
2131
|
+
if (!local)
|
|
2132
|
+
return {};
|
|
2133
|
+
const sandbox = local.sandbox;
|
|
2134
|
+
if (sandbox !== undefined && !isSandboxHandle(sandbox))
|
|
2135
|
+
throw new Error("The ai-sdk harness was given a sandbox without a provider, sandbox id and working directory.");
|
|
2136
|
+
const roots = local.readableRoots;
|
|
2137
|
+
const shell = local.shell;
|
|
2138
|
+
return {
|
|
2139
|
+
...sandbox ? { sandbox } : {},
|
|
2140
|
+
...Array.isArray(roots) ? {
|
|
2141
|
+
readableRoots: roots.filter((root) => typeof root === "string")
|
|
2142
|
+
} : {},
|
|
2143
|
+
...isShellState(shell) ? { shell } : {},
|
|
2144
|
+
...typeof local.userId === "string" ? { userId: local.userId } : {}
|
|
2145
|
+
};
|
|
2146
|
+
}
|
|
2147
|
+
function isSandboxHandle(value) {
|
|
2148
|
+
return isRecord(value) && isRecord(value.provider) && typeof value.provider.executeCommand === "function" && typeof value.provider.uploadFiles === "function" && typeof value.provider.downloadFile === "function" && typeof value.sandboxId === "string" && typeof value.workingDirectory === "string" && (value.commandBudgetSeconds === undefined || typeof value.commandBudgetSeconds === "number") && (value.envFiles === undefined || Array.isArray(value.envFiles) && value.envFiles.every((file) => typeof file === "string"));
|
|
2149
|
+
}
|
|
2150
|
+
function isShellState(value) {
|
|
2151
|
+
return isRecord(value) && (value.cwd === undefined || typeof value.cwd === "string") && (value.background === undefined || value.background instanceof Map);
|
|
2152
|
+
}
|
|
2153
|
+
export {
|
|
2154
|
+
AI_SDK_HARNESS,
|
|
2155
|
+
classifyModelError,
|
|
2156
|
+
createAiSdkAdapter,
|
|
2157
|
+
entriesThroughTurn,
|
|
2158
|
+
foldThread,
|
|
2159
|
+
mcpModelToolName,
|
|
2160
|
+
parseThreadEntries,
|
|
2161
|
+
pruneEmptyOptionalArgs,
|
|
2162
|
+
stopBackgroundCommands
|
|
2163
|
+
};
|
|
2164
|
+
|
|
2165
|
+
//# debugId=B3DF91190019E80C64756E2164756E21
|
|
2166
|
+
//# sourceMappingURL=index.js.map
|