@deepagents/context 4.0.0 → 4.2.0

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.
Files changed (48) hide show
  1. package/README.md +25 -16
  2. package/dist/browser.js +18 -8
  3. package/dist/browser.js.map +2 -2
  4. package/dist/index.js +2551 -1596
  5. package/dist/index.js.map +4 -4
  6. package/dist/lib/agent.d.ts.map +1 -1
  7. package/dist/lib/engine.d.ts +11 -4
  8. package/dist/lib/engine.d.ts.map +1 -1
  9. package/dist/lib/fragments/message/user.d.ts +28 -14
  10. package/dist/lib/fragments/message/user.d.ts.map +1 -1
  11. package/dist/lib/sandbox/agent-os-sandbox.d.ts +2 -2
  12. package/dist/lib/sandbox/agent-os-sandbox.d.ts.map +1 -1
  13. package/dist/lib/sandbox/apple-container-sandbox-errors.d.ts +44 -0
  14. package/dist/lib/sandbox/apple-container-sandbox-errors.d.ts.map +1 -0
  15. package/dist/lib/sandbox/apple-container-sandbox.d.ts +130 -0
  16. package/dist/lib/sandbox/apple-container-sandbox.d.ts.map +1 -0
  17. package/dist/lib/sandbox/bash-meta.d.ts +0 -3
  18. package/dist/lib/sandbox/bash-meta.d.ts.map +1 -1
  19. package/dist/lib/sandbox/bash-tool.d.ts +3 -3
  20. package/dist/lib/sandbox/bash-tool.d.ts.map +1 -1
  21. package/dist/lib/sandbox/cli-process.d.ts +24 -0
  22. package/dist/lib/sandbox/cli-process.d.ts.map +1 -0
  23. package/dist/lib/sandbox/container-engine.d.ts +150 -0
  24. package/dist/lib/sandbox/container-engine.d.ts.map +1 -0
  25. package/dist/lib/sandbox/container-sandbox-errors.d.ts +10 -0
  26. package/dist/lib/sandbox/container-sandbox-errors.d.ts.map +1 -0
  27. package/dist/lib/sandbox/container-sandbox.d.ts +90 -0
  28. package/dist/lib/sandbox/container-sandbox.d.ts.map +1 -0
  29. package/dist/lib/sandbox/daytona-sandbox.d.ts +2 -2
  30. package/dist/lib/sandbox/daytona-sandbox.d.ts.map +1 -1
  31. package/dist/lib/sandbox/docker-sandbox-errors.d.ts +2 -2
  32. package/dist/lib/sandbox/docker-sandbox-errors.d.ts.map +1 -1
  33. package/dist/lib/sandbox/docker-sandbox.d.ts +122 -218
  34. package/dist/lib/sandbox/docker-sandbox.d.ts.map +1 -1
  35. package/dist/lib/sandbox/index.d.ts +5 -0
  36. package/dist/lib/sandbox/index.d.ts.map +1 -1
  37. package/dist/lib/sandbox/microsandbox-sandbox.d.ts +93 -0
  38. package/dist/lib/sandbox/microsandbox-sandbox.d.ts.map +1 -0
  39. package/dist/lib/sandbox/shell-quote.d.ts +2 -2
  40. package/dist/lib/sandbox/strace/index.d.ts +6 -21
  41. package/dist/lib/sandbox/strace/index.d.ts.map +1 -1
  42. package/dist/lib/sandbox/strace/index.js +18 -7
  43. package/dist/lib/sandbox/strace/index.js.map +2 -2
  44. package/dist/lib/sandbox/types.d.ts +22 -3
  45. package/dist/lib/sandbox/types.d.ts.map +1 -1
  46. package/dist/lib/sandbox/virtual-sandbox.d.ts +2 -2
  47. package/dist/lib/sandbox/virtual-sandbox.d.ts.map +1 -1
  48. package/package.json +14 -8
@@ -0,0 +1,93 @@
1
+ import type { SandboxBuilder } from 'microsandbox';
2
+ import type { DisposableSandbox, SandboxReadinessOptions } from './types.ts';
3
+ export declare const MICROSANDBOX_DEFAULT_DESTINATION = "/workspace";
4
+ export interface MicrosandboxSandboxOptions extends SandboxReadinessOptions {
5
+ /**
6
+ * Stable sandbox name. When provided, creation uses get-or-create
7
+ * semantics: attach to the running sandbox of this name, resume it if it is
8
+ * stopped (rootfs state intact), otherwise create it fresh. `dispose()`
9
+ * stops the microVM but never removes it — the next
10
+ * `createMicrosandboxSandbox({ name })` resumes where it left off.
11
+ *
12
+ * When omitted, an ephemeral sandbox with a generated name is created and
13
+ * fully removed on `dispose()`.
14
+ */
15
+ name?: string;
16
+ /** OCI image to boot (default `'alpine'`). Ignored when attaching. */
17
+ image?: string;
18
+ /** Number of virtual CPUs. */
19
+ cpus?: number;
20
+ /** Memory in MiB. */
21
+ memory?: number;
22
+ /** Environment variables baked into the sandbox at boot. */
23
+ env?: Record<string, string>;
24
+ /**
25
+ * Default working directory, created at boot (default `'/workspace'`).
26
+ * Microsandbox images default to `/`, and common images ship no
27
+ * `/workspace`, so the factory creates it — pass this same path as
28
+ * `createBashTool`'s `destination`.
29
+ */
30
+ workdir?: string;
31
+ /**
32
+ * Replace an existing sandbox with the same name instead of attaching to
33
+ * it. Requires `name`.
34
+ */
35
+ replace?: boolean;
36
+ /** Per-command timeout in milliseconds for `executeCommand`. */
37
+ commandTimeout?: number;
38
+ /**
39
+ * Escape hatch over the SDK builder for everything without a plain option
40
+ * (volumes, network policy, secrets, user, idle timeout, …). Applied after
41
+ * the factory's own setters, so it can override them. Only runs on
42
+ * creation, not when attaching to an existing sandbox.
43
+ */
44
+ configure?: (builder: SandboxBuilder) => SandboxBuilder;
45
+ }
46
+ /**
47
+ * Named `MicrosandboxSandboxError` (not `MicrosandboxError`) because the SDK
48
+ * itself exports a `MicrosandboxError` base class and this module is
49
+ * re-exported through the package barrel.
50
+ */
51
+ export declare class MicrosandboxSandboxError extends Error {
52
+ constructor(message: string, cause?: Error);
53
+ }
54
+ export declare class MicrosandboxNotAvailableError extends MicrosandboxSandboxError {
55
+ constructor(cause?: Error);
56
+ }
57
+ export declare class MicrosandboxCreationError extends MicrosandboxSandboxError {
58
+ constructor(message: string, cause?: Error);
59
+ }
60
+ export declare class MicrosandboxCommandError extends MicrosandboxSandboxError {
61
+ constructor(message: string, cause?: Error);
62
+ }
63
+ /**
64
+ * Creates a sandbox backed by a microsandbox microVM.
65
+ *
66
+ * Each sandbox is a hardware-isolated VM with its own Linux kernel, booted
67
+ * in-process through the SDK's native binding — no daemon, no API key.
68
+ * Boots standard OCI images in about a second; per-command latency inside a
69
+ * running sandbox is single-digit milliseconds.
70
+ *
71
+ * The factory never touches the SDK's process-global backend selection
72
+ * (`setDefaultBackend`) — callers targeting the cloud backend configure it
73
+ * themselves before calling this.
74
+ *
75
+ * Requires the optional peer dependency `microsandbox`.
76
+ *
77
+ * @example Ephemeral sandbox (removed on dispose)
78
+ * ```typescript
79
+ * await using sandbox = await createMicrosandboxSandbox();
80
+ * const result = await sandbox.executeCommand('echo hello');
81
+ * ```
82
+ *
83
+ * @example Named sandbox (stopped on dispose, resumed on next create)
84
+ * ```typescript
85
+ * const sandbox = await createMicrosandboxSandbox({ name: chatId });
86
+ * const { tools } = await createBashTool({
87
+ * sandbox,
88
+ * destination: MICROSANDBOX_DEFAULT_DESTINATION,
89
+ * });
90
+ * ```
91
+ */
92
+ export declare function createMicrosandboxSandbox(options?: MicrosandboxSandboxOptions): Promise<DisposableSandbox>;
93
+ //# sourceMappingURL=microsandbox-sandbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"microsandbox-sandbox.d.ts","sourceRoot":"","sources":["../../../src/lib/sandbox/microsandbox-sandbox.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAGV,cAAc,EAEf,MAAM,cAAc,CAAC;AAGtB,OAAO,KAAK,EACV,iBAAiB,EAIjB,uBAAuB,EAExB,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,gCAAgC,eAAe,CAAC;AAO7D,MAAM,WAAW,0BAA2B,SAAQ,uBAAuB;IACzE;;;;;;;;;OASG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,sEAAsE;IACtE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,8BAA8B;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,qBAAqB;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4DAA4D;IAC5D,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,gEAAgE;IAChE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,cAAc,CAAC;CACzD;AAED;;;;GAIG;AACH,qBAAa,wBAAyB,SAAQ,KAAK;gBACrC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK;CAK3C;AAED,qBAAa,6BAA8B,SAAQ,wBAAwB;gBAC7D,KAAK,CAAC,EAAE,KAAK;CAO1B;AAED,qBAAa,yBAA0B,SAAQ,wBAAwB;gBACzD,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK;CAI3C;AAED,qBAAa,wBAAyB,SAAQ,wBAAwB;gBACxD,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK;CAI3C;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,yBAAyB,CAC7C,OAAO,GAAE,0BAA+B,GACvC,OAAO,CAAC,iBAAiB,CAAC,CAiC5B"}
@@ -2,8 +2,8 @@
2
2
  * POSIX shell single-quote escape: wrap in `'...'`, replace any embedded
3
3
  * `'` with `'\''`. Safe for arbitrary content inside `sh -c`.
4
4
  *
5
- * Lives in its own zero-import module so node-builtins-only consumers (e.g. the
6
- * lean `./sandbox/strace` leaf entry) can use it without dragging in the
5
+ * Lives in its own zero-import module so lean consumers such as the
6
+ * `./sandbox/strace` leaf entry can use it without dragging in the
7
7
  * installer/runtime surface.
8
8
  */
9
9
  export declare function shellQuote(s: string): string;
@@ -58,32 +58,17 @@ export declare function matchesGlobs(path: string, include: string[], exclude?:
58
58
  * treated as transient and dropped.
59
59
  */
60
60
  export declare function parseStraceTrace(raw: string, options: ParseStraceOptions): FileChange[];
61
- /**
62
- * The minimal structural surface {@link selfTestStrace} needs from its host.
63
- * Deliberately narrower than `DisposableSandbox` so the probe can run anywhere:
64
- * a remote/docker caller passes its sandbox unchanged (it satisfies this shape
65
- * structurally), and an in-process caller (e.g. a daemon running as PID 1
66
- * inside the container) implements just these two methods over
67
- * `node:child_process` + `node:fs`.
68
- */
69
- export interface StraceHost {
70
- executeCommand(command: string): Promise<{
71
- exitCode: number;
72
- stderr: string;
73
- }>;
74
- readFile(path: string): Promise<string>;
75
- }
76
61
  /**
77
62
  * One-time probe at sandbox setup. Runs a known create/write/rename sequence
78
- * under strace and asserts the trace is clean and parseable. Throws
63
+ * under strace on the host and asserts the trace is clean and parseable. Throws
79
64
  * {@link StraceUnavailableError} (hard-fail) when ptrace is blocked, strace is
80
65
  * absent, or the trace is garbled (e.g. amd64 under Rosetta).
81
66
  *
82
- * "strace works in this sandbox" is an invariant of the (image + host kernel +
83
- * seccomp/caps) — constant across every tool call and chat turn in a given
84
- * container — so this is the consumer's once-per-container responsibility (e.g.
85
- * a daemon boot gate), NOT a per-tool cost. `createBashTool` /
67
+ * "strace works here" is an invariant of the (image + host kernel + seccomp/caps)
68
+ * — constant across every tool call and chat turn in a given container — so this
69
+ * is the consumer's once-per-container responsibility (e.g. a daemon boot gate
70
+ * running as PID 1 inside the container), NOT a per-tool cost. `createBashTool` /
86
71
  * `withStraceFileChanges` no longer call it.
87
72
  */
88
- export declare function selfTestStrace(host: StraceHost): Promise<void>;
73
+ export declare function selfTestStrace(): Promise<void>;
89
74
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/lib/sandbox/strace/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEjE,MAAM,MAAM,uBAAuB,GAC/B,gBAAgB,GAChB,gBAAgB,GAChB,mBAAmB,CAAC;AAWxB;;;;;GAKG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;IAC/C,QAAQ,CAAC,MAAM,EAAE,uBAAuB,CAAC;IACzC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC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B,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EAAE,EACjB,OAAO,CAAC,EAAE,MAAM,EAAE,GACjB,OAAO,CAKT;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,kBAAkB,GAC1B,UAAU,EAAE,CAiGd;AA6BD;;;;;;;;;;;GAWG;AACH,wBAAsB,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,CAqDpD"}
@@ -1,5 +1,7 @@
1
1
  // packages/context/src/lib/sandbox/strace/index.ts
2
+ import spawn from "nano-spawn";
2
3
  import { randomUUID } from "node:crypto";
4
+ import { readFile, rm } from "node:fs/promises";
3
5
  import { posix } from "node:path";
4
6
 
5
7
  // packages/context/src/lib/sandbox/shell-quote.ts
@@ -233,17 +235,24 @@ function parseStraceTrace(raw, options) {
233
235
  }
234
236
  var PTRACE_DENIED = /strace:[^\n]*(?:PTRACE_TRACEME|ptrace|Operation not permitted|EPERM)/i;
235
237
  var STRACE_MISSING = /strace:?\s+(?:command\s+)?not found/i;
236
- async function selfTestStrace(host) {
238
+ async function runOnHost(command) {
239
+ try {
240
+ const { stderr } = await spawn("sh", ["-c", command]);
241
+ return { exitCode: 0, stderr };
242
+ } catch (error) {
243
+ const e = error;
244
+ return { exitCode: e.exitCode ?? 1, stderr: e.stderr };
245
+ }
246
+ }
247
+ async function selfTestStrace() {
237
248
  const probeDir = `/tmp/dat-strace-${randomUUID()}`;
238
249
  const traceFile = `/tmp/dat-strace-${randomUUID()}.trace`;
239
250
  const q = shellQuote;
240
251
  const sequence = `mkdir -p ${q(probeDir)} && echo hi > ${q(`${probeDir}/a.txt`)} && mv ${q(`${probeDir}/a.txt`)} ${q(`${probeDir}/b.txt`)} && echo more > ${q(`${probeDir}/c.txt`)}`;
241
252
  const wrapped = buildStraceCommand(sequence, traceFile, "/tmp");
242
- let result;
243
- let raw = "";
244
253
  try {
245
- result = await host.executeCommand(wrapped);
246
- raw = await host.readFile(traceFile).catch(() => "");
254
+ const result = await runOnHost(wrapped);
255
+ const raw = await readFile(traceFile, "utf8").catch(() => "");
247
256
  const diagnostics = `exit=${result.exitCode}
248
257
  stderr=${result.stderr}
249
258
  trace[0:600]=${raw.slice(0, 600)}`;
@@ -269,8 +278,10 @@ trace[0:600]=${raw.slice(0, 600)}`;
269
278
  throw new StraceUnavailableError("trace-unparseable", diagnostics);
270
279
  }
271
280
  } finally {
272
- void host.executeCommand(`rm -rf ${q(probeDir)} ${q(traceFile)}`).catch(() => {
273
- });
281
+ await Promise.allSettled([
282
+ rm(probeDir, { recursive: true, force: true }),
283
+ rm(traceFile, { force: true })
284
+ ]);
274
285
  }
275
286
  }
276
287
  export {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/lib/sandbox/strace/index.ts", "../../../../src/lib/sandbox/shell-quote.ts"],
4
- "sourcesContent": ["import { randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\n\nimport { shellQuote } from '../shell-quote.ts';\nimport type { FileChange } from './file-change.ts';\n\nexport type { FileChange, FileChangeOp } from './file-change.ts';\n\nexport type StraceUnavailableReason =\n | 'ptrace-blocked'\n | 'strace-missing'\n | 'trace-unparseable';\n\nconst REASON_HINT: Record<StraceUnavailableReason, string> = {\n 'ptrace-blocked':\n 'ptrace is denied by the sandbox runtime. Modern Docker permits it by default; on a hardened host, relax the runtime seccomp/ptrace policy (allow the ptrace syscall, or add the SYS_PTRACE capability).',\n 'strace-missing':\n 'strace is not installed in the sandbox image. Bake `strace` into the image.',\n 'trace-unparseable':\n 'strace ran but its output is unusable \u2014 the sandbox is likely running under emulation (e.g. amd64 via Rosetta). Use a native-architecture sandbox.',\n};\n\n/**\n * Thrown by {@link selfTestStrace} when per-command strace tracking cannot be\n * used. `reason` lets callers branch (fix-image vs fix-caps vs fix-arch). This\n * is a hard failure by design \u2014 there is no silent degrade to the snapshot\n * observer.\n */\nexport class StraceUnavailableError extends Error {\n readonly reason: StraceUnavailableReason;\n readonly diagnostics: string;\n\n constructor(reason: StraceUnavailableReason, diagnostics: string) {\n super(\n `strace file-change tracking unavailable (${reason}): ${REASON_HINT[reason]}`,\n );\n this.name = 'StraceUnavailableError';\n this.reason = reason;\n this.diagnostics = diagnostics;\n }\n}\n\nconst STRACE_FLAGS = '-f -y -qq -e trace=%file,write,pwrite64,writev';\n\n/**\n * Wraps `command` so its filesystem syscalls are traced to `traceFile`. Both\n * the inner command and this wrapper are re-parsed by a shell (`sh -c`), so the\n * single-quoting via {@link shellQuote} composes with the backend's own\n * `sh -c`. strace propagates the traced command's exit code. The `mkdir -p`\n * runs before strace (so it isn't traced) and self-heals the trace dir per\n * command \u2014 if it ever disappears mid-session, the next command recreates it\n * rather than strace failing to open `-o` and skipping the command entirely.\n */\nexport function buildStraceCommand(\n command: string,\n traceFile: string,\n traceDir: string,\n): string {\n return (\n `mkdir -p ${shellQuote(traceDir)} 2>/dev/null; ` +\n `strace ${STRACE_FLAGS} -o ${shellQuote(traceFile)} -- sh -c ${shellQuote(command)}`\n );\n}\n\n/**\n * Like {@link buildStraceCommand}, but dumps the (base64) trace inline on stdout\n * after `sentinel`, then exits with the traced command's code. This lets one\n * `executeCommand` round-trip carry both the command output and its trace \u2014 no\n * second `readFile` exec to pull the trace out of the container. Pair with\n * {@link splitTracedOutput}. `sentinel` must be unguessable (a UUID) so the\n * command's own stdout cannot contain it. `base64` keeps the trace stream-safe\n * and its stderr is dropped so a missing trace (strace failed) doesn't leak into\n * the command's stderr.\n */\nexport function buildTracedCommand(\n command: string,\n traceFile: string,\n traceDir: string,\n sentinel: string,\n): string {\n return (\n `mkdir -p ${shellQuote(traceDir)} 2>/dev/null; ` +\n `strace ${STRACE_FLAGS} -o ${shellQuote(traceFile)} -- sh -c ${shellQuote(command)}; ` +\n `__dat_rc=$?; ` +\n `printf '\\\\n%s\\\\n' ${shellQuote(sentinel)}; ` +\n `base64 ${shellQuote(traceFile)} 2>/dev/null; ` +\n `rm -f ${shellQuote(traceFile)} 2>/dev/null; ` +\n `exit $__dat_rc`\n );\n}\n\n/**\n * Split {@link buildTracedCommand} output into the command's own stdout and its\n * decoded strace trace. A missing sentinel (strace produced nothing) yields an\n * empty trace so the caller degrades to \"no changes\".\n */\nexport function splitTracedOutput(\n stdout: string,\n sentinel: string,\n): { stdout: string; trace: string } {\n const marker = `\\n${sentinel}\\n`;\n const at = stdout.indexOf(marker);\n if (at === -1) return { stdout, trace: '' };\n const base64 = stdout.slice(at + marker.length);\n return {\n stdout: stdout.slice(0, at),\n trace: base64 ? Buffer.from(base64, 'base64').toString('utf8') : '',\n };\n}\n\n// An open is a definite write only when it creates or truncates. Bare\n// O_WRONLY/O_RDWR/O_APPEND opens are NOT assumed to mutate \u2014 a real write()\n// syscall confirms them \u2014 so read-only-via-O_RDWR (sqlite SELECT, an editor\n// that opens then quits) doesn't produce a phantom `write`.\nconst CREATE_OR_TRUNC_FLAGS = /O_(CREAT|TRUNC)/;\nconst RENAME_SYSCALLS = new Set(['rename', 'renameat', 'renameat2']);\nconst DELETE_SYSCALLS = new Set(['unlink', 'unlinkat', 'rmdir']);\nconst MKDIR_SYSCALLS = new Set(['mkdir', 'mkdirat']);\nconst LINK_SYSCALLS = new Set(['link', 'linkat', 'symlink', 'symlinkat']);\nconst OPEN_SYSCALLS = new Set(['open', 'openat', 'openat2', 'creat']);\nconst WRITE_SYSCALLS = new Set([\n 'write',\n 'pwrite64',\n 'pwrite',\n 'writev',\n 'pwritev2',\n]);\nconst TRUNCATE_SYSCALLS = new Set(['truncate', 'ftruncate']);\n\ninterface ParsedCall {\n syscall: string;\n args: string;\n retval: string;\n errno?: string;\n}\n\n/** Reassemble `<unfinished \u2026>` / `<\u2026 resumed>` syscall splits per PID. */\nfunction stitchLines(raw: string): string[] {\n const pending = new Map<string, string>();\n const out: string[] = [];\n for (const original of raw.split('\\n')) {\n const line = original.trimEnd();\n if (!line) continue;\n const pid = line.match(/^\\s*(\\d+)\\s+/)?.[1] ?? '0';\n if (/<unfinished \\.\\.\\.>\\s*$/.test(line)) {\n pending.set(pid, line.replace(/<unfinished \\.\\.\\.>\\s*$/, ''));\n continue;\n }\n const resumed = line.match(/<\\.\\.\\.\\s+\\S+\\s+resumed>(.*)$/);\n if (resumed) {\n const head = pending.get(pid);\n pending.delete(pid);\n if (head !== undefined) out.push(head + resumed[1]);\n continue;\n }\n out.push(line);\n }\n return out;\n}\n\nfunction parseCall(line: string): ParsedCall | null {\n const m = line.match(\n /^\\s*(?:\\d+\\s+)?([a-z_][a-z0-9_]*)\\((.*)\\)\\s*=\\s*(.+?)\\s*$/,\n );\n if (!m) return null;\n const [, syscall, args, rest] = m;\n const errnoMatch = rest.match(/^(-?\\d+)\\s+([A-Z][A-Z0-9_]*)/);\n if (errnoMatch) {\n return { syscall, args, retval: errnoMatch[1], errno: errnoMatch[2] };\n }\n return { syscall, args, retval: rest.split(/\\s+/)[0] };\n}\n\nconst STRACE_ESCAPE: Record<string, number> = {\n n: 0x0a,\n t: 0x09,\n r: 0x0d,\n v: 0x0b,\n f: 0x0c,\n '\"': 0x22,\n '\\\\': 0x5c,\n};\n\n/**\n * Decode one strace-rendered string. strace emits printable ASCII verbatim and\n * non-printable / non-ASCII bytes as octal `\\NNN`, plus a few `\\x` escapes. We\n * reconstruct the raw byte sequence and decode it as UTF-8 so multi-byte\n * filenames (e.g. `caf\u00E9.txt` \u2192 `\\303\\251`) round-trip instead of being mangled.\n */\nfunction decodeStraceString(s: string): string {\n const bytes: number[] = [];\n for (let i = 0; i < s.length; ) {\n if (s[i] === '\\\\' && i + 1 < s.length) {\n const octal = s.slice(i + 1, i + 4).match(/^[0-7]{1,3}/)?.[0];\n if (octal) {\n bytes.push(parseInt(octal, 8) & 0xff);\n i += 1 + octal.length;\n continue;\n }\n const mapped = STRACE_ESCAPE[s[i + 1]];\n bytes.push(mapped ?? s.charCodeAt(i + 1));\n i += 2;\n continue;\n }\n const code = s.charCodeAt(i);\n if (code < 0x80) bytes.push(code);\n else for (const b of Buffer.from(s[i], 'utf8')) bytes.push(b);\n i += 1;\n }\n return Buffer.from(bytes).toString('utf8');\n}\n\nfunction quotedStrings(args: string): string[] {\n const out: string[] = [];\n const re = /\"((?:[^\"\\\\]|\\\\.)*)\"/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(args)) !== null) {\n out.push(decodeStraceString(m[1]));\n }\n return out;\n}\n\n/** Directory path annotated on the leading dirfd (`AT_FDCWD</cwd>` / `7</dir>`). */\nfunction dirfdPath(args: string): string {\n return args.match(/^\\s*(?:AT_FDCWD|-?\\d+)<([^>]*)>/)?.[1] ?? '/';\n}\n\n/** Path annotated on the leading fd argument (`-y` output), for write syscalls. */\nfunction fdPath(args: string): string | null {\n return args.match(/^\\s*-?\\d+<([^>]*)>/)?.[1] ?? null;\n}\n\nfunction openFlags(args: string): string {\n return args.match(/\\bO_[A-Z_]+(?:\\|O_[A-Z_]+)*/)?.[0] ?? '';\n}\n\nexport interface ParseStraceOptions {\n include: string[];\n exclude?: string[];\n traceFile?: string;\n traceDir?: string;\n}\n\n/** A path is tracked when it matches an `include` glob and no `exclude` glob. */\nexport function matchesGlobs(\n path: string,\n include: string[],\n exclude?: string[],\n): boolean {\n return (\n include.some((glob) => posix.matchesGlob(path, glob)) &&\n !exclude?.some((glob) => posix.matchesGlob(path, glob))\n );\n}\n\n/**\n * Parse one command's strace output into a coarse `FileChange[]`. Failed\n * syscalls are skipped; paths are filtered to `destination`; the trace file and\n * `/proc`,`/sys`,`/dev` are excluded. Per-path final state collapses repeated\n * writes to one `write`; a path written then deleted within the command is\n * treated as transient and dropped.\n */\nexport function parseStraceTrace(\n raw: string,\n options: ParseStraceOptions,\n): FileChange[] {\n const { include, exclude, traceDir, traceFile } = options;\n const now = Date.now();\n\n const state = new Map<string, 'write' | 'delete'>();\n const renames: Array<{ from: string; to: string }> = [];\n\n const resolve = (dir: string, p: string): string =>\n posix.normalize(p.startsWith('/') ? p : posix.join(dir, p));\n\n const write = (path: string) => {\n state.set(path, 'write');\n };\n const remove = (path: string) => {\n if (state.get(path) === 'write') state.delete(path);\n else state.set(path, 'delete');\n };\n\n for (const line of stitchLines(raw)) {\n const call = parseCall(line);\n if (!call || call.errno || call.retval === '-1') continue;\n const { syscall, args } = call;\n const dir = dirfdPath(args);\n\n if (RENAME_SYSCALLS.has(syscall)) {\n const strings = quotedStrings(args);\n if (strings.length < 2) continue;\n const from = resolve(dir, strings[0]);\n const to = resolve(dir, strings[strings.length - 1]);\n state.delete(from);\n renames.push({ from, to });\n continue;\n }\n if (DELETE_SYSCALLS.has(syscall)) {\n const strings = quotedStrings(args);\n if (strings.length) remove(resolve(dir, strings[0]));\n continue;\n }\n if (MKDIR_SYSCALLS.has(syscall)) {\n const strings = quotedStrings(args);\n if (strings.length) write(resolve(dir, strings[0]));\n continue;\n }\n if (LINK_SYSCALLS.has(syscall)) {\n const strings = quotedStrings(args);\n if (strings.length) write(resolve(dir, strings[strings.length - 1]));\n continue;\n }\n if (OPEN_SYSCALLS.has(syscall)) {\n if (!CREATE_OR_TRUNC_FLAGS.test(openFlags(args))) continue;\n const strings = quotedStrings(args);\n if (strings.length) write(resolve(dir, strings[0]));\n continue;\n }\n if (WRITE_SYSCALLS.has(syscall)) {\n const p = fdPath(args);\n if (p && Number(call.retval) > 0) write(posix.normalize(p));\n continue;\n }\n if (TRUNCATE_SYSCALLS.has(syscall)) {\n const p = fdPath(args) ?? quotedStrings(args)[0];\n if (p) write(resolve(dir, p));\n }\n }\n\n const keep = (path: string): boolean => {\n if (traceFile && path === traceFile) return false;\n if (traceDir && (path === traceDir || path.startsWith(`${traceDir}/`))) {\n return false;\n }\n if (/^\\/(proc|sys|dev)(\\/|$)/.test(path)) return false;\n return matchesGlobs(path, include, exclude);\n };\n\n const changes: FileChange[] = [];\n const emittedRenameTargets = new Set<string>();\n for (const { from, to } of renames) {\n if (!keep(to)) continue;\n // A later delete of the target supersedes the rename (the tail emits the\n // delete); otherwise the rename entry already represents the target's final\n // state, so the tail must NOT also emit a `write` for it (would duplicate).\n if (state.get(to) === 'delete') continue;\n changes.push({ op: 'rename', path: to, from, timestamp: now });\n emittedRenameTargets.add(to);\n }\n const tail: FileChange[] = [];\n for (const [path, op] of state) {\n if (emittedRenameTargets.has(path)) continue;\n if (keep(path)) tail.push({ op, path, timestamp: now });\n }\n tail.sort((a, b) => {\n if (a.path < b.path) return -1;\n if (a.path > b.path) return 1;\n return 0;\n });\n changes.push(...tail);\n return changes;\n}\n\n// strace prints its own failures to stderr prefixed `strace: `. Anchor on that\n// so a benign command whose output merely contains \"Operation not permitted\" or\n// \"not found\" is not misclassified as a tracer failure.\nconst PTRACE_DENIED =\n /strace:[^\\n]*(?:PTRACE_TRACEME|ptrace|Operation not permitted|EPERM)/i;\nconst STRACE_MISSING = /strace:?\\s+(?:command\\s+)?not found/i;\n\n/**\n * The minimal structural surface {@link selfTestStrace} needs from its host.\n * Deliberately narrower than `DisposableSandbox` so the probe can run anywhere:\n * a remote/docker caller passes its sandbox unchanged (it satisfies this shape\n * structurally), and an in-process caller (e.g. a daemon running as PID 1\n * inside the container) implements just these two methods over\n * `node:child_process` + `node:fs`.\n */\nexport interface StraceHost {\n executeCommand(\n command: string,\n ): Promise<{ exitCode: number; stderr: string }>;\n readFile(path: string): Promise<string>;\n}\n\n/**\n * One-time probe at sandbox setup. Runs a known create/write/rename sequence\n * under strace and asserts the trace is clean and parseable. Throws\n * {@link StraceUnavailableError} (hard-fail) when ptrace is blocked, strace is\n * absent, or the trace is garbled (e.g. amd64 under Rosetta).\n *\n * \"strace works in this sandbox\" is an invariant of the (image + host kernel +\n * seccomp/caps) \u2014 constant across every tool call and chat turn in a given\n * container \u2014 so this is the consumer's once-per-container responsibility (e.g.\n * a daemon boot gate), NOT a per-tool cost. `createBashTool` /\n * `withStraceFileChanges` no longer call it.\n */\nexport async function selfTestStrace(host: StraceHost): Promise<void> {\n const probeDir = `/tmp/dat-strace-${randomUUID()}`;\n const traceFile = `/tmp/dat-strace-${randomUUID()}.trace`;\n const q = shellQuote;\n const sequence =\n `mkdir -p ${q(probeDir)} && ` +\n `echo hi > ${q(`${probeDir}/a.txt`)} && ` +\n `mv ${q(`${probeDir}/a.txt`)} ${q(`${probeDir}/b.txt`)} && ` +\n `echo more > ${q(`${probeDir}/c.txt`)}`;\n const wrapped = buildStraceCommand(sequence, traceFile, '/tmp');\n\n let result: { exitCode: number; stderr: string } | undefined;\n let raw = '';\n try {\n result = await host.executeCommand(wrapped);\n raw = await host.readFile(traceFile).catch(() => '');\n\n const diagnostics = `exit=${result.exitCode}\\nstderr=${result.stderr}\\ntrace[0:600]=${raw.slice(0, 600)}`;\n\n // Order matters: a ptrace block makes strace error on stderr AND emit no\n // trace, so check the ptrace signal (stderr only) before the empty-trace\n // strace-missing check, or a blocked ptrace would be mislabelled.\n if (PTRACE_DENIED.test(result.stderr)) {\n throw new StraceUnavailableError('ptrace-blocked', diagnostics);\n }\n if (!raw || result.exitCode === 127 || STRACE_MISSING.test(result.stderr)) {\n throw new StraceUnavailableError('strace-missing', diagnostics);\n }\n\n // Scope to the probe dir; the exact-path `traceFile` exclusion drops the\n // sibling trace file that lives under /tmp alongside it.\n const changes = parseStraceTrace(raw, {\n include: [probeDir, `${probeDir}/**`],\n traceFile,\n });\n const hasRealFdPath = raw.includes(`<${probeDir}/`);\n const hasRename = changes.some(\n (c) =>\n c.op === 'rename' &&\n c.from === `${probeDir}/a.txt` &&\n c.path === `${probeDir}/b.txt`,\n );\n const hasWrite = changes.some((c) => c.op === 'write');\n const allUnderDir = changes.every(\n (c) => c.path === probeDir || c.path.startsWith(`${probeDir}/`),\n );\n if (!hasRealFdPath || !hasRename || !hasWrite || !allUnderDir) {\n throw new StraceUnavailableError('trace-unparseable', diagnostics);\n }\n } finally {\n void host\n .executeCommand(`rm -rf ${q(probeDir)} ${q(traceFile)}`)\n .catch(() => {});\n }\n}\n", "/**\n * POSIX shell single-quote escape: wrap in `'...'`, replace any embedded\n * `'` with `'\\''`. Safe for arbitrary content inside `sh -c`.\n *\n * Lives in its own zero-import module so node-builtins-only consumers (e.g. the\n * lean `./sandbox/strace` leaf entry) can use it without dragging in the\n * installer/runtime surface.\n */\nexport function shellQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n"],
5
- "mappings": ";AAAA,SAAS,kBAAkB;AAC3B,SAAS,aAAa;;;ACOf,SAAS,WAAW,GAAmB;AAC5C,SAAO,IAAI,EAAE,QAAQ,MAAM,OAAO,CAAC;AACrC;;;ADGA,IAAM,cAAuD;AAAA,EAC3D,kBACE;AAAA,EACF,kBACE;AAAA,EACF,qBACE;AACJ;AAQO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EACvC;AAAA,EACA;AAAA,EAET,YAAY,QAAiC,aAAqB;AAChE;AAAA,MACE,4CAA4C,MAAM,MAAM,YAAY,MAAM,CAAC;AAAA,IAC7E;AACA,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,cAAc;AAAA,EACrB;AACF;AAEA,IAAM,eAAe;AAWd,SAAS,mBACd,SACA,WACA,UACQ;AACR,SACE,YAAY,WAAW,QAAQ,CAAC,wBACtB,YAAY,OAAO,WAAW,SAAS,CAAC,aAAa,WAAW,OAAO,CAAC;AAEtF;AAYO,SAAS,mBACd,SACA,WACA,UACA,UACQ;AACR,SACE,YAAY,WAAW,QAAQ,CAAC,wBACtB,YAAY,OAAO,WAAW,SAAS,CAAC,aAAa,WAAW,OAAO,CAAC,oCAE7D,WAAW,QAAQ,CAAC,YAC/B,WAAW,SAAS,CAAC,uBACtB,WAAW,SAAS,CAAC;AAGlC;AAOO,SAAS,kBACd,QACA,UACmC;AACnC,QAAM,SAAS;AAAA,EAAK,QAAQ;AAAA;AAC5B,QAAM,KAAK,OAAO,QAAQ,MAAM;AAChC,MAAI,OAAO,GAAI,QAAO,EAAE,QAAQ,OAAO,GAAG;AAC1C,QAAM,SAAS,OAAO,MAAM,KAAK,OAAO,MAAM;AAC9C,SAAO;AAAA,IACL,QAAQ,OAAO,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AC,iBAAiB,CAAC,aAAa,CAAC,YAAY,CAAC,aAAa;AAC7D,YAAM,IAAI,uBAAuB,qBAAqB,WAAW;AAAA,IACnE;AAAA,EACF,UAAE;AACA,SAAK,KACF,eAAe,UAAU,EAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,EAAE,EACtD,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EACnB;AACF;",
4
+ "sourcesContent": ["import spawn, { type SubprocessError } from 'nano-spawn';\nimport { randomUUID } from 'node:crypto';\nimport { readFile, rm } from 'node:fs/promises';\nimport { posix } from 'node:path';\n\nimport { shellQuote } from '../shell-quote.ts';\nimport type { FileChange } from './file-change.ts';\n\nexport type { FileChange, FileChangeOp } from './file-change.ts';\n\nexport type StraceUnavailableReason =\n | 'ptrace-blocked'\n | 'strace-missing'\n | 'trace-unparseable';\n\nconst REASON_HINT: Record<StraceUnavailableReason, string> = {\n 'ptrace-blocked':\n 'ptrace is denied by the sandbox runtime. Modern Docker permits it by default; on a hardened host, relax the runtime seccomp/ptrace policy (allow the ptrace syscall, or add the SYS_PTRACE capability).',\n 'strace-missing':\n 'strace is not installed in the sandbox image. Bake `strace` into the image.',\n 'trace-unparseable':\n 'strace ran but its output is unusable \u2014 the sandbox is likely running under emulation (e.g. amd64 via Rosetta). Use a native-architecture sandbox.',\n};\n\n/**\n * Thrown by {@link selfTestStrace} when per-command strace tracking cannot be\n * used. `reason` lets callers branch (fix-image vs fix-caps vs fix-arch). This\n * is a hard failure by design \u2014 there is no silent degrade to the snapshot\n * observer.\n */\nexport class StraceUnavailableError extends Error {\n readonly reason: StraceUnavailableReason;\n readonly diagnostics: string;\n\n constructor(reason: StraceUnavailableReason, diagnostics: string) {\n super(\n `strace file-change tracking unavailable (${reason}): ${REASON_HINT[reason]}`,\n );\n this.name = 'StraceUnavailableError';\n this.reason = reason;\n this.diagnostics = diagnostics;\n }\n}\n\nconst STRACE_FLAGS = '-f -y -qq -e trace=%file,write,pwrite64,writev';\n\n/**\n * Wraps `command` so its filesystem syscalls are traced to `traceFile`. Both\n * the inner command and this wrapper are re-parsed by a shell (`sh -c`), so the\n * single-quoting via {@link shellQuote} composes with the backend's own\n * `sh -c`. strace propagates the traced command's exit code. The `mkdir -p`\n * runs before strace (so it isn't traced) and self-heals the trace dir per\n * command \u2014 if it ever disappears mid-session, the next command recreates it\n * rather than strace failing to open `-o` and skipping the command entirely.\n */\nexport function buildStraceCommand(\n command: string,\n traceFile: string,\n traceDir: string,\n): string {\n return (\n `mkdir -p ${shellQuote(traceDir)} 2>/dev/null; ` +\n `strace ${STRACE_FLAGS} -o ${shellQuote(traceFile)} -- sh -c ${shellQuote(command)}`\n );\n}\n\n/**\n * Like {@link buildStraceCommand}, but dumps the (base64) trace inline on stdout\n * after `sentinel`, then exits with the traced command's code. This lets one\n * `executeCommand` round-trip carry both the command output and its trace \u2014 no\n * second `readFile` exec to pull the trace out of the container. Pair with\n * {@link splitTracedOutput}. `sentinel` must be unguessable (a UUID) so the\n * command's own stdout cannot contain it. `base64` keeps the trace stream-safe\n * and its stderr is dropped so a missing trace (strace failed) doesn't leak into\n * the command's stderr.\n */\nexport function buildTracedCommand(\n command: string,\n traceFile: string,\n traceDir: string,\n sentinel: string,\n): string {\n return (\n `mkdir -p ${shellQuote(traceDir)} 2>/dev/null; ` +\n `strace ${STRACE_FLAGS} -o ${shellQuote(traceFile)} -- sh -c ${shellQuote(command)}; ` +\n `__dat_rc=$?; ` +\n `printf '\\\\n%s\\\\n' ${shellQuote(sentinel)}; ` +\n `base64 ${shellQuote(traceFile)} 2>/dev/null; ` +\n `rm -f ${shellQuote(traceFile)} 2>/dev/null; ` +\n `exit $__dat_rc`\n );\n}\n\n/**\n * Split {@link buildTracedCommand} output into the command's own stdout and its\n * decoded strace trace. A missing sentinel (strace produced nothing) yields an\n * empty trace so the caller degrades to \"no changes\".\n */\nexport function splitTracedOutput(\n stdout: string,\n sentinel: string,\n): { stdout: string; trace: string } {\n const marker = `\\n${sentinel}\\n`;\n const at = stdout.indexOf(marker);\n if (at === -1) return { stdout, trace: '' };\n const base64 = stdout.slice(at + marker.length);\n return {\n stdout: stdout.slice(0, at),\n trace: base64 ? Buffer.from(base64, 'base64').toString('utf8') : '',\n };\n}\n\n// An open is a definite write only when it creates or truncates. Bare\n// O_WRONLY/O_RDWR/O_APPEND opens are NOT assumed to mutate \u2014 a real write()\n// syscall confirms them \u2014 so read-only-via-O_RDWR (sqlite SELECT, an editor\n// that opens then quits) doesn't produce a phantom `write`.\nconst CREATE_OR_TRUNC_FLAGS = /O_(CREAT|TRUNC)/;\nconst RENAME_SYSCALLS = new Set(['rename', 'renameat', 'renameat2']);\nconst DELETE_SYSCALLS = new Set(['unlink', 'unlinkat', 'rmdir']);\nconst MKDIR_SYSCALLS = new Set(['mkdir', 'mkdirat']);\nconst LINK_SYSCALLS = new Set(['link', 'linkat', 'symlink', 'symlinkat']);\nconst OPEN_SYSCALLS = new Set(['open', 'openat', 'openat2', 'creat']);\nconst WRITE_SYSCALLS = new Set([\n 'write',\n 'pwrite64',\n 'pwrite',\n 'writev',\n 'pwritev2',\n]);\nconst TRUNCATE_SYSCALLS = new Set(['truncate', 'ftruncate']);\n\ninterface ParsedCall {\n syscall: string;\n args: string;\n retval: string;\n errno?: string;\n}\n\n/** Reassemble `<unfinished \u2026>` / `<\u2026 resumed>` syscall splits per PID. */\nfunction stitchLines(raw: string): string[] {\n const pending = new Map<string, string>();\n const out: string[] = [];\n for (const original of raw.split('\\n')) {\n const line = original.trimEnd();\n if (!line) continue;\n const pid = line.match(/^\\s*(\\d+)\\s+/)?.[1] ?? '0';\n if (/<unfinished \\.\\.\\.>\\s*$/.test(line)) {\n pending.set(pid, line.replace(/<unfinished \\.\\.\\.>\\s*$/, ''));\n continue;\n }\n const resumed = line.match(/<\\.\\.\\.\\s+\\S+\\s+resumed>(.*)$/);\n if (resumed) {\n const head = pending.get(pid);\n pending.delete(pid);\n if (head !== undefined) out.push(head + resumed[1]);\n continue;\n }\n out.push(line);\n }\n return out;\n}\n\nfunction parseCall(line: string): ParsedCall | null {\n const m = line.match(\n /^\\s*(?:\\d+\\s+)?([a-z_][a-z0-9_]*)\\((.*)\\)\\s*=\\s*(.+?)\\s*$/,\n );\n if (!m) return null;\n const [, syscall, args, rest] = m;\n const errnoMatch = rest.match(/^(-?\\d+)\\s+([A-Z][A-Z0-9_]*)/);\n if (errnoMatch) {\n return { syscall, args, retval: errnoMatch[1], errno: errnoMatch[2] };\n }\n return { syscall, args, retval: rest.split(/\\s+/)[0] };\n}\n\nconst STRACE_ESCAPE: Record<string, number> = {\n n: 0x0a,\n t: 0x09,\n r: 0x0d,\n v: 0x0b,\n f: 0x0c,\n '\"': 0x22,\n '\\\\': 0x5c,\n};\n\n/**\n * Decode one strace-rendered string. strace emits printable ASCII verbatim and\n * non-printable / non-ASCII bytes as octal `\\NNN`, plus a few `\\x` escapes. We\n * reconstruct the raw byte sequence and decode it as UTF-8 so multi-byte\n * filenames (e.g. `caf\u00E9.txt` \u2192 `\\303\\251`) round-trip instead of being mangled.\n */\nfunction decodeStraceString(s: string): string {\n const bytes: number[] = [];\n for (let i = 0; i < s.length; ) {\n if (s[i] === '\\\\' && i + 1 < s.length) {\n const octal = s.slice(i + 1, i + 4).match(/^[0-7]{1,3}/)?.[0];\n if (octal) {\n bytes.push(parseInt(octal, 8) & 0xff);\n i += 1 + octal.length;\n continue;\n }\n const mapped = STRACE_ESCAPE[s[i + 1]];\n bytes.push(mapped ?? s.charCodeAt(i + 1));\n i += 2;\n continue;\n }\n const code = s.charCodeAt(i);\n if (code < 0x80) bytes.push(code);\n else for (const b of Buffer.from(s[i], 'utf8')) bytes.push(b);\n i += 1;\n }\n return Buffer.from(bytes).toString('utf8');\n}\n\nfunction quotedStrings(args: string): string[] {\n const out: string[] = [];\n const re = /\"((?:[^\"\\\\]|\\\\.)*)\"/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(args)) !== null) {\n out.push(decodeStraceString(m[1]));\n }\n return out;\n}\n\n/** Directory path annotated on the leading dirfd (`AT_FDCWD</cwd>` / `7</dir>`). */\nfunction dirfdPath(args: string): string {\n return args.match(/^\\s*(?:AT_FDCWD|-?\\d+)<([^>]*)>/)?.[1] ?? '/';\n}\n\n/** Path annotated on the leading fd argument (`-y` output), for write syscalls. */\nfunction fdPath(args: string): string | null {\n return args.match(/^\\s*-?\\d+<([^>]*)>/)?.[1] ?? null;\n}\n\nfunction openFlags(args: string): string {\n return args.match(/\\bO_[A-Z_]+(?:\\|O_[A-Z_]+)*/)?.[0] ?? '';\n}\n\nexport interface ParseStraceOptions {\n include: string[];\n exclude?: string[];\n traceFile?: string;\n traceDir?: string;\n}\n\n/** A path is tracked when it matches an `include` glob and no `exclude` glob. */\nexport function matchesGlobs(\n path: string,\n include: string[],\n exclude?: string[],\n): boolean {\n return (\n include.some((glob) => posix.matchesGlob(path, glob)) &&\n !exclude?.some((glob) => posix.matchesGlob(path, glob))\n );\n}\n\n/**\n * Parse one command's strace output into a coarse `FileChange[]`. Failed\n * syscalls are skipped; paths are filtered to `destination`; the trace file and\n * `/proc`,`/sys`,`/dev` are excluded. Per-path final state collapses repeated\n * writes to one `write`; a path written then deleted within the command is\n * treated as transient and dropped.\n */\nexport function parseStraceTrace(\n raw: string,\n options: ParseStraceOptions,\n): FileChange[] {\n const { include, exclude, traceDir, traceFile } = options;\n const now = Date.now();\n\n const state = new Map<string, 'write' | 'delete'>();\n const renames: Array<{ from: string; to: string }> = [];\n\n const resolve = (dir: string, p: string): string =>\n posix.normalize(p.startsWith('/') ? p : posix.join(dir, p));\n\n const write = (path: string) => {\n state.set(path, 'write');\n };\n const remove = (path: string) => {\n if (state.get(path) === 'write') state.delete(path);\n else state.set(path, 'delete');\n };\n\n for (const line of stitchLines(raw)) {\n const call = parseCall(line);\n if (!call || call.errno || call.retval === '-1') continue;\n const { syscall, args } = call;\n const dir = dirfdPath(args);\n\n if (RENAME_SYSCALLS.has(syscall)) {\n const strings = quotedStrings(args);\n if (strings.length < 2) continue;\n const from = resolve(dir, strings[0]);\n const to = resolve(dir, strings[strings.length - 1]);\n state.delete(from);\n renames.push({ from, to });\n continue;\n }\n if (DELETE_SYSCALLS.has(syscall)) {\n const strings = quotedStrings(args);\n if (strings.length) remove(resolve(dir, strings[0]));\n continue;\n }\n if (MKDIR_SYSCALLS.has(syscall)) {\n const strings = quotedStrings(args);\n if (strings.length) write(resolve(dir, strings[0]));\n continue;\n }\n if (LINK_SYSCALLS.has(syscall)) {\n const strings = quotedStrings(args);\n if (strings.length) write(resolve(dir, strings[strings.length - 1]));\n continue;\n }\n if (OPEN_SYSCALLS.has(syscall)) {\n if (!CREATE_OR_TRUNC_FLAGS.test(openFlags(args))) continue;\n const strings = quotedStrings(args);\n if (strings.length) write(resolve(dir, strings[0]));\n continue;\n }\n if (WRITE_SYSCALLS.has(syscall)) {\n const p = fdPath(args);\n if (p && Number(call.retval) > 0) write(posix.normalize(p));\n continue;\n }\n if (TRUNCATE_SYSCALLS.has(syscall)) {\n const p = fdPath(args) ?? quotedStrings(args)[0];\n if (p) write(resolve(dir, p));\n }\n }\n\n const keep = (path: string): boolean => {\n if (traceFile && path === traceFile) return false;\n if (traceDir && (path === traceDir || path.startsWith(`${traceDir}/`))) {\n return false;\n }\n if (/^\\/(proc|sys|dev)(\\/|$)/.test(path)) return false;\n return matchesGlobs(path, include, exclude);\n };\n\n const changes: FileChange[] = [];\n const emittedRenameTargets = new Set<string>();\n for (const { from, to } of renames) {\n if (!keep(to)) continue;\n // A later delete of the target supersedes the rename (the tail emits the\n // delete); otherwise the rename entry already represents the target's final\n // state, so the tail must NOT also emit a `write` for it (would duplicate).\n if (state.get(to) === 'delete') continue;\n changes.push({ op: 'rename', path: to, from, timestamp: now });\n emittedRenameTargets.add(to);\n }\n const tail: FileChange[] = [];\n for (const [path, op] of state) {\n if (emittedRenameTargets.has(path)) continue;\n if (keep(path)) tail.push({ op, path, timestamp: now });\n }\n tail.sort((a, b) => {\n if (a.path < b.path) return -1;\n if (a.path > b.path) return 1;\n return 0;\n });\n changes.push(...tail);\n return changes;\n}\n\n// strace prints its own failures to stderr prefixed `strace: `. Anchor on that\n// so a benign command whose output merely contains \"Operation not permitted\" or\n// \"not found\" is not misclassified as a tracer failure.\nconst PTRACE_DENIED =\n /strace:[^\\n]*(?:PTRACE_TRACEME|ptrace|Operation not permitted|EPERM)/i;\nconst STRACE_MISSING = /strace:?\\s+(?:command\\s+)?not found/i;\n\n/**\n * Run `command` on the host via `sh -c`, flattening nano-spawn's\n * throw-on-nonzero contract into `{ exitCode, stderr }`. The probe must read\n * both even on failure \u2014 a missing strace exits 127, a blocked ptrace exits\n * non-zero with its diagnosis on stderr \u2014 which nano-spawn surfaces by rejecting\n * with a {@link SubprocessError} (its `exitCode` is undefined only when the\n * process never started or a signal killed it, hence the `?? 1`).\n */\nasync function runOnHost(\n command: string,\n): Promise<{ exitCode: number; stderr: string }> {\n try {\n const { stderr } = await spawn('sh', ['-c', command]);\n return { exitCode: 0, stderr };\n } catch (error) {\n const e = error as SubprocessError;\n return { exitCode: e.exitCode ?? 1, stderr: e.stderr };\n }\n}\n\n/**\n * One-time probe at sandbox setup. Runs a known create/write/rename sequence\n * under strace on the host and asserts the trace is clean and parseable. Throws\n * {@link StraceUnavailableError} (hard-fail) when ptrace is blocked, strace is\n * absent, or the trace is garbled (e.g. amd64 under Rosetta).\n *\n * \"strace works here\" is an invariant of the (image + host kernel + seccomp/caps)\n * \u2014 constant across every tool call and chat turn in a given container \u2014 so this\n * is the consumer's once-per-container responsibility (e.g. a daemon boot gate\n * running as PID 1 inside the container), NOT a per-tool cost. `createBashTool` /\n * `withStraceFileChanges` no longer call it.\n */\nexport async function selfTestStrace(): Promise<void> {\n const probeDir = `/tmp/dat-strace-${randomUUID()}`;\n const traceFile = `/tmp/dat-strace-${randomUUID()}.trace`;\n const q = shellQuote;\n const sequence =\n `mkdir -p ${q(probeDir)} && ` +\n `echo hi > ${q(`${probeDir}/a.txt`)} && ` +\n `mv ${q(`${probeDir}/a.txt`)} ${q(`${probeDir}/b.txt`)} && ` +\n `echo more > ${q(`${probeDir}/c.txt`)}`;\n const wrapped = buildStraceCommand(sequence, traceFile, '/tmp');\n\n try {\n const result = await runOnHost(wrapped);\n const raw = await readFile(traceFile, 'utf8').catch(() => '');\n\n const diagnostics = `exit=${result.exitCode}\\nstderr=${result.stderr}\\ntrace[0:600]=${raw.slice(0, 600)}`;\n\n // Order matters: a ptrace block makes strace error on stderr AND emit no\n // trace, so check the ptrace signal (stderr only) before the empty-trace\n // strace-missing check, or a blocked ptrace would be mislabelled.\n if (PTRACE_DENIED.test(result.stderr)) {\n throw new StraceUnavailableError('ptrace-blocked', diagnostics);\n }\n if (!raw || result.exitCode === 127 || STRACE_MISSING.test(result.stderr)) {\n throw new StraceUnavailableError('strace-missing', diagnostics);\n }\n\n // Scope to the probe dir; the exact-path `traceFile` exclusion drops the\n // sibling trace file that lives under /tmp alongside it.\n const changes = parseStraceTrace(raw, {\n include: [probeDir, `${probeDir}/**`],\n traceFile,\n });\n const hasRealFdPath = raw.includes(`<${probeDir}/`);\n const hasRename = changes.some(\n (c) =>\n c.op === 'rename' &&\n c.from === `${probeDir}/a.txt` &&\n c.path === `${probeDir}/b.txt`,\n );\n const hasWrite = changes.some((c) => c.op === 'write');\n const allUnderDir = changes.every(\n (c) => c.path === probeDir || c.path.startsWith(`${probeDir}/`),\n );\n if (!hasRealFdPath || !hasRename || !hasWrite || !allUnderDir) {\n throw new StraceUnavailableError('trace-unparseable', diagnostics);\n }\n } finally {\n await Promise.allSettled([\n rm(probeDir, { recursive: true, force: true }),\n rm(traceFile, { force: true }),\n ]);\n }\n}\n", "/**\n * POSIX shell single-quote escape: wrap in `'...'`, replace any embedded\n * `'` with `'\\''`. Safe for arbitrary content inside `sh -c`.\n *\n * Lives in its own zero-import module so lean consumers such as the\n * `./sandbox/strace` leaf entry can use it without dragging in the\n * installer/runtime surface.\n */\nexport function shellQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\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UAAM,cAAc,QAAQ;AAAA,MAC1B,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,KAAK,WAAW,GAAG,QAAQ,GAAG;AAAA,IAChE;AACA,QAAI,CAAC,iBAAiB,CAAC,aAAa,CAAC,YAAY,CAAC,aAAa;AAC7D,YAAM,IAAI,uBAAuB,qBAAqB,WAAW;AAAA,IACnE;AAAA,EACF,UAAE;AACA,UAAM,QAAQ,WAAW;AAAA,MACvB,GAAG,UAAU,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAAA,MAC7C,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC;AAAA,IAC/B,CAAC;AAAA,EACH;AACF;",
6
6
  "names": []
7
7
  }
@@ -35,9 +35,9 @@ export interface SandboxProcess {
35
35
  * no-op `dispose()`.
36
36
  *
37
37
  * `spawn` is optional: only backends that can honestly expose unbuffered
38
- * stdio (e.g. docker-sandbox) implement it. Callers feature-detect with
39
- * `if (!sandbox.spawn) ...` — no silent fallback that aggregates output
40
- * and flushes on completion.
38
+ * stdio (e.g. Docker or Apple Container sandboxes) implement it. Callers
39
+ * feature-detect with `if (!sandbox.spawn) ...` — no silent fallback that
40
+ * aggregates output and flushes on completion.
41
41
  */
42
42
  export interface DisposableSandbox extends Omit<UpstreamSandbox, 'executeCommand'>, AsyncDisposable {
43
43
  executeCommand(command: string, options?: ExecuteCommandOptions): Promise<CommandResult>;
@@ -49,6 +49,25 @@ export interface DisposableSandbox extends Omit<UpstreamSandbox, 'executeCommand
49
49
  */
50
50
  dispose(): Promise<void>;
51
51
  }
52
+ /**
53
+ * Readiness option accepted by every sandbox factory. Readiness is workload
54
+ * policy supplied by the caller — the hook runs once after boot and gates the
55
+ * factory's return; on failure the sandbox is disposed and the error
56
+ * propagates, so callers either receive a sandbox that satisfies their
57
+ * readiness condition or no sandbox at all. Recurring health monitoring stays
58
+ * the caller's responsibility.
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * const sandbox = await createMicrosandboxSandbox({
63
+ * name: 'demo',
64
+ * readiness: (sandbox) => startDaemon(sandbox),
65
+ * });
66
+ * ```
67
+ */
68
+ export interface SandboxReadinessOptions {
69
+ readiness?: (sandbox: DisposableSandbox) => void | Promise<void>;
70
+ }
52
71
  /**
53
72
  * Declarative skill upload: a host directory whose contents are copied into
54
73
  * the sandbox at startup. The factory also parses each skill's frontmatter
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/sandbox/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,KAAK,EACV,WAAW,EACX,aAAa,EACb,OAAO,IAAI,eAAe,EAC3B,MAAM,WAAW,CAAC;AAEnB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IACpC,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC;IAC9B,oCAAoC;IACpC,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,CAAC;IAC5C,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,CAAC;IAC5C,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;CAClC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,iBACf,SAAQ,IAAI,CAAC,eAAe,EA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gB;IAC/B,6EAA6E;IAC7E,IAAI,EAAE,MAAM,CAAC;IACb,iEAAiE;IACjE,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,mEAAmE;AACnE,MAAM,MAAM,eAAe,GAAG,IAAI,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;AAEjE;;;;;GAKG;AACH,MAAM,WAAW,YAAa,SAAQ,IAAI,CACxC,WAAW,EACX,MAAM,GAAG,OAAO,GAAG,SAAS,CAC7B;IACC,+DAA+D;IAC/D,MAAM,EAAE,gBAAgB,EAAE,CAAC;IAC3B,IAAI,EAAE,eAAe,CAAC;IACtB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,GAAG;QAAE,IAAI,EAAE,eAAe,CAAA;KAAE,CAAC;IACtE,OAAO,EAAE,iBAAiB,CAAC;CAC5B"}
@@ -1,6 +1,6 @@
1
1
  import { type CustomCommand, type IFileSystem } from 'just-bash';
2
- import type { DisposableSandbox } from './types.ts';
3
- export interface CreateVirtualSandboxOptions {
2
+ import type { DisposableSandbox, SandboxReadinessOptions } from './types.ts';
3
+ export interface CreateVirtualSandboxOptions extends SandboxReadinessOptions {
4
4
  fs: IFileSystem;
5
5
  cwd?: string;
6
6
  env?: Record<string, string>;
@@ -1 +1 @@
1
- {"version":3,"file":"virtual-sandbox.d.ts","sourceRoot":"","sources":["../../../src/lib/sandbox/virtual-sandbox.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,aAAa,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAEvE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD,MAAM,WAAW,2BAA2B;IAC1C,EAAE,EAAE,WAAW,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,cAAc,CAAC,EAAE,aAAa,EAAE,CAAC;CAClC;AAED,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,iBAAiB,CAAC,CA0C5B"}
1
+ {"version":3,"file":"virtual-sandbox.d.ts","sourceRoot":"","sources":["../../../src/lib/sandbox/virtual-sandbox.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,aAAa,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAEvE,OAAO,KAAK,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAE7E,MAAM,WAAW,2BAA4B,SAAQ,uBAAuB;IAC1E,EAAE,EAAE,WAAW,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,cAAc,CAAC,EAAE,aAAa,EAAE,CAAC;CAClC;AAED,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,iBAAiB,CAAC,CAoD5B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepagents/context",
3
- "version": "4.0.0",
3
+ "version": "4.2.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -47,10 +47,10 @@
47
47
  "access": "public"
48
48
  },
49
49
  "dependencies": {
50
- "@ai-sdk/groq": "^3.0.36",
51
- "@ai-sdk/provider": "^3.0.10",
52
- "@deepagents/agent": "4.0.0",
53
- "ai": "^6.0.174",
50
+ "@ai-sdk/groq": "^3.0.47",
51
+ "@ai-sdk/provider": "^3.0.13",
52
+ "@deepagents/agent": "4.2.0",
53
+ "ai": "^6.0.218",
54
54
  "bash-tool": "^1.3.16",
55
55
  "chalk": "^5.6.0",
56
56
  "dedent": "^1.7.0",
@@ -61,20 +61,23 @@
61
61
  "stringcase": "^4.3.1",
62
62
  "tiny-tfidf": "^1.0.0",
63
63
  "yaml": "^2.8.0",
64
- "zod": "^3.25.76 || ^4.0.0"
64
+ "zod": "^3.25.76 || ^4.0.0",
65
+ "@ai-sdk/openai": "^3.0.80",
66
+ "@deepagents/test": "0.15.0"
65
67
  },
66
68
  "devDependencies": {
67
69
  "@daytona/sdk": "^0.175.0",
68
70
  "@types/debug": "^4.1.12",
69
71
  "@types/mssql": "^12.3.0",
70
72
  "@types/pg": "^8.20.0",
71
- "nock": "^14.0.14",
72
- "pg-boss": "^12.18.2"
73
+ "microsandbox": "^0.6.4",
74
+ "nock": "^14.0.14"
73
75
  },
74
76
  "peerDependencies": {
75
77
  "@daytona/sdk": "^0.175.0",
76
78
  "@rivet-dev/agent-os-common": "^0.0.260331072558",
77
79
  "@rivet-dev/agent-os-core": ">=0.1.0",
80
+ "microsandbox": "^0.6.4",
78
81
  "mssql": "^12.5.2",
79
82
  "pg": "^8.20.0"
80
83
  },
@@ -82,6 +85,9 @@
82
85
  "@daytona/sdk": {
83
86
  "optional": true
84
87
  },
88
+ "microsandbox": {
89
+ "optional": true
90
+ },
85
91
  "mssql": {
86
92
  "optional": true
87
93
  },