@ai-sdk/harness-deepagents 0.0.0 → 1.0.1
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/CHANGELOG.md +17 -0
- package/LICENSE +13 -0
- package/README.md +68 -0
- package/dist/bridge/index.mjs +843 -0
- package/dist/bridge/index.mjs.map +1 -0
- package/dist/bridge/package.json +14 -0
- package/dist/bridge/pnpm-lock.yaml +536 -0
- package/dist/index.d.ts +98 -0
- package/dist/index.js +741 -0
- package/dist/index.js.map +1 -0
- package/package.json +77 -1
- package/src/bridge/approvals.ts +61 -0
- package/src/bridge/index.ts +416 -0
- package/src/bridge/json-schema-to-zod.ts +64 -0
- package/src/bridge/local-shell-backend.ts +19 -0
- package/src/bridge/package.json +14 -0
- package/src/bridge/pnpm-lock.yaml +536 -0
- package/src/deepagents-auth.ts +77 -0
- package/src/deepagents-bridge-protocol.ts +31 -0
- package/src/deepagents-harness.ts +818 -0
- package/src/index.ts +8 -0
|
@@ -0,0 +1,818 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import {
|
|
5
|
+
commonTool,
|
|
6
|
+
HarnessCapabilityUnsupportedError,
|
|
7
|
+
harnessV1DiagnosticFromBridgeFrame,
|
|
8
|
+
type HarnessV1,
|
|
9
|
+
type HarnessV1Bootstrap,
|
|
10
|
+
type HarnessV1BuiltinTool,
|
|
11
|
+
type HarnessV1ContinueTurnState,
|
|
12
|
+
type HarnessV1NetworkSandboxSession,
|
|
13
|
+
type HarnessV1PermissionMode,
|
|
14
|
+
type HarnessV1Prompt,
|
|
15
|
+
type HarnessV1PromptControl,
|
|
16
|
+
type HarnessV1ResumeSessionState,
|
|
17
|
+
type HarnessV1Session,
|
|
18
|
+
type HarnessV1Skill,
|
|
19
|
+
type HarnessV1StreamPart,
|
|
20
|
+
} from '@ai-sdk/harness';
|
|
21
|
+
import {
|
|
22
|
+
markBridgeStarting,
|
|
23
|
+
SandboxChannel,
|
|
24
|
+
waitForBridgeReady,
|
|
25
|
+
} from '@ai-sdk/harness/utils';
|
|
26
|
+
import { tool, type Experimental_SandboxProcess } from '@ai-sdk/provider-utils';
|
|
27
|
+
import { WebSocket } from 'ws';
|
|
28
|
+
import { z } from 'zod';
|
|
29
|
+
import {
|
|
30
|
+
resolveDeepAgentsEnv,
|
|
31
|
+
type DeepAgentsAuthOptions,
|
|
32
|
+
} from './deepagents-auth';
|
|
33
|
+
import {
|
|
34
|
+
outboundMessageSchema,
|
|
35
|
+
type InboundMessage,
|
|
36
|
+
type OutboundMessage,
|
|
37
|
+
} from './deepagents-bridge-protocol';
|
|
38
|
+
|
|
39
|
+
type DeepAgentsChannel = SandboxChannel<OutboundMessage, InboundMessage>;
|
|
40
|
+
|
|
41
|
+
// Pure derived state in /tmp; reinstalled per sandbox, persistence is the provider snapshot.
|
|
42
|
+
const BOOTSTRAP_DIR = '/tmp/harness/deepagents';
|
|
43
|
+
|
|
44
|
+
// Pinned ripgrep release + per-arch tarball checksums (verified before install).
|
|
45
|
+
const RIPGREP_VERSION = '14.1.1';
|
|
46
|
+
const RIPGREP_SHA256_X64 =
|
|
47
|
+
'4cf9f2741e6c465ffdb7c26f38056a59e2a2544b51f7cc128ef28337eeae4d8e';
|
|
48
|
+
const RIPGREP_SHA256_ARM =
|
|
49
|
+
'c827481c4ff4ea10c9dc7a4022c8de5db34a5737cb74484d62eb94a95841ab2f';
|
|
50
|
+
|
|
51
|
+
// Idempotent, checksum-verified install of a static ripgrep binary into a PATH dir.
|
|
52
|
+
// DeepAgents' grep shells out to `rg`; without it, its fallback reads the whole workdir (incl. node_modules) into memory and OOMs. Skipped if `rg` already exists.
|
|
53
|
+
function installRipgrepCommand(): string {
|
|
54
|
+
const v = RIPGREP_VERSION;
|
|
55
|
+
return [
|
|
56
|
+
'command -v rg >/dev/null 2>&1 || {',
|
|
57
|
+
'case "$(uname -m)" in',
|
|
58
|
+
`aarch64) a=aarch64-unknown-linux-gnu; sha=${RIPGREP_SHA256_ARM} ;;`,
|
|
59
|
+
`*) a=x86_64-unknown-linux-musl; sha=${RIPGREP_SHA256_X64} ;;`,
|
|
60
|
+
'esac;',
|
|
61
|
+
`f=/tmp/ripgrep-${v}.tar.gz;`,
|
|
62
|
+
`curl -fsSL "https://github.com/BurntSushi/ripgrep/releases/download/${v}/ripgrep-${v}-$a.tar.gz" -o "$f"`,
|
|
63
|
+
'&& echo "$sha $f" | sha256sum -c -',
|
|
64
|
+
'&& tar xzf "$f" -C /tmp',
|
|
65
|
+
`&& mv "/tmp/ripgrep-${v}-$a/rg" /usr/local/bin/rg && chmod +x /usr/local/bin/rg;`,
|
|
66
|
+
'}',
|
|
67
|
+
].join(' ');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Skills source subpath, written under $HOME (out of the work dir so it can't clash with code cloned into the work dir) and also discovered from <workDir> for repo-provided skills.
|
|
71
|
+
const SKILLS_SOURCE_PATH = '/.agents/skills';
|
|
72
|
+
|
|
73
|
+
const DEEPAGENTS_DEFAULT_CONTEXT_WINDOW = 200_000;
|
|
74
|
+
|
|
75
|
+
export type DeepAgentsHarnessSettings = {
|
|
76
|
+
readonly auth?: DeepAgentsAuthOptions;
|
|
77
|
+
/** Model id for the DeepAgents runtime, e.g. `claude-sonnet-4` (converted to `provider:model`). */
|
|
78
|
+
readonly model?: string;
|
|
79
|
+
/** Bridge port override; defaults to the sandbox's first declared port. */
|
|
80
|
+
readonly port?: number;
|
|
81
|
+
/** Maximum milliseconds to wait for the bridge to advertise its port. Defaults to 120000. */
|
|
82
|
+
readonly startupTimeoutMs?: number;
|
|
83
|
+
/** Max LangGraph super-steps per turn before it errors. Defaults to 100; raise for long multi-step tasks. */
|
|
84
|
+
readonly recursionLimit?: number;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
// Live bridge coordinates returned by doDetach/doSuspendTurn so a later process can reattach.
|
|
88
|
+
const deepAgentsBridgeCoordsSchema = z.object({
|
|
89
|
+
port: z.number(),
|
|
90
|
+
token: z.string(),
|
|
91
|
+
lastSeenEventId: z.number(),
|
|
92
|
+
sandboxId: z.string().optional(),
|
|
93
|
+
});
|
|
94
|
+
const deepAgentsResumeStateSchema = z.object({
|
|
95
|
+
bridge: deepAgentsBridgeCoordsSchema.optional(),
|
|
96
|
+
});
|
|
97
|
+
type DeepAgentsBridgeCoords = z.infer<typeof deepAgentsBridgeCoordsSchema>;
|
|
98
|
+
|
|
99
|
+
// Every model-callable DeepAgents built-in, keyed by what the bridge emits (commonName ?? nativeName); all must be listed or AI SDK throws AI_NoSuchToolError.
|
|
100
|
+
const DEEPAGENTS_BUILTIN_TOOLS = {
|
|
101
|
+
read: commonTool('read', {
|
|
102
|
+
nativeName: 'read_file',
|
|
103
|
+
toolUseKind: 'readonly',
|
|
104
|
+
description: 'Read file contents',
|
|
105
|
+
inputSchema: z.object({ file_path: z.string() }),
|
|
106
|
+
}),
|
|
107
|
+
write: commonTool('write', {
|
|
108
|
+
nativeName: 'write_file',
|
|
109
|
+
toolUseKind: 'edit',
|
|
110
|
+
description: 'Create a file',
|
|
111
|
+
inputSchema: z.object({ file_path: z.string(), content: z.string() }),
|
|
112
|
+
}),
|
|
113
|
+
edit: commonTool('edit', {
|
|
114
|
+
nativeName: 'edit_file',
|
|
115
|
+
toolUseKind: 'edit',
|
|
116
|
+
description: 'Perform exact string replacements in a file',
|
|
117
|
+
inputSchema: z.object({
|
|
118
|
+
file_path: z.string(),
|
|
119
|
+
old_string: z.string(),
|
|
120
|
+
new_string: z.string(),
|
|
121
|
+
}),
|
|
122
|
+
}),
|
|
123
|
+
bash: commonTool('bash', {
|
|
124
|
+
nativeName: 'execute',
|
|
125
|
+
toolUseKind: 'bash',
|
|
126
|
+
description: 'Run a shell command',
|
|
127
|
+
inputSchema: z.object({ command: z.string() }),
|
|
128
|
+
}),
|
|
129
|
+
grep: commonTool('grep', {
|
|
130
|
+
nativeName: 'grep',
|
|
131
|
+
toolUseKind: 'readonly',
|
|
132
|
+
description: 'Search file contents',
|
|
133
|
+
inputSchema: z.object({ pattern: z.string() }),
|
|
134
|
+
}),
|
|
135
|
+
glob: commonTool('glob', {
|
|
136
|
+
nativeName: 'glob',
|
|
137
|
+
toolUseKind: 'readonly',
|
|
138
|
+
description: 'Find files matching a glob pattern',
|
|
139
|
+
inputSchema: z.object({ pattern: z.string() }),
|
|
140
|
+
}),
|
|
141
|
+
// No common-name equivalent — keyed by native name.
|
|
142
|
+
ls: tool({
|
|
143
|
+
description: 'List files in a directory',
|
|
144
|
+
inputSchema: z.object({ path: z.string().optional() }),
|
|
145
|
+
}),
|
|
146
|
+
task: tool({
|
|
147
|
+
description: 'Spawn a subagent to handle a delegated task',
|
|
148
|
+
inputSchema: z.object({
|
|
149
|
+
description: z.string().optional(),
|
|
150
|
+
subagent_type: z.string().optional(),
|
|
151
|
+
}),
|
|
152
|
+
}),
|
|
153
|
+
write_todos: tool({
|
|
154
|
+
description: 'Manage a structured todo list',
|
|
155
|
+
inputSchema: z.object({ todos: z.array(z.unknown()).optional() }),
|
|
156
|
+
}),
|
|
157
|
+
} as const satisfies Record<string, HarnessV1BuiltinTool<any, any>>;
|
|
158
|
+
|
|
159
|
+
export function createDeepAgents(
|
|
160
|
+
settings: DeepAgentsHarnessSettings = {},
|
|
161
|
+
): HarnessV1<typeof DEEPAGENTS_BUILTIN_TOOLS> {
|
|
162
|
+
let cachedBootstrap: HarnessV1Bootstrap | undefined;
|
|
163
|
+
|
|
164
|
+
return {
|
|
165
|
+
specificationVersion: 'harness-v1',
|
|
166
|
+
harnessId: 'deepagents',
|
|
167
|
+
builtinTools: DEEPAGENTS_BUILTIN_TOOLS,
|
|
168
|
+
// Built-in tool approvals are gated in-bridge via DeepAgents' interruptOn (HITL) middleware.
|
|
169
|
+
supportsBuiltinToolApprovals: true,
|
|
170
|
+
lifecycleStateSchema: deepAgentsResumeStateSchema,
|
|
171
|
+
getBootstrap: async () => {
|
|
172
|
+
if (cachedBootstrap != null) return cachedBootstrap;
|
|
173
|
+
const [bridge, pkg, lock] = await Promise.all([
|
|
174
|
+
readBridgeAsset('index.mjs'),
|
|
175
|
+
readBridgeAsset('package.json'),
|
|
176
|
+
readBridgeAsset('pnpm-lock.yaml'),
|
|
177
|
+
]);
|
|
178
|
+
cachedBootstrap = {
|
|
179
|
+
harnessId: 'deepagents',
|
|
180
|
+
bootstrapDir: BOOTSTRAP_DIR,
|
|
181
|
+
files: [
|
|
182
|
+
{ path: `${BOOTSTRAP_DIR}/bridge.mjs`, content: bridge },
|
|
183
|
+
{ path: `${BOOTSTRAP_DIR}/package.json`, content: pkg },
|
|
184
|
+
{ path: `${BOOTSTRAP_DIR}/pnpm-lock.yaml`, content: lock },
|
|
185
|
+
],
|
|
186
|
+
commands: [
|
|
187
|
+
{ command: `mkdir -p ${BOOTSTRAP_DIR}` },
|
|
188
|
+
{ command: installRipgrepCommand() },
|
|
189
|
+
{
|
|
190
|
+
command: `pnpm --dir ${BOOTSTRAP_DIR} install --frozen-lockfile --store-dir ${BOOTSTRAP_DIR}/.pnpm-store`,
|
|
191
|
+
},
|
|
192
|
+
],
|
|
193
|
+
};
|
|
194
|
+
return cachedBootstrap;
|
|
195
|
+
},
|
|
196
|
+
doStart: async startOpts => {
|
|
197
|
+
const permissionMode = startOpts.permissionMode;
|
|
198
|
+
const sandboxSession = startOpts.sandboxSession;
|
|
199
|
+
const session = sandboxSession.restricted();
|
|
200
|
+
const sandboxId = sandboxSession.id;
|
|
201
|
+
|
|
202
|
+
const lifecycleState = startOpts.continueFrom ?? startOpts.resumeFrom;
|
|
203
|
+
const isResume = lifecycleState != null;
|
|
204
|
+
const isContinue = startOpts.continueFrom != null;
|
|
205
|
+
const coords =
|
|
206
|
+
isResume && typeof lifecycleState?.data === 'object'
|
|
207
|
+
? (lifecycleState.data as { bridge?: DeepAgentsBridgeCoords }).bridge
|
|
208
|
+
: undefined;
|
|
209
|
+
|
|
210
|
+
const workDir = startOpts.sessionWorkDir;
|
|
211
|
+
const sessionDataDir = `${sandboxSession.defaultWorkingDirectory}/.agent-runs/${startOpts.sessionId}`;
|
|
212
|
+
const bridgeStateDir = `${sessionDataDir}/bridge`;
|
|
213
|
+
const timeoutMs = settings.startupTimeoutMs ?? 120_000;
|
|
214
|
+
|
|
215
|
+
const report = startOpts.observability?.report;
|
|
216
|
+
const onDiagnostic = report
|
|
217
|
+
? (frame: Parameters<typeof harnessV1DiagnosticFromBridgeFrame>[0]) =>
|
|
218
|
+
report(
|
|
219
|
+
harnessV1DiagnosticFromBridgeFrame(frame, {
|
|
220
|
+
sessionId: startOpts.sessionId,
|
|
221
|
+
timestamp: Date.now(),
|
|
222
|
+
}),
|
|
223
|
+
)
|
|
224
|
+
: undefined;
|
|
225
|
+
|
|
226
|
+
// Attach to the still-running bridge (continueFrom replays past the cursor); on failure fall through to a fresh spawn.
|
|
227
|
+
if (coords) {
|
|
228
|
+
try {
|
|
229
|
+
const attachUrl =
|
|
230
|
+
(await sandboxSession.getPortUrl({
|
|
231
|
+
port: coords.port,
|
|
232
|
+
protocol: 'ws',
|
|
233
|
+
})) + `?agent_bridge_token=${encodeURIComponent(coords.token)}`;
|
|
234
|
+
const attachChannel: DeepAgentsChannel = new SandboxChannel({
|
|
235
|
+
connect: () => openWebSocket(attachUrl),
|
|
236
|
+
outboundSchema: outboundMessageSchema,
|
|
237
|
+
initialLastSeenEventId: coords.lastSeenEventId,
|
|
238
|
+
onDiagnostic,
|
|
239
|
+
});
|
|
240
|
+
await attachChannel.open(isContinue ? { resume: true } : undefined);
|
|
241
|
+
return createSession({
|
|
242
|
+
sessionId: startOpts.sessionId,
|
|
243
|
+
channel: attachChannel,
|
|
244
|
+
proc: undefined,
|
|
245
|
+
model: settings.model,
|
|
246
|
+
bridgePort: coords.port,
|
|
247
|
+
bridgeToken: coords.token,
|
|
248
|
+
sandboxId,
|
|
249
|
+
isResume: true,
|
|
250
|
+
attached: true,
|
|
251
|
+
permissionMode,
|
|
252
|
+
recursionLimit: settings.recursionLimit,
|
|
253
|
+
});
|
|
254
|
+
} catch {
|
|
255
|
+
// Bridge no longer reachable — recover by respawning below.
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const port = resolveBridgePort(sandboxSession, settings.port);
|
|
260
|
+
const token = randomBytes(32).toString('hex');
|
|
261
|
+
|
|
262
|
+
// Always discover repo-provided skills under <workDir>/.agents/skills (e.g. a cloned repo); a missing dir is tolerated by deepagents.
|
|
263
|
+
// Absolute paths: LocalShellBackend (non-virtual) treats a leading-slash path as a real fs path.
|
|
264
|
+
const skillsPaths = [`${workDir}${SKILLS_SOURCE_PATH}`];
|
|
265
|
+
// Host-provided skills go to $HOME (out of the work dir) and take priority (listed last → wins on name collision).
|
|
266
|
+
if ((startOpts.skills?.length ?? 0) > 0) {
|
|
267
|
+
const homeDir = await resolveSandboxHomeDir({
|
|
268
|
+
sandbox: session,
|
|
269
|
+
abortSignal: startOpts.abortSignal,
|
|
270
|
+
});
|
|
271
|
+
const homeSkillsRoot = `${homeDir}${SKILLS_SOURCE_PATH}`;
|
|
272
|
+
await writeSkills({
|
|
273
|
+
sandbox: session,
|
|
274
|
+
root: homeSkillsRoot,
|
|
275
|
+
skills: startOpts.skills ?? [],
|
|
276
|
+
abortSignal: startOpts.abortSignal,
|
|
277
|
+
});
|
|
278
|
+
skillsPaths.push(homeSkillsRoot);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const env = {
|
|
282
|
+
...resolveDeepAgentsEnv({ auth: settings.auth }),
|
|
283
|
+
BRIDGE_CHANNEL_TOKEN: token,
|
|
284
|
+
BRIDGE_WS_PORT: String(port),
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
await session.run({
|
|
288
|
+
command: `mkdir -p ${shellQuote(workDir)} ${shellQuote(bridgeStateDir)}`,
|
|
289
|
+
abortSignal: startOpts.abortSignal,
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
await markBridgeStarting({
|
|
293
|
+
sandbox: session,
|
|
294
|
+
bridgeStateDir,
|
|
295
|
+
bridgeType: 'deepagents',
|
|
296
|
+
abortSignal: startOpts.abortSignal,
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
const proc = await session.spawn({
|
|
300
|
+
command: `node ${BOOTSTRAP_DIR}/bridge.mjs --workdir ${shellQuote(workDir)} --bridge-state-dir ${shellQuote(bridgeStateDir)} --bootstrap-dir ${shellQuote(BOOTSTRAP_DIR)}`,
|
|
301
|
+
env,
|
|
302
|
+
abortSignal: startOpts.abortSignal,
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
const { port: boundPort } = await waitForBridgeReady({
|
|
306
|
+
proc,
|
|
307
|
+
sandbox: session,
|
|
308
|
+
bridgeStateDir,
|
|
309
|
+
bridgeType: 'deepagents',
|
|
310
|
+
timeoutMs,
|
|
311
|
+
abortSignal: startOpts.abortSignal,
|
|
312
|
+
createTimeoutError: () =>
|
|
313
|
+
new Error('deepagents bridge did not become ready in time.'),
|
|
314
|
+
createExitError: () =>
|
|
315
|
+
new Error('deepagents bridge exited before becoming ready.'),
|
|
316
|
+
});
|
|
317
|
+
void forwardBridgeStderr(proc.stderr);
|
|
318
|
+
|
|
319
|
+
const wsUrl =
|
|
320
|
+
(await sandboxSession.getPortUrl({
|
|
321
|
+
port: boundPort,
|
|
322
|
+
protocol: 'ws',
|
|
323
|
+
})) + `?agent_bridge_token=${encodeURIComponent(token)}`;
|
|
324
|
+
|
|
325
|
+
const channel: DeepAgentsChannel = new SandboxChannel({
|
|
326
|
+
connect: () => openWebSocket(wsUrl),
|
|
327
|
+
outboundSchema: outboundMessageSchema,
|
|
328
|
+
onDiagnostic,
|
|
329
|
+
});
|
|
330
|
+
await channel.open();
|
|
331
|
+
|
|
332
|
+
return createSession({
|
|
333
|
+
sessionId: startOpts.sessionId,
|
|
334
|
+
channel,
|
|
335
|
+
proc,
|
|
336
|
+
model: settings.model,
|
|
337
|
+
bridgePort: boundPort,
|
|
338
|
+
bridgeToken: token,
|
|
339
|
+
sandboxId,
|
|
340
|
+
isResume,
|
|
341
|
+
// Freshly spawned bridge — it must receive the instructions on the first prompt.
|
|
342
|
+
attached: false,
|
|
343
|
+
skillsPaths,
|
|
344
|
+
permissionMode,
|
|
345
|
+
recursionLimit: settings.recursionLimit,
|
|
346
|
+
});
|
|
347
|
+
},
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function resolveBridgePort(
|
|
352
|
+
sandboxSession: HarnessV1NetworkSandboxSession,
|
|
353
|
+
override: number | undefined,
|
|
354
|
+
): number {
|
|
355
|
+
if (override !== undefined) return override;
|
|
356
|
+
if (sandboxSession.ports.length > 0) return sandboxSession.ports[0];
|
|
357
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
358
|
+
harnessId: 'deepagents',
|
|
359
|
+
message:
|
|
360
|
+
'The deepagents harness needs a TCP port exposed by the sandbox. ' +
|
|
361
|
+
'Create the sandbox with `ports: [<port>]` or pass `createDeepAgents({ port })`.',
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
async function readBridgeAsset(name: string): Promise<string> {
|
|
366
|
+
const candidates = [
|
|
367
|
+
new URL(`./bridge/${name}`, import.meta.url),
|
|
368
|
+
new URL(`../bridge/${name}`, import.meta.url),
|
|
369
|
+
];
|
|
370
|
+
let lastErr: unknown;
|
|
371
|
+
for (const url of candidates) {
|
|
372
|
+
try {
|
|
373
|
+
return await readFile(fileURLToPath(url), 'utf8');
|
|
374
|
+
} catch (err) {
|
|
375
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
376
|
+
if (code !== 'ENOENT') throw err;
|
|
377
|
+
lastErr = err;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
throw lastErr ?? new Error(`bridge asset not found: ${name}`);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// Resolve the sandbox $HOME so skills can be written outside the work dir.
|
|
384
|
+
async function resolveSandboxHomeDir({
|
|
385
|
+
sandbox,
|
|
386
|
+
abortSignal,
|
|
387
|
+
}: {
|
|
388
|
+
sandbox: ReturnType<HarnessV1NetworkSandboxSession['restricted']>;
|
|
389
|
+
abortSignal?: AbortSignal;
|
|
390
|
+
}): Promise<string> {
|
|
391
|
+
const result = await sandbox.run({
|
|
392
|
+
command: 'printf "%s" "$HOME"',
|
|
393
|
+
abortSignal,
|
|
394
|
+
});
|
|
395
|
+
const homeDir = result.stdout.trim();
|
|
396
|
+
if (result.exitCode !== 0 || !homeDir.startsWith('/')) {
|
|
397
|
+
throw new Error(
|
|
398
|
+
`Unable to resolve sandbox HOME directory: ${result.stderr || result.stdout}`,
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
return homeDir;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// Materialize each skill as a native deepagents `<name>/SKILL.md` folder (+ attached files) under the given root, so skills load on demand and file references resolve.
|
|
405
|
+
async function writeSkills({
|
|
406
|
+
sandbox,
|
|
407
|
+
root,
|
|
408
|
+
skills,
|
|
409
|
+
abortSignal,
|
|
410
|
+
}: {
|
|
411
|
+
sandbox: ReturnType<HarnessV1NetworkSandboxSession['restricted']>;
|
|
412
|
+
root: string;
|
|
413
|
+
skills: ReadonlyArray<HarnessV1Skill>;
|
|
414
|
+
abortSignal?: AbortSignal;
|
|
415
|
+
}): Promise<void> {
|
|
416
|
+
for (const skill of skills) {
|
|
417
|
+
const name = safeSkillName(skill.name);
|
|
418
|
+
const skillDir = `${root}/${name}`;
|
|
419
|
+
// SKILL.md `name` must match the parent directory name (deepagents requirement).
|
|
420
|
+
const content = `---\nname: ${name}\ndescription: ${skill.description}\n---\n\n${skill.content}`;
|
|
421
|
+
await sandbox.writeTextFile({
|
|
422
|
+
path: `${skillDir}/SKILL.md`,
|
|
423
|
+
content,
|
|
424
|
+
abortSignal,
|
|
425
|
+
});
|
|
426
|
+
for (const file of skill.files ?? []) {
|
|
427
|
+
await sandbox.writeTextFile({
|
|
428
|
+
path: `${skillDir}/${safeSkillFilePath(name, file.path)}`,
|
|
429
|
+
content: file.content,
|
|
430
|
+
abortSignal,
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function safeSkillName(name: string): string {
|
|
437
|
+
if (!/^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/.test(name)) {
|
|
438
|
+
throw new Error(
|
|
439
|
+
`Invalid deepagents skill name '${name}': must be lowercase alphanumeric with hyphens, 1-64 chars.`,
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
return name;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function safeSkillFilePath(skillName: string, filePath: string): string {
|
|
446
|
+
const normalized = filePath.replace(/^\/+/, '');
|
|
447
|
+
if (
|
|
448
|
+
normalized === '' ||
|
|
449
|
+
normalized.startsWith('../') ||
|
|
450
|
+
normalized.includes('/../') ||
|
|
451
|
+
normalized.endsWith('/..')
|
|
452
|
+
) {
|
|
453
|
+
throw new Error(`Invalid skill file path for '${skillName}': ${filePath}`);
|
|
454
|
+
}
|
|
455
|
+
return normalized;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function shellQuote(value: string): string {
|
|
459
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function openWebSocket(url: string): Promise<WebSocket> {
|
|
463
|
+
return new Promise((resolve, reject) => {
|
|
464
|
+
const ws = new WebSocket(url);
|
|
465
|
+
const onOpen = () => {
|
|
466
|
+
ws.off('error', onError);
|
|
467
|
+
resolve(ws);
|
|
468
|
+
};
|
|
469
|
+
const onError = (err: Error) => {
|
|
470
|
+
ws.off('open', onOpen);
|
|
471
|
+
reject(err);
|
|
472
|
+
};
|
|
473
|
+
ws.once('open', onOpen);
|
|
474
|
+
ws.once('error', onError);
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
async function forwardBridgeStderr(
|
|
479
|
+
stream: ReadableStream<Uint8Array>,
|
|
480
|
+
): Promise<void> {
|
|
481
|
+
try {
|
|
482
|
+
const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
|
|
483
|
+
while (true) {
|
|
484
|
+
const { value, done } = await reader.read();
|
|
485
|
+
if (done) return;
|
|
486
|
+
if (value) {
|
|
487
|
+
const trimmed = value.endsWith('\n') ? value.slice(0, -1) : value;
|
|
488
|
+
if (trimmed.length > 0) {
|
|
489
|
+
// eslint-disable-next-line no-console
|
|
490
|
+
console.log(`[bridge stderr] ${trimmed}`);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
} catch {
|
|
495
|
+
// Reader errors are non-fatal — best-effort diagnostic only.
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function createSession({
|
|
500
|
+
sessionId,
|
|
501
|
+
channel,
|
|
502
|
+
proc,
|
|
503
|
+
model,
|
|
504
|
+
bridgePort,
|
|
505
|
+
bridgeToken,
|
|
506
|
+
sandboxId,
|
|
507
|
+
isResume,
|
|
508
|
+
attached,
|
|
509
|
+
skillsPaths,
|
|
510
|
+
permissionMode,
|
|
511
|
+
recursionLimit,
|
|
512
|
+
}: {
|
|
513
|
+
sessionId: string;
|
|
514
|
+
channel: DeepAgentsChannel;
|
|
515
|
+
// Undefined on attach — the live bridge was spawned by another process.
|
|
516
|
+
proc: Experimental_SandboxProcess | undefined;
|
|
517
|
+
model: string | undefined;
|
|
518
|
+
bridgePort: number;
|
|
519
|
+
bridgeToken: string;
|
|
520
|
+
sandboxId: string;
|
|
521
|
+
isResume: boolean;
|
|
522
|
+
// True only when attaching to a live bridge that already built the agent with
|
|
523
|
+
// its instructions. A fresh spawn (incl. a respawn on attach failure or a
|
|
524
|
+
// stop-resume) starts a new bridge that must receive the instructions again.
|
|
525
|
+
attached: boolean;
|
|
526
|
+
skillsPaths?: string[];
|
|
527
|
+
permissionMode?: HarnessV1PermissionMode;
|
|
528
|
+
recursionLimit?: number;
|
|
529
|
+
}): HarnessV1Session {
|
|
530
|
+
let stopped = false;
|
|
531
|
+
let instructionsApplied = attached;
|
|
532
|
+
|
|
533
|
+
const wireTurn = (turnOpts: {
|
|
534
|
+
emit: (event: HarnessV1StreamPart) => void;
|
|
535
|
+
abortSignal?: AbortSignal;
|
|
536
|
+
}): HarnessV1PromptControl => {
|
|
537
|
+
let pendingResolve: (() => void) | undefined;
|
|
538
|
+
let pendingReject: ((err: unknown) => void) | undefined;
|
|
539
|
+
const done = new Promise<void>((resolve, reject) => {
|
|
540
|
+
pendingResolve = resolve;
|
|
541
|
+
pendingReject = reject;
|
|
542
|
+
});
|
|
543
|
+
|
|
544
|
+
const unsubs: Array<() => void> = [];
|
|
545
|
+
const forward = (event: HarnessV1StreamPart) => {
|
|
546
|
+
try {
|
|
547
|
+
turnOpts.emit(event);
|
|
548
|
+
} catch {}
|
|
549
|
+
};
|
|
550
|
+
|
|
551
|
+
const eventTypes = [
|
|
552
|
+
'stream-start',
|
|
553
|
+
'text-start',
|
|
554
|
+
'text-delta',
|
|
555
|
+
'text-end',
|
|
556
|
+
'reasoning-start',
|
|
557
|
+
'reasoning-delta',
|
|
558
|
+
'reasoning-end',
|
|
559
|
+
'tool-call',
|
|
560
|
+
'tool-approval-request',
|
|
561
|
+
'tool-result',
|
|
562
|
+
'file-change',
|
|
563
|
+
'finish-step',
|
|
564
|
+
'raw',
|
|
565
|
+
] as const;
|
|
566
|
+
let isSettled = false;
|
|
567
|
+
const settleSuccess = () => {
|
|
568
|
+
if (isSettled) return;
|
|
569
|
+
isSettled = true;
|
|
570
|
+
for (const u of unsubs) u();
|
|
571
|
+
pendingResolve!();
|
|
572
|
+
};
|
|
573
|
+
const settleError = (err: unknown) => {
|
|
574
|
+
if (isSettled) return;
|
|
575
|
+
isSettled = true;
|
|
576
|
+
for (const u of unsubs) u();
|
|
577
|
+
pendingReject!(err);
|
|
578
|
+
};
|
|
579
|
+
|
|
580
|
+
for (const type of eventTypes) {
|
|
581
|
+
unsubs.push(channel.on(type, msg => forward(msg)));
|
|
582
|
+
}
|
|
583
|
+
unsubs.push(
|
|
584
|
+
channel.on('finish', msg => {
|
|
585
|
+
forward(msg);
|
|
586
|
+
settleSuccess();
|
|
587
|
+
}),
|
|
588
|
+
);
|
|
589
|
+
unsubs.push(
|
|
590
|
+
channel.on('error', msg => {
|
|
591
|
+
forward(msg);
|
|
592
|
+
settleError(msg.error);
|
|
593
|
+
}),
|
|
594
|
+
);
|
|
595
|
+
|
|
596
|
+
// A `'suspended'` close is a graceful slice-boundary freeze (suspend/detach keep the bridge alive for continuation); end the turn cleanly. Any other close is an unexpected bridge failure.
|
|
597
|
+
const onClose = (_code: number, reason: string) => {
|
|
598
|
+
if (isSettled) return;
|
|
599
|
+
if (reason === 'suspended') {
|
|
600
|
+
settleSuccess();
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
settleError(
|
|
604
|
+
new Error('deepagents bridge closed before the turn finished.'),
|
|
605
|
+
);
|
|
606
|
+
};
|
|
607
|
+
channel.onClose(onClose);
|
|
608
|
+
|
|
609
|
+
const onAbort = () => {
|
|
610
|
+
if (isSettled) return;
|
|
611
|
+
try {
|
|
612
|
+
channel.send({ type: 'abort' });
|
|
613
|
+
} catch {}
|
|
614
|
+
settleError(
|
|
615
|
+
turnOpts.abortSignal?.reason ??
|
|
616
|
+
new DOMException('Aborted', 'AbortError'),
|
|
617
|
+
);
|
|
618
|
+
};
|
|
619
|
+
if (turnOpts.abortSignal) {
|
|
620
|
+
if (turnOpts.abortSignal.aborted) {
|
|
621
|
+
onAbort();
|
|
622
|
+
} else {
|
|
623
|
+
turnOpts.abortSignal.addEventListener('abort', onAbort, { once: true });
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
return {
|
|
628
|
+
submitToolResult: async input => {
|
|
629
|
+
channel.send({
|
|
630
|
+
type: 'tool-result',
|
|
631
|
+
toolCallId: input.toolCallId,
|
|
632
|
+
output: input.output,
|
|
633
|
+
isError: input.isError,
|
|
634
|
+
});
|
|
635
|
+
},
|
|
636
|
+
submitUserMessage: async text => {
|
|
637
|
+
channel.send({ type: 'user-message', text });
|
|
638
|
+
},
|
|
639
|
+
submitToolApproval: async input => {
|
|
640
|
+
channel.send({
|
|
641
|
+
type: 'tool-approval-response',
|
|
642
|
+
approvalId: input.approvalId,
|
|
643
|
+
approved: input.approved,
|
|
644
|
+
...(input.reason != null ? { reason: input.reason } : {}),
|
|
645
|
+
});
|
|
646
|
+
},
|
|
647
|
+
done,
|
|
648
|
+
};
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
const unsupported = (capability: string): never => {
|
|
652
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
653
|
+
harnessId: 'deepagents',
|
|
654
|
+
message: `Harness 'deepagents' does not support ${capability} yet.`,
|
|
655
|
+
});
|
|
656
|
+
};
|
|
657
|
+
|
|
658
|
+
return {
|
|
659
|
+
sessionId,
|
|
660
|
+
isResume,
|
|
661
|
+
modelId: model,
|
|
662
|
+
doPromptTurn: async promptOpts => {
|
|
663
|
+
const control = wireTurn({
|
|
664
|
+
emit: promptOpts.emit,
|
|
665
|
+
abortSignal: promptOpts.abortSignal,
|
|
666
|
+
});
|
|
667
|
+
|
|
668
|
+
const applyInstructions =
|
|
669
|
+
!instructionsApplied && !!promptOpts.instructions;
|
|
670
|
+
instructionsApplied = true;
|
|
671
|
+
|
|
672
|
+
channel.send({
|
|
673
|
+
type: 'start',
|
|
674
|
+
prompt: extractUserText(promptOpts.prompt),
|
|
675
|
+
...(applyInstructions ? { instructions: promptOpts.instructions } : {}),
|
|
676
|
+
tools: (promptOpts.tools ?? []).map(t => ({
|
|
677
|
+
name: t.name,
|
|
678
|
+
description: t.description,
|
|
679
|
+
inputSchema: t.inputSchema,
|
|
680
|
+
})),
|
|
681
|
+
...(model ? { model } : {}),
|
|
682
|
+
...(skillsPaths?.length ? { skillsPaths } : {}),
|
|
683
|
+
...(permissionMode ? { permissionMode } : {}),
|
|
684
|
+
...(recursionLimit != null ? { recursionLimit } : {}),
|
|
685
|
+
});
|
|
686
|
+
|
|
687
|
+
return control;
|
|
688
|
+
},
|
|
689
|
+
doContinueTurn: async continueOpts => {
|
|
690
|
+
// Attach/replay: doStart opened with `{ resume: true }` so the bridge replays past the cursor; no `start` is sent (that would clear the replay log).
|
|
691
|
+
return wireTurn({
|
|
692
|
+
emit: continueOpts.emit,
|
|
693
|
+
abortSignal: continueOpts.abortSignal,
|
|
694
|
+
});
|
|
695
|
+
},
|
|
696
|
+
doSuspendTurn: async () => {
|
|
697
|
+
if (stopped) {
|
|
698
|
+
throw new Error(
|
|
699
|
+
`deepagents session ${sessionId} is stopped; cannot suspend.`,
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
stopped = true;
|
|
703
|
+
// Freeze the active turn at the cursor, leaving the bridge running so the next slice replays the tail.
|
|
704
|
+
const lastSeenEventId = await channel.suspend();
|
|
705
|
+
const payload: HarnessV1ContinueTurnState = {
|
|
706
|
+
type: 'continue-turn',
|
|
707
|
+
harnessId: 'deepagents',
|
|
708
|
+
specificationVersion: 'harness-v1',
|
|
709
|
+
data: {
|
|
710
|
+
bridge: {
|
|
711
|
+
port: bridgePort,
|
|
712
|
+
token: bridgeToken,
|
|
713
|
+
lastSeenEventId,
|
|
714
|
+
sandboxId,
|
|
715
|
+
},
|
|
716
|
+
},
|
|
717
|
+
};
|
|
718
|
+
return payload;
|
|
719
|
+
},
|
|
720
|
+
doDetach: async () => {
|
|
721
|
+
if (stopped) {
|
|
722
|
+
throw new Error(
|
|
723
|
+
`deepagents session ${sessionId} is already stopped; cannot detach.`,
|
|
724
|
+
);
|
|
725
|
+
}
|
|
726
|
+
stopped = true;
|
|
727
|
+
// Park between turns: close the host socket but leave the bridge running for a later reattach via these coords.
|
|
728
|
+
const lastSeenEventId = await channel.suspend();
|
|
729
|
+
const payload: HarnessV1ResumeSessionState = {
|
|
730
|
+
type: 'resume-session',
|
|
731
|
+
harnessId: 'deepagents',
|
|
732
|
+
specificationVersion: 'harness-v1',
|
|
733
|
+
data: {
|
|
734
|
+
bridge: {
|
|
735
|
+
port: bridgePort,
|
|
736
|
+
token: bridgeToken,
|
|
737
|
+
lastSeenEventId,
|
|
738
|
+
sandboxId,
|
|
739
|
+
},
|
|
740
|
+
},
|
|
741
|
+
};
|
|
742
|
+
return payload;
|
|
743
|
+
},
|
|
744
|
+
doCompact: async () => unsupported('manual compaction'),
|
|
745
|
+
doStop: async () => {
|
|
746
|
+
if (stopped) {
|
|
747
|
+
throw new Error(
|
|
748
|
+
`deepagents session ${sessionId} is already stopped; cannot stop.`,
|
|
749
|
+
);
|
|
750
|
+
}
|
|
751
|
+
stopped = true;
|
|
752
|
+
await teardown(channel, proc);
|
|
753
|
+
// In-memory conversation is lost on teardown; the sandbox snapshot preserves the workspace files, not the conversation.
|
|
754
|
+
const payload: HarnessV1ResumeSessionState = {
|
|
755
|
+
type: 'resume-session',
|
|
756
|
+
harnessId: 'deepagents',
|
|
757
|
+
specificationVersion: 'harness-v1',
|
|
758
|
+
data: {},
|
|
759
|
+
};
|
|
760
|
+
return payload;
|
|
761
|
+
},
|
|
762
|
+
doDestroy: async () => {
|
|
763
|
+
if (stopped) return;
|
|
764
|
+
stopped = true;
|
|
765
|
+
await teardown(channel, proc);
|
|
766
|
+
},
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
async function teardown(
|
|
771
|
+
channel: DeepAgentsChannel,
|
|
772
|
+
proc: Experimental_SandboxProcess | undefined,
|
|
773
|
+
): Promise<void> {
|
|
774
|
+
channel.beginClose();
|
|
775
|
+
try {
|
|
776
|
+
if (!channel.isClosed()) {
|
|
777
|
+
channel.send({ type: 'shutdown' });
|
|
778
|
+
}
|
|
779
|
+
} catch {}
|
|
780
|
+
let stopTimer: ReturnType<typeof setTimeout> | undefined;
|
|
781
|
+
try {
|
|
782
|
+
if (proc) {
|
|
783
|
+
await Promise.race([
|
|
784
|
+
proc.wait(),
|
|
785
|
+
new Promise<void>(resolve => {
|
|
786
|
+
stopTimer = setTimeout(resolve, 5000);
|
|
787
|
+
stopTimer.unref?.();
|
|
788
|
+
}),
|
|
789
|
+
]);
|
|
790
|
+
}
|
|
791
|
+
} finally {
|
|
792
|
+
if (stopTimer) clearTimeout(stopTimer);
|
|
793
|
+
try {
|
|
794
|
+
await proc?.kill();
|
|
795
|
+
} catch {}
|
|
796
|
+
channel.close();
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// Reduce the prompt to plain user text; non-text parts are unsupported.
|
|
801
|
+
function extractUserText(prompt: HarnessV1Prompt): string {
|
|
802
|
+
if (typeof prompt === 'string') return prompt;
|
|
803
|
+
const { content } = prompt;
|
|
804
|
+
if (typeof content === 'string') return content;
|
|
805
|
+
const parts: string[] = [];
|
|
806
|
+
for (const part of content) {
|
|
807
|
+
if (part.type !== 'text') {
|
|
808
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
809
|
+
harnessId: 'deepagents',
|
|
810
|
+
message: `The deepagents harness does not yet support user message parts of type '${part.type}'. Pass a string or a user message whose content contains only text parts.`,
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
parts.push(part.text);
|
|
814
|
+
}
|
|
815
|
+
return parts.join('\n\n');
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
export { DEEPAGENTS_BUILTIN_TOOLS, DEEPAGENTS_DEFAULT_CONTEXT_WINDOW };
|