@mastra/code-sdk 1.7.2-alpha.0 → 1.7.2-alpha.3
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/dist/agent-connections/messaging-processor.d.ts +17 -0
- package/dist/agent-connections/messaging-processor.d.ts.map +1 -0
- package/dist/agent-connections/messaging-processor.js +134 -0
- package/dist/agent-connections/messaging-processor.js.map +1 -0
- package/dist/agent-connections/ownership.d.ts +9 -0
- package/dist/agent-connections/ownership.d.ts.map +1 -0
- package/dist/agent-connections/ownership.js +64 -0
- package/dist/agent-connections/ownership.js.map +1 -0
- package/dist/agent-connections/registry.d.ts +20 -0
- package/dist/agent-connections/registry.d.ts.map +1 -0
- package/dist/agent-connections/registry.js +167 -0
- package/dist/agent-connections/registry.js.map +1 -0
- package/dist/agent-connections/signal-provider.d.ts +142 -0
- package/dist/agent-connections/signal-provider.d.ts.map +1 -0
- package/dist/agent-connections/signal-provider.js +38 -0
- package/dist/agent-connections/signal-provider.js.map +1 -0
- package/dist/agent-connections/state-processor.d.ts +23 -0
- package/dist/agent-connections/state-processor.d.ts.map +1 -0
- package/dist/agent-connections/state-processor.js +273 -0
- package/dist/agent-connections/state-processor.js.map +1 -0
- package/dist/agent-connections/thread-state.d.ts +41 -0
- package/dist/agent-connections/thread-state.d.ts.map +1 -0
- package/dist/agent-connections/thread-state.js +160 -0
- package/dist/agent-connections/thread-state.js.map +1 -0
- package/dist/agent-connections/tools.d.ts +134 -0
- package/dist/agent-connections/tools.d.ts.map +1 -0
- package/dist/agent-connections/tools.js +527 -0
- package/dist/agent-connections/tools.js.map +1 -0
- package/dist/agent-connections/types.d.ts +99 -0
- package/dist/agent-connections/types.d.ts.map +1 -0
- package/dist/agent-connections/types.js +7 -0
- package/dist/agent-connections/types.js.map +1 -0
- package/dist/agent-connections/untrusted-text.d.ts +5 -0
- package/dist/agent-connections/untrusted-text.d.ts.map +1 -0
- package/dist/agent-connections/untrusted-text.js +22 -0
- package/dist/agent-connections/untrusted-text.js.map +1 -0
- package/dist/agents/prompts/agent-instructions.d.ts +1 -0
- package/dist/agents/prompts/agent-instructions.d.ts.map +1 -1
- package/dist/agents/prompts/agent-instructions.js +39 -14
- package/dist/agents/prompts/agent-instructions.js.map +1 -1
- package/dist/agents/sandbox-filesystem.d.ts +34 -1
- package/dist/agents/sandbox-filesystem.d.ts.map +1 -1
- package/dist/agents/sandbox-filesystem.js +224 -2
- package/dist/agents/sandbox-filesystem.js.map +1 -1
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +52 -2
- package/dist/index.js.map +1 -1
- package/dist/onboarding/settings.d.ts +2 -0
- package/dist/onboarding/settings.d.ts.map +1 -1
- package/dist/onboarding/settings.js +3 -1
- package/dist/onboarding/settings.js.map +1 -1
- package/dist/providers/amazon-bedrock-gateway.d.ts.map +1 -1
- package/dist/providers/amazon-bedrock-gateway.js +3 -12
- package/dist/providers/amazon-bedrock-gateway.js.map +1 -1
- package/dist/tool-names.d.ts +4 -0
- package/dist/tool-names.d.ts.map +1 -1
- package/dist/tool-names.js +5 -1
- package/dist/tool-names.js.map +1 -1
- package/dist/tools/request-sandbox-access.js +1 -1
- package/dist/tools/web-search.js +1 -1
- package/dist/utils/storage-maintenance.d.ts +18 -0
- package/dist/utils/storage-maintenance.d.ts.map +1 -1
- package/dist/utils/storage-maintenance.js +53 -2
- package/dist/utils/storage-maintenance.js.map +1 -1
- package/package.json +14 -14
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { posix } from "path";
|
|
2
|
-
import { FileExistsError, FileNotFoundError, IsDirectoryError } from "@mastra/core/workspace";
|
|
2
|
+
import { DirectoryNotFoundError, FileExistsError, FileNotFoundError, IsDirectoryError, NotDirectoryError, UnsupportedGrepPatternError } from "@mastra/core/workspace";
|
|
3
3
|
//#region src/agents/sandbox-filesystem.ts
|
|
4
4
|
/**
|
|
5
5
|
* SandboxFilesystem
|
|
@@ -22,6 +22,7 @@ import { FileExistsError, FileNotFoundError, IsDirectoryError } from "@mastra/co
|
|
|
22
22
|
const EXIT_NOT_FOUND = 20;
|
|
23
23
|
const EXIT_IS_DIRECTORY = 21;
|
|
24
24
|
const EXIT_EXISTS = 22;
|
|
25
|
+
const EXIT_NOT_DIRECTORY = 23;
|
|
25
26
|
/** Default per-command deadline so a hung sandbox can't block file tools forever. */
|
|
26
27
|
const COMMAND_TIMEOUT_MS = 3e4;
|
|
27
28
|
/** Single-quote a string for safe POSIX shell interpolation. */
|
|
@@ -35,7 +36,7 @@ function toBuffer(content) {
|
|
|
35
36
|
if (isFileContentString(content)) return Buffer.from(content, "utf8");
|
|
36
37
|
return Buffer.from(content);
|
|
37
38
|
}
|
|
38
|
-
var SandboxFilesystem = class {
|
|
39
|
+
var SandboxFilesystem = class SandboxFilesystem {
|
|
39
40
|
id;
|
|
40
41
|
name = "SandboxFilesystem";
|
|
41
42
|
provider = "sandbox";
|
|
@@ -304,6 +305,227 @@ var SandboxFilesystem = class {
|
|
|
304
305
|
if (!extension) return true;
|
|
305
306
|
return (Array.isArray(extension) ? extension : [extension]).some((ext) => name.endsWith(ext));
|
|
306
307
|
}
|
|
308
|
+
/**
|
|
309
|
+
* Walk the tree in a single sandbox command instead of one readdir round
|
|
310
|
+
* trip per directory. Uses `find` with a portable classification loop
|
|
311
|
+
* (`find -printf` is GNU-only and fails on macOS/BSD hosts). `find` does
|
|
312
|
+
* not follow symlinked directories by default, matching the host-side
|
|
313
|
+
* walker's no-recursion-into-symlinks behavior.
|
|
314
|
+
*/
|
|
315
|
+
async walk(path, options) {
|
|
316
|
+
const abs = await this.resolveAsync(path);
|
|
317
|
+
await this.assertContainedRealpath(abs, path);
|
|
318
|
+
const maxDepth = options?.maxDepth !== void 0 && Number.isFinite(options.maxDepth) ? `-maxdepth ${Math.max(0, Math.floor(options.maxDepth))} ` : "";
|
|
319
|
+
const hiddenPrune = options?.includeHidden ? "" : `-name '.*' -prune -o `;
|
|
320
|
+
const script = `root=${shellQuote(abs)}\n[ -e "$root" ] || [ -L "$root" ] || exit ${EXIT_NOT_FOUND}\n[ -d "$root" ] || exit ${EXIT_NOT_DIRECTORY}\nfind "$root" -mindepth 1 ${maxDepth}${hiddenPrune}-print 2>/dev/null | while IFS= read -r f; do if [ -L "$f" ]; then if [ -d "$f" ]; then t=D; else t=F; fi; printf '%s\\t%s\\t%s\\n' "$t" "$f" "$(readlink "$f")"; elif [ -d "$f" ]; then printf 'd\\t%s\\n' "$f"; else printf 'f\\t%s\\n' "$f"; fi; done`;
|
|
321
|
+
const result = await this.exec(script);
|
|
322
|
+
if (result.exitCode === EXIT_NOT_FOUND) throw new DirectoryNotFoundError(path);
|
|
323
|
+
if (result.exitCode === EXIT_NOT_DIRECTORY) throw new NotDirectoryError(path);
|
|
324
|
+
if (result.exitCode !== 0) throw new Error(`walk ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
|
|
325
|
+
const entries = [];
|
|
326
|
+
for (const line of result.stdout.split("\n")) {
|
|
327
|
+
if (!line) continue;
|
|
328
|
+
const tab = line.indexOf(" ");
|
|
329
|
+
if (tab < 0) continue;
|
|
330
|
+
const flag = line.slice(0, tab);
|
|
331
|
+
const isSymlink = flag === "D" || flag === "F";
|
|
332
|
+
let fullPath = line.slice(tab + 1);
|
|
333
|
+
let symlinkTarget;
|
|
334
|
+
if (isSymlink) {
|
|
335
|
+
const tab2 = fullPath.lastIndexOf(" ");
|
|
336
|
+
if (tab2 >= 0) {
|
|
337
|
+
symlinkTarget = fullPath.slice(tab2 + 1) || void 0;
|
|
338
|
+
fullPath = fullPath.slice(0, tab2);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
const rel = posix.relative(abs, fullPath);
|
|
342
|
+
if (!rel || rel.startsWith("..")) continue;
|
|
343
|
+
entries.push({
|
|
344
|
+
name: posix.basename(rel),
|
|
345
|
+
type: flag === "d" || flag === "D" ? "directory" : "file",
|
|
346
|
+
...isSymlink ? {
|
|
347
|
+
isSymlink: true,
|
|
348
|
+
...symlinkTarget ? { symlinkTarget } : {}
|
|
349
|
+
} : {},
|
|
350
|
+
path: rel
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
return entries;
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Content search executed inside the sandbox in one command. Prefers
|
|
357
|
+
* ripgrep (`rg --json`) when installed; otherwise falls back to
|
|
358
|
+
* `grep -rnE`. Patterns the ERE fallback can't express (PCRE-style classes,
|
|
359
|
+
* word boundaries, lookarounds, non-greedy quantifiers) throw
|
|
360
|
+
* {@link UnsupportedGrepPatternError} so callers use their host-side walk.
|
|
361
|
+
*
|
|
362
|
+
* Callers are expected to apply their own gitignore/hidden/glob filtering
|
|
363
|
+
* to the returned paths; both engines run with ignore rules disabled so
|
|
364
|
+
* results are a superset of what any host-side filter would keep.
|
|
365
|
+
*/
|
|
366
|
+
async grep(options) {
|
|
367
|
+
const abs = await this.resolveAsync(options.path);
|
|
368
|
+
await this.assertContainedRealpath(abs, options.path);
|
|
369
|
+
if (await this.hasRipgrep()) return this.grepWithRipgrep(abs, options);
|
|
370
|
+
return this.grepWithPosixGrep(abs, options);
|
|
371
|
+
}
|
|
372
|
+
rgCheck;
|
|
373
|
+
hasRipgrep() {
|
|
374
|
+
this.rgCheck ??= this.exec("command -v rg >/dev/null 2>&1").then((r) => r.exitCode === 0, () => false);
|
|
375
|
+
return this.rgCheck;
|
|
376
|
+
}
|
|
377
|
+
async grepWithRipgrep(abs, options) {
|
|
378
|
+
const args = [
|
|
379
|
+
"rg --json --no-ignore --hidden",
|
|
380
|
+
`-g ${shellQuote("!.git/**")}`,
|
|
381
|
+
options.caseSensitive ? "" : "-i",
|
|
382
|
+
options.maxCountPerFile !== void 0 ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : "",
|
|
383
|
+
options.contextLines ? `-C ${Math.max(0, Math.floor(options.contextLines))}` : "",
|
|
384
|
+
`-e ${shellQuote(options.pattern)}`,
|
|
385
|
+
shellQuote(abs)
|
|
386
|
+
].filter(Boolean).join(" ");
|
|
387
|
+
const result = await this.exec(args);
|
|
388
|
+
if (result.exitCode === 1) return [];
|
|
389
|
+
const results = this.parseRipgrepJson(result.stdout, abs, options);
|
|
390
|
+
if (result.exitCode !== 0 && results.length === 0) throw new UnsupportedGrepPatternError(options.pattern);
|
|
391
|
+
return results;
|
|
392
|
+
}
|
|
393
|
+
parseRipgrepJson(stdout, abs, options) {
|
|
394
|
+
const files = /* @__PURE__ */ new Map();
|
|
395
|
+
for (const line of stdout.split("\n")) {
|
|
396
|
+
if (!line) continue;
|
|
397
|
+
let event;
|
|
398
|
+
try {
|
|
399
|
+
event = JSON.parse(line);
|
|
400
|
+
} catch {
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
if (event.type !== "match" && event.type !== "context") continue;
|
|
404
|
+
const filePath = event.data?.path?.text;
|
|
405
|
+
const lineNumber = event.data?.line_number;
|
|
406
|
+
if (!filePath || !lineNumber) continue;
|
|
407
|
+
let state = files.get(filePath);
|
|
408
|
+
if (!state) {
|
|
409
|
+
state = {
|
|
410
|
+
matches: [],
|
|
411
|
+
linesByNumber: /* @__PURE__ */ new Map()
|
|
412
|
+
};
|
|
413
|
+
files.set(filePath, state);
|
|
414
|
+
}
|
|
415
|
+
const text = (event.data?.lines?.text ?? "").replace(/\r?\n$/, "");
|
|
416
|
+
state.linesByNumber.set(lineNumber, text);
|
|
417
|
+
if (event.type === "match") {
|
|
418
|
+
const byteStart = event.data?.submatches?.[0]?.start ?? 0;
|
|
419
|
+
const column = Buffer.from(text, "utf8").subarray(0, byteStart).toString("utf8").length;
|
|
420
|
+
state.matches.push({
|
|
421
|
+
line: lineNumber,
|
|
422
|
+
column,
|
|
423
|
+
text,
|
|
424
|
+
lineNumber
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
const contextLines = options.contextLines ?? 0;
|
|
429
|
+
const results = [];
|
|
430
|
+
for (const [filePath, state] of files) {
|
|
431
|
+
if (state.matches.length === 0) continue;
|
|
432
|
+
const rel = posix.relative(abs, filePath) || posix.basename(filePath);
|
|
433
|
+
const matches = state.matches.map(({ lineNumber, ...match }) => {
|
|
434
|
+
if (contextLines <= 0) return match;
|
|
435
|
+
const before = [];
|
|
436
|
+
for (let n = lineNumber - 1; n >= Math.max(1, lineNumber - contextLines); n--) {
|
|
437
|
+
const t = state.linesByNumber.get(n);
|
|
438
|
+
if (t === void 0) break;
|
|
439
|
+
before.unshift(t);
|
|
440
|
+
}
|
|
441
|
+
const after = [];
|
|
442
|
+
for (let n = lineNumber + 1; n <= lineNumber + contextLines; n++) {
|
|
443
|
+
const t = state.linesByNumber.get(n);
|
|
444
|
+
if (t === void 0) break;
|
|
445
|
+
after.push(t);
|
|
446
|
+
}
|
|
447
|
+
return {
|
|
448
|
+
...match,
|
|
449
|
+
before,
|
|
450
|
+
after
|
|
451
|
+
};
|
|
452
|
+
});
|
|
453
|
+
results.push({
|
|
454
|
+
path: rel,
|
|
455
|
+
matches
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
return this.applyTotalCap(results, options.maxTotalMatches);
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Patterns whose meaning differs between POSIX ERE and JS RegExp. The grep
|
|
462
|
+
* runs with ERE but match columns are recomputed with JS, so anything that
|
|
463
|
+
* only one side understands (PCRE classes, lookarounds, lazy quantifiers,
|
|
464
|
+
* POSIX bracket classes, GNU word anchors) must fall back to the host walk.
|
|
465
|
+
*/
|
|
466
|
+
static ERE_UNSUPPORTED = /\\[dDwWsSbB<>]|\(\?|[*+?}]\?|\[:[a-z]+:\]/;
|
|
467
|
+
async grepWithPosixGrep(abs, options) {
|
|
468
|
+
if (SandboxFilesystem.ERE_UNSUPPORTED.test(options.pattern)) throw new UnsupportedGrepPatternError(options.pattern);
|
|
469
|
+
let jsRegex;
|
|
470
|
+
try {
|
|
471
|
+
jsRegex = new RegExp(options.pattern, options.caseSensitive ? "" : "i");
|
|
472
|
+
} catch {
|
|
473
|
+
throw new UnsupportedGrepPatternError(options.pattern);
|
|
474
|
+
}
|
|
475
|
+
if (options.contextLines) throw new UnsupportedGrepPatternError(options.pattern);
|
|
476
|
+
const args = [
|
|
477
|
+
"grep -rnIE",
|
|
478
|
+
options.caseSensitive ? "" : "-i",
|
|
479
|
+
options.maxCountPerFile !== void 0 ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : "",
|
|
480
|
+
"--",
|
|
481
|
+
shellQuote(options.pattern),
|
|
482
|
+
shellQuote(abs)
|
|
483
|
+
].filter(Boolean).join(" ");
|
|
484
|
+
const result = await this.exec(args);
|
|
485
|
+
if (result.exitCode === 1) return [];
|
|
486
|
+
if (result.exitCode !== 0) throw new UnsupportedGrepPatternError(options.pattern);
|
|
487
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
488
|
+
for (const line of result.stdout.split("\n")) {
|
|
489
|
+
if (!line) continue;
|
|
490
|
+
const parsed = /^(.*?):(\d+):(.*)$/.exec(line);
|
|
491
|
+
if (!parsed) continue;
|
|
492
|
+
const rel = posix.relative(abs, parsed[1]) || posix.basename(parsed[1]);
|
|
493
|
+
const text = parsed[3];
|
|
494
|
+
const column = jsRegex.exec(text)?.index;
|
|
495
|
+
if (column === void 0) throw new UnsupportedGrepPatternError(options.pattern);
|
|
496
|
+
let matches = byFile.get(rel);
|
|
497
|
+
if (!matches) {
|
|
498
|
+
matches = [];
|
|
499
|
+
byFile.set(rel, matches);
|
|
500
|
+
}
|
|
501
|
+
matches.push({
|
|
502
|
+
line: Number(parsed[2]),
|
|
503
|
+
column,
|
|
504
|
+
text
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
const results = [...byFile.entries()].map(([path, matches]) => ({
|
|
508
|
+
path,
|
|
509
|
+
matches
|
|
510
|
+
}));
|
|
511
|
+
return this.applyTotalCap(results, options.maxTotalMatches);
|
|
512
|
+
}
|
|
513
|
+
applyTotalCap(results, maxTotal) {
|
|
514
|
+
if (maxTotal === void 0) return results;
|
|
515
|
+
const capped = [];
|
|
516
|
+
let total = 0;
|
|
517
|
+
for (const file of results) {
|
|
518
|
+
if (total >= maxTotal) break;
|
|
519
|
+
const remaining = maxTotal - total;
|
|
520
|
+
const matches = file.matches.slice(0, remaining);
|
|
521
|
+
total += matches.length;
|
|
522
|
+
capped.push({
|
|
523
|
+
path: file.path,
|
|
524
|
+
matches
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
return capped;
|
|
528
|
+
}
|
|
307
529
|
async exists(path) {
|
|
308
530
|
const abs = await this.resolveAsync(path);
|
|
309
531
|
return (await this.exec(`test -e ${shellQuote(abs)}`)).exitCode === 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox-filesystem.js","names":["posixPath"],"sources":["../../src/agents/sandbox-filesystem.ts"],"sourcesContent":["/**\n * SandboxFilesystem\n *\n * A `WorkspaceFilesystem` that stores files inside a remote `MastraSandbox`\n * (e.g. a Railway VM) rather than on the server host. File operations are\n * implemented by shelling out through the sandbox's `executeCommand`, so the\n * agent's file tools and command tools share one VM and one view of the repo.\n *\n * Paths are workspace-relative (`/src/foo.ts`) and resolve under the sandbox\n * working directory (`basePath`). A traversal guard rejects any path that\n * escapes the workdir, mirroring `LocalFilesystem`'s contained mode.\n *\n * Reads/writes use base64 over the wire so binary content survives the shell.\n */\n\nimport { posix as posixPath } from 'node:path';\nimport type {\n CopyOptions,\n FileContent,\n FileEntry,\n FileStat,\n FilesystemInfo,\n ListOptions,\n ProviderStatus,\n ReadOptions,\n RemoveOptions,\n WorkspaceFilesystem,\n WriteOptions,\n} from '@mastra/core/workspace';\nimport { FileExistsError, FileNotFoundError, IsDirectoryError } from '@mastra/core/workspace';\n\n/**\n * Sentinel exit codes used by guard clauses that run before the real command,\n * so shell failures can be mapped to typed filesystem errors.\n */\nconst EXIT_NOT_FOUND = 20;\nconst EXIT_IS_DIRECTORY = 21;\nconst EXIT_EXISTS = 22;\n\n/** Minimal command result shape we depend on. */\nexport interface SandboxCommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/** Minimal sandbox surface the filesystem needs. */\nexport interface SandboxExec {\n readonly id: string;\n executeCommand(command: string, args?: string[], options?: { timeout?: number }): Promise<SandboxCommandResult>;\n}\n\nexport interface SandboxFilesystemOptions {\n /** Live sandbox to run commands in. */\n sandbox: SandboxExec;\n /**\n * Absolute path inside the sandbox that is the workspace root — or a lazy\n * resolver for it. The resolver form exists for sandboxes whose workspace\n * root is only knowable once the VM is running (e.g. `$HOME/<repo>` under\n * a provider-chosen home dir): it is awaited on the first file operation\n * (which itself may lazily start the VM) and the result is memoized.\n */\n workdir: string | (() => Promise<string> | string);\n /** Optional stable id; defaults to a sandbox-derived id. */\n id?: string;\n}\n\n/** Default per-command deadline so a hung sandbox can't block file tools forever. */\nconst COMMAND_TIMEOUT_MS = 30_000;\n\n/** Single-quote a string for safe POSIX shell interpolation. */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\nfunction isFileContentString(content: FileContent): content is string {\n return typeof content === 'string';\n}\n\nfunction toBuffer(content: FileContent): Buffer {\n if (isFileContentString(content)) return Buffer.from(content, 'utf8');\n return Buffer.from(content);\n}\n\nexport class SandboxFilesystem implements WorkspaceFilesystem {\n readonly id: string;\n readonly name = 'SandboxFilesystem';\n readonly provider = 'sandbox';\n status: ProviderStatus = 'ready';\n\n private readonly sandbox: SandboxExec;\n private readonly workdirSource: string | (() => Promise<string> | string);\n private resolvedBase?: string;\n private resolvingBase?: Promise<string>;\n\n constructor(options: SandboxFilesystemOptions) {\n this.sandbox = options.sandbox;\n this.workdirSource = options.workdir;\n if (typeof options.workdir === 'string') this.resolvedBase = options.workdir;\n // Include the workdir when known: one sandbox can back several\n // filesystems rooted at different checkouts, and each needs a distinct\n // id. Lazy-workdir callers pass an explicit id.\n this.id =\n options.id ??\n (typeof options.workdir === 'string'\n ? `sandbox-fs:${options.sandbox.id}:${options.workdir}`\n : `sandbox-fs:${options.sandbox.id}`);\n }\n\n /** The resolved workspace root; empty until a lazy workdir first resolves. */\n get basePath(): string {\n return this.resolvedBase ?? '';\n }\n\n /** Await (and memoize) the workspace root, resolving a lazy workdir once. */\n private async base(): Promise<string> {\n if (this.resolvedBase) return this.resolvedBase;\n const source = this.workdirSource;\n if (typeof source === 'string') return (this.resolvedBase = source);\n this.resolvingBase ??= Promise.resolve()\n .then(source)\n .then(resolved => {\n if (!resolved) throw new Error('Sandbox workspace root resolution returned an empty path');\n return (this.resolvedBase = resolved);\n })\n .finally(() => {\n this.resolvingBase = undefined;\n });\n return this.resolvingBase;\n }\n\n // ── Path handling ──────────────────────────────────────────────────────\n\n /**\n * Resolve a workspace path to an absolute path inside the sandbox, enforcing\n * that it stays within the workdir. Awaits the workspace root first, which\n * for a lazy workdir may start the VM.\n */\n private async resolveAsync(inputPath: string): Promise<string> {\n return this.resolveAgainst(await this.base(), inputPath);\n }\n\n /**\n * Resolve a workspace path against a known base, enforcing that it stays\n * within the workdir.\n *\n * Accepts both workspace-relative paths (`src/foo.ts`, `/src/foo.ts`) and\n * absolute sandbox paths that already live under the workdir — the agent's\n * prompt advertises the workdir as its working directory, so tools are\n * routinely called with fully-qualified paths like `<workdir>/src/foo.ts`.\n */\n private resolveAgainst(basePath: string, inputPath: string): string {\n const base = posixPath.normalize(basePath);\n const normalizedInput = posixPath.normalize(inputPath);\n const rel =\n normalizedInput === base\n ? ''\n : normalizedInput.startsWith(`${base}/`)\n ? normalizedInput.slice(base.length + 1)\n : inputPath.startsWith('/')\n ? inputPath.slice(1)\n : inputPath;\n const resolved = posixPath.normalize(posixPath.join(base, rel));\n if (resolved !== base && !resolved.startsWith(`${base}/`)) {\n throw new Error(`Path escapes workspace root: ${inputPath}`);\n }\n return resolved;\n }\n\n resolveAbsolutePath(inputPath: string): string | undefined {\n // Sync interface: a lazy workdir that has not resolved yet has no\n // absolute form to offer.\n if (!this.resolvedBase) return undefined;\n return this.resolveAgainst(this.resolvedBase, inputPath);\n }\n\n // ── Command helper ─────────────────────────────────────────────────────\n\n private async exec(script: string): Promise<SandboxCommandResult> {\n return this.sandbox.executeCommand('sh', ['-c', script], { timeout: COMMAND_TIMEOUT_MS });\n }\n\n /**\n * Lexical guard catches `..` traversal, but a symlink inside the workdir can\n * still point outside it. After resolving a path that refers to an existing\n * entry, verify its realpath is still contained in the workdir.\n *\n * Canonicalization tries `realpath`, then `readlink -f` (GNU/busybox), then\n * `cd && pwd -P` for directories — covering GNU hosts, macOS/BSD, and\n * busybox. If the path exists but cannot be canonicalized we fail CLOSED:\n * returning without a check would let a symlink bypass containment.\n */\n private async assertContainedRealpath(abs: string, inputPath: string): Promise<void> {\n const result = await this.exec(\n [\n `p=${shellQuote(abs)}`,\n `if [ ! -e \"$p\" ] && [ ! -L \"$p\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n // The workdir itself may contain symlinked components (/tmp on macOS),\n // so canonicalize it as the comparison root.\n `root=$(cd ${shellQuote(this.basePath)} 2>/dev/null && pwd -P)`,\n `[ -n \"$root\" ] || exit 1`,\n `rp=$(realpath \"$p\" 2>/dev/null) || rp=$(readlink -f \"$p\" 2>/dev/null) || { [ -d \"$p\" ] && rp=$(cd \"$p\" 2>/dev/null && pwd -P); }`,\n `[ -n \"$rp\" ] || exit 1`,\n `printf '%s\\\\n%s' \"$root\" \"$rp\"`,\n ].join('\\n'),\n );\n // Path doesn't exist yet: nothing to canonicalize (writes to a fresh leaf\n // are covered by assertContainedDest checking the parent directory).\n if (result.exitCode === EXIT_NOT_FOUND) return;\n const [root, real] = result.stdout.split('\\n').map(s => s.trim());\n if (result.exitCode !== 0 || !root || !real) {\n throw new Error(`Unable to verify path stays within workspace root: ${inputPath}`);\n }\n if (real !== root && !real.startsWith(`${root}/`)) {\n throw new Error(`Path escapes workspace root (symlink): ${inputPath}`);\n }\n }\n\n /**\n * Guard for write destinations. The lexical guard catches `..`, but a symlink\n * inside the workdir can redirect a write outside it. For an existing target\n * we check its realpath; for a not-yet-existing target we check the realpath\n * of its nearest existing ancestor directory, since a symlinked parent is the\n * escape vector (e.g. `link -> /etc` then writing `link/passwd`).\n */\n private async assertContainedDest(abs: string, inputPath: string): Promise<void> {\n // First check the target itself (covers overwriting an existing symlink).\n await this.assertContainedRealpath(abs, inputPath);\n // Then check the parent directory's realpath; readlink -f resolves the\n // nearest existing ancestor when the leaf doesn't exist yet.\n const parent = posixPath.dirname(abs);\n if (parent && parent !== abs) {\n await this.assertContainedRealpath(parent, inputPath);\n }\n }\n\n private async execOk(script: string, context: string): Promise<SandboxCommandResult> {\n const result = await this.exec(script);\n if (result.exitCode !== 0) {\n throw new Error(`${context} failed (exit ${result.exitCode}): ${result.stderr.trim() || result.stdout.trim()}`);\n }\n return result;\n }\n\n // ── File operations ────────────────────────────────────────────────────\n\n async readFile(path: string, options?: ReadOptions): Promise<string | Buffer> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedRealpath(abs, path);\n // Guard clauses first: redirecting from a directory \"succeeds\" with empty\n // output on some shells, so classify before reading.\n const result = await this.exec(\n `if [ -d ${shellQuote(abs)} ]; then exit ${EXIT_IS_DIRECTORY}; elif [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; base64 < ${shellQuote(abs)}`,\n );\n if (result.exitCode === EXIT_IS_DIRECTORY) throw new IsDirectoryError(path);\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(path);\n if (result.exitCode !== 0) {\n throw new Error(`readFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n const buffer = Buffer.from(result.stdout.replace(/\\s/g, ''), 'base64');\n if (options?.encoding) {\n return buffer.toString(options.encoding);\n }\n return buffer;\n }\n\n async writeFile(path: string, content: FileContent, options?: WriteOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedDest(abs, path);\n const b64 = toBuffer(content).toString('base64');\n const dir = posixPath.dirname(abs);\n const mkdir = options?.recursive === false ? '' : `mkdir -p ${shellQuote(dir)} && `;\n if (options?.overwrite === false) {\n // `set -C` (noclobber) makes the redirect itself the exclusivity check —\n // no exists() pre-check that could race with a concurrent writer.\n const result = await this.exec(\n `${mkdir}{ (set -C; printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}) 2>/dev/null || { [ -e ${shellQuote(abs)} ] && exit ${EXIT_EXISTS} || exit 1; }; }`,\n );\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(path);\n if (result.exitCode !== 0) {\n throw new Error(`writeFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n await this.execOk(`${mkdir}printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}`, `writeFile ${path}`);\n }\n\n async appendFile(path: string, content: FileContent): Promise<void> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedDest(abs, path);\n const b64 = toBuffer(content).toString('base64');\n await this.execOk(\n `mkdir -p ${shellQuote(posixPath.dirname(abs))} && printf %s ${shellQuote(b64)} | base64 -d >> ${shellQuote(abs)}`,\n `appendFile ${path}`,\n );\n }\n\n async deleteFile(path: string, options?: RemoveOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n // Contain the parent's realpath: deleting `link/file` where `link` points\n // outside the workdir must fail, while deleting a symlink entry itself\n // (which lives inside the workdir) stays allowed.\n await this.assertContainedRealpath(posixPath.dirname(abs), path);\n if (options?.force) {\n // `rm -f` already succeeds for a missing file, but still fails for\n // directories and permission errors — surface those.\n await this.execOk(`rm -f ${shellQuote(abs)}`, `deleteFile ${path}`);\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; rm ${shellQuote(abs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(path);\n if (result.exitCode !== 0) {\n throw new Error(`deleteFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n async copyFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n const srcAbs = await this.resolveAsync(src);\n const destAbs = await this.resolveAsync(dest);\n await this.assertContainedRealpath(srcAbs, src);\n await this.assertContainedDest(destAbs, dest);\n const recursive = options?.recursive ? '-r ' : '';\n if (options?.overwrite === false) {\n // Atomic no-clobber: directories claim the destination with an exclusive\n // mkdir; files copy to a temp name then hardlink into place (link(2)\n // fails if the destination exists). No racy exists() pre-check.\n const result = await this.exec(\n [\n `src=${shellQuote(srcAbs)}`,\n `dest=${shellQuote(destAbs)}`,\n `if [ ! -e \"$src\" ] && [ ! -L \"$src\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n `mkdir -p ${shellQuote(posixPath.dirname(destAbs))} || exit 1`,\n `if [ -d \"$src\" ]; then`,\n ` mkdir \"$dest\" 2>/dev/null || exit ${EXIT_EXISTS}`,\n ` cp -R \"$src\"/. \"$dest\"/`,\n `else`,\n ` tmp=\"$dest.__cptmp$$\"`,\n ` cp \"$src\" \"$tmp\" || exit 1`,\n ` ln \"$tmp\" \"$dest\" 2>/dev/null || { rm -f \"$tmp\"; [ -e \"$dest\" ] && exit ${EXIT_EXISTS} || exit 1; }`,\n ` rm -f \"$tmp\"`,\n `fi`,\n ].join('\\n'),\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(dest);\n if (result.exitCode !== 0) {\n throw new Error(`copyFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(srcAbs)} ]; then exit ${EXIT_NOT_FOUND}; fi; mkdir -p ${shellQuote(posixPath.dirname(destAbs))} && cp ${recursive}${shellQuote(srcAbs)} ${shellQuote(destAbs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode !== 0) {\n throw new Error(`copyFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n async moveFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n const srcAbs = await this.resolveAsync(src);\n const destAbs = await this.resolveAsync(dest);\n await this.assertContainedRealpath(srcAbs, src);\n await this.assertContainedDest(destAbs, dest);\n if (options?.overwrite === false) {\n // `mv -n` exits 0 even when it skips, so detect a skipped move by the\n // source surviving. The no-clobber rename itself is atomic; no racy\n // exists() pre-check.\n const result = await this.exec(\n [\n `src=${shellQuote(srcAbs)}`,\n `dest=${shellQuote(destAbs)}`,\n `if [ ! -e \"$src\" ] && [ ! -L \"$src\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n `mkdir -p ${shellQuote(posixPath.dirname(destAbs))} || exit 1`,\n `mv -n \"$src\" \"$dest\" 2>/dev/null || exit 1`,\n `if [ -e \"$src\" ] || [ -L \"$src\" ]; then exit ${EXIT_EXISTS}; fi`,\n ].join('\\n'),\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(dest);\n if (result.exitCode !== 0) {\n throw new Error(`moveFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(srcAbs)} ]; then exit ${EXIT_NOT_FOUND}; fi; mkdir -p ${shellQuote(posixPath.dirname(destAbs))} && mv ${shellQuote(srcAbs)} ${shellQuote(destAbs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode !== 0) {\n throw new Error(`moveFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n // ── Directory operations ───────────────────────────────────────────────\n\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedDest(abs, path);\n const flag = options?.recursive === false ? '' : '-p ';\n await this.execOk(`mkdir ${flag}${shellQuote(abs)}`, `mkdir ${path}`);\n }\n\n async rmdir(path: string, options?: RemoveOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n // Same parent containment as deleteFile — `rm -r` through a symlinked\n // parent would otherwise delete outside the workspace.\n await this.assertContainedRealpath(posixPath.dirname(abs), path);\n if (options?.recursive) {\n const force = options?.force ? '-f ' : '';\n await this.execOk(`rm -r ${force}${shellQuote(abs)}`, `rmdir ${path}`);\n return;\n }\n const result = await this.exec(`rmdir ${shellQuote(abs)}`);\n if (result.exitCode !== 0 && !options?.force) {\n throw new Error(`Directory not empty or not found: ${path}`);\n }\n }\n\n async readdir(path: string, options?: ListOptions): Promise<FileEntry[]> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedRealpath(abs, path);\n if (options?.recursive) {\n // Recursive listing emitting \"type\\tpath\". `find -printf` is GNU-only\n // (fails on macOS/BSD hosts backing a local sandbox), so classify each\n // entry with a portable shell loop instead.\n const result = await this.exec(\n `test -d ${shellQuote(abs)} && find ${shellQuote(abs)} -mindepth 1 ${options.maxDepth ? `-maxdepth ${Number(options.maxDepth)} ` : ''}2>/dev/null | while IFS= read -r f; do if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`,\n );\n if (result.exitCode !== 0) throw new Error(`Directory not found: ${path}`);\n return this.parseFindOutput(result.stdout, abs, options);\n }\n // Non-recursive: list with name + type via a portable loop. Use printf,\n // not echo — bash-as-/bin/sh (macOS local sandboxes) does not expand \\t\n // in echo arguments.\n const result = await this.exec(\n `cd ${shellQuote(abs)} 2>/dev/null && for f in * .[!.]*; do [ -e \"$f\" ] || continue; if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`,\n );\n if (result.exitCode !== 0) throw new Error(`Directory not found: ${path}`);\n return this.parseListOutput(result.stdout, options);\n }\n\n private parseListOutput(stdout: string, options?: ListOptions): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const type = line.slice(0, tab) === 'd' ? 'directory' : 'file';\n const name = line.slice(tab + 1);\n if (!name || name === '.' || name === '..') continue;\n if (type === 'file' && !this.matchesExtension(name, options?.extension)) continue;\n entries.push({ name, type });\n }\n return entries;\n }\n\n private parseFindOutput(stdout: string, base: string, options?: ListOptions): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const type = line.slice(0, tab) === 'd' ? 'directory' : 'file';\n const fullPath = line.slice(tab + 1);\n const name = posixPath.relative(base, fullPath);\n if (!name) continue;\n if (type === 'file' && !this.matchesExtension(name, options?.extension)) continue;\n entries.push({ name, type });\n }\n return entries;\n }\n\n private matchesExtension(name: string, extension?: string | string[]): boolean {\n if (!extension) return true;\n const exts = Array.isArray(extension) ? extension : [extension];\n return exts.some(ext => name.endsWith(ext));\n }\n\n // ── Path / metadata ────────────────────────────────────────────────────\n\n async exists(path: string): Promise<boolean> {\n const abs = await this.resolveAsync(path);\n const result = await this.exec(`test -e ${shellQuote(abs)}`);\n return result.exitCode === 0;\n }\n\n async stat(path: string): Promise<FileStat> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedRealpath(abs, path);\n // GNU stat: %F=type, %s=size, %Y=mtime (epoch seconds), %W=birth (or -1).\n // BSD/macOS stat (local sandbox hosts) rejects `-c`; fall back to its\n // `-f` format with the same field order (%HT=type, %z=size, %m=mtime,\n // %B=birth). Delimit with `|` — neither stat interprets `\\t` escapes in\n // its format string.\n const result = await this.exec(\n `stat -c '%F|%s|%Y|%W' ${shellQuote(abs)} 2>/dev/null || stat -f '%HT|%z|%m|%B' ${shellQuote(abs)}`,\n );\n if (result.exitCode !== 0) {\n throw new FileNotFoundError(path);\n }\n const [kind, sizeStr, mtimeStr, ctimeStr] = result.stdout.trim().split('|');\n const type = kind && kind.toLowerCase().includes('directory') ? 'directory' : 'file';\n const size = Number(sizeStr) || 0;\n const mtime = Number(mtimeStr) || 0;\n const ctime = Number(ctimeStr);\n return {\n name: posixPath.basename(abs),\n path: `/${posixPath.relative(this.basePath, abs)}`,\n type,\n size: type === 'directory' ? 0 : size,\n modifiedAt: new Date(mtime * 1000),\n createdAt: new Date((ctime > 0 ? ctime : mtime) * 1000),\n };\n }\n\n // ── Lifecycle ──────────────────────────────────────────────────────────\n\n async init(): Promise<void> {\n await this.execOk(`mkdir -p ${shellQuote(await this.base())}`, 'init workdir');\n }\n\n async destroy(): Promise<void> {\n // The sandbox lifecycle is owned by the caller; nothing to tear down here.\n }\n\n async isReady(): Promise<boolean> {\n const result = await this.exec(`test -d ${shellQuote(await this.base())}`);\n return result.exitCode === 0;\n }\n\n getInfo(): FilesystemInfo {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n metadata: { basePath: this.basePath, sandboxId: this.sandbox.id },\n };\n }\n\n getInstructions(): string {\n return `Files are stored in a remote sandbox at ${this.basePath}. Use absolute workspace paths like /src/index.ts. All reads, writes and commands run inside the same sandbox.`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmCA,MAAM,iBAAiB;AACvB,MAAM,oBAAoB;AAC1B,MAAM,cAAc;;AA+BpB,MAAM,qBAAqB;;AAG3B,SAAS,WAAW,OAAuB;CACzC,OAAO,IAAI,MAAM,QAAQ,MAAM,OAAO,EAAE;AAC1C;AAEA,SAAS,oBAAoB,SAAyC;CACpE,OAAO,OAAO,YAAY;AAC5B;AAEA,SAAS,SAAS,SAA8B;CAC9C,IAAI,oBAAoB,OAAO,GAAG,OAAO,OAAO,KAAK,SAAS,MAAM;CACpE,OAAO,OAAO,KAAK,OAAO;AAC5B;AAEA,IAAa,oBAAb,MAA8D;CAC5D;CACA,OAAgB;CAChB,WAAoB;CACpB,SAAyB;CAEzB;CACA;CACA;CACA;CAEA,YAAY,SAAmC;EAC7C,KAAK,UAAU,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7B,OAAO;GACL,MAAMA,MAAU,SAAS,GAAG;GAC5B,MAAM,IAAIA,MAAU,SAAS,KAAK,UAAU,GAAG;GAC/C;GACA,MAAM,SAAS,cAAc,IAAI;GACjC,4BAAY,IAAI,KAAK,QAAQ,GAAI;GACjC,2BAAW,IAAI,MAAM,QAAQ,IAAI,QAAQ,SAAS,GAAI;EACxD;CACF;CAIA,MAAM,OAAsB;EAC1B,MAAM,KAAK,OAAO,YAAY,WAAW,MAAM,KAAK,KAAK,CAAC,KAAK,cAAc;CAC/E;CAEA,MAAM,UAAyB,CAE/B;CAEA,MAAM,UAA4B;EAEhC,QAAO,MADc,KAAK,KAAK,WAAW,WAAW,MAAM,KAAK,KAAK,CAAC,GAAG,EAAA,CAC3D,aAAa;CAC7B;CAEA,UAA0B;EACxB,OAAO;GACL,IAAI,KAAK;GACT,MAAM,KAAK;GACX,UAAU,KAAK;GACf,QAAQ,KAAK;GACb,UAAU;IAAE,UAAU,KAAK;IAAU,WAAW,KAAK,QAAQ;GAAG;EAClE;CACF;CAEA,kBAA0B;EACxB,OAAO,2CAA2C,KAAK,SAAS;CAClE;AACF"}
|
|
1
|
+
{"version":3,"file":"sandbox-filesystem.js","names":["posixPath"],"sources":["../../src/agents/sandbox-filesystem.ts"],"sourcesContent":["/**\n * SandboxFilesystem\n *\n * A `WorkspaceFilesystem` that stores files inside a remote `MastraSandbox`\n * (e.g. a Railway VM) rather than on the server host. File operations are\n * implemented by shelling out through the sandbox's `executeCommand`, so the\n * agent's file tools and command tools share one VM and one view of the repo.\n *\n * Paths are workspace-relative (`/src/foo.ts`) and resolve under the sandbox\n * working directory (`basePath`). A traversal guard rejects any path that\n * escapes the workdir, mirroring `LocalFilesystem`'s contained mode.\n *\n * Reads/writes use base64 over the wire so binary content survives the shell.\n */\n\nimport { posix as posixPath } from 'node:path';\nimport type {\n CopyOptions,\n FileContent,\n FileEntry,\n FileStat,\n FilesystemGrepMatch,\n FilesystemGrepOptions,\n FilesystemGrepResult,\n FilesystemInfo,\n ListOptions,\n ProviderStatus,\n ReadOptions,\n RemoveOptions,\n WalkEntry,\n WalkOptions,\n WorkspaceFilesystem,\n WriteOptions,\n} from '@mastra/core/workspace';\nimport {\n DirectoryNotFoundError,\n FileExistsError,\n FileNotFoundError,\n IsDirectoryError,\n NotDirectoryError,\n UnsupportedGrepPatternError,\n} from '@mastra/core/workspace';\n\n/**\n * Sentinel exit codes used by guard clauses that run before the real command,\n * so shell failures can be mapped to typed filesystem errors.\n */\nconst EXIT_NOT_FOUND = 20;\nconst EXIT_IS_DIRECTORY = 21;\nconst EXIT_EXISTS = 22;\nconst EXIT_NOT_DIRECTORY = 23;\n\n/** Minimal command result shape we depend on. */\nexport interface SandboxCommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/** Minimal sandbox surface the filesystem needs. */\nexport interface SandboxExec {\n readonly id: string;\n executeCommand(command: string, args?: string[], options?: { timeout?: number }): Promise<SandboxCommandResult>;\n}\n\nexport interface SandboxFilesystemOptions {\n /** Live sandbox to run commands in. */\n sandbox: SandboxExec;\n /**\n * Absolute path inside the sandbox that is the workspace root — or a lazy\n * resolver for it. The resolver form exists for sandboxes whose workspace\n * root is only knowable once the VM is running (e.g. `$HOME/<repo>` under\n * a provider-chosen home dir): it is awaited on the first file operation\n * (which itself may lazily start the VM) and the result is memoized.\n */\n workdir: string | (() => Promise<string> | string);\n /** Optional stable id; defaults to a sandbox-derived id. */\n id?: string;\n}\n\n/** Default per-command deadline so a hung sandbox can't block file tools forever. */\nconst COMMAND_TIMEOUT_MS = 30_000;\n\n/** Single-quote a string for safe POSIX shell interpolation. */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\nfunction isFileContentString(content: FileContent): content is string {\n return typeof content === 'string';\n}\n\nfunction toBuffer(content: FileContent): Buffer {\n if (isFileContentString(content)) return Buffer.from(content, 'utf8');\n return Buffer.from(content);\n}\n\nexport class SandboxFilesystem implements WorkspaceFilesystem {\n readonly id: string;\n readonly name = 'SandboxFilesystem';\n readonly provider = 'sandbox';\n status: ProviderStatus = 'ready';\n\n private readonly sandbox: SandboxExec;\n private readonly workdirSource: string | (() => Promise<string> | string);\n private resolvedBase?: string;\n private resolvingBase?: Promise<string>;\n\n constructor(options: SandboxFilesystemOptions) {\n this.sandbox = options.sandbox;\n this.workdirSource = options.workdir;\n if (typeof options.workdir === 'string') this.resolvedBase = options.workdir;\n // Include the workdir when known: one sandbox can back several\n // filesystems rooted at different checkouts, and each needs a distinct\n // id. Lazy-workdir callers pass an explicit id.\n this.id =\n options.id ??\n (typeof options.workdir === 'string'\n ? `sandbox-fs:${options.sandbox.id}:${options.workdir}`\n : `sandbox-fs:${options.sandbox.id}`);\n }\n\n /** The resolved workspace root; empty until a lazy workdir first resolves. */\n get basePath(): string {\n return this.resolvedBase ?? '';\n }\n\n /** Await (and memoize) the workspace root, resolving a lazy workdir once. */\n private async base(): Promise<string> {\n if (this.resolvedBase) return this.resolvedBase;\n const source = this.workdirSource;\n if (typeof source === 'string') return (this.resolvedBase = source);\n this.resolvingBase ??= Promise.resolve()\n .then(source)\n .then(resolved => {\n if (!resolved) throw new Error('Sandbox workspace root resolution returned an empty path');\n return (this.resolvedBase = resolved);\n })\n .finally(() => {\n this.resolvingBase = undefined;\n });\n return this.resolvingBase;\n }\n\n // ── Path handling ──────────────────────────────────────────────────────\n\n /**\n * Resolve a workspace path to an absolute path inside the sandbox, enforcing\n * that it stays within the workdir. Awaits the workspace root first, which\n * for a lazy workdir may start the VM.\n */\n private async resolveAsync(inputPath: string): Promise<string> {\n return this.resolveAgainst(await this.base(), inputPath);\n }\n\n /**\n * Resolve a workspace path against a known base, enforcing that it stays\n * within the workdir.\n *\n * Accepts both workspace-relative paths (`src/foo.ts`, `/src/foo.ts`) and\n * absolute sandbox paths that already live under the workdir — the agent's\n * prompt advertises the workdir as its working directory, so tools are\n * routinely called with fully-qualified paths like `<workdir>/src/foo.ts`.\n */\n private resolveAgainst(basePath: string, inputPath: string): string {\n const base = posixPath.normalize(basePath);\n const normalizedInput = posixPath.normalize(inputPath);\n const rel =\n normalizedInput === base\n ? ''\n : normalizedInput.startsWith(`${base}/`)\n ? normalizedInput.slice(base.length + 1)\n : inputPath.startsWith('/')\n ? inputPath.slice(1)\n : inputPath;\n const resolved = posixPath.normalize(posixPath.join(base, rel));\n if (resolved !== base && !resolved.startsWith(`${base}/`)) {\n throw new Error(`Path escapes workspace root: ${inputPath}`);\n }\n return resolved;\n }\n\n resolveAbsolutePath(inputPath: string): string | undefined {\n // Sync interface: a lazy workdir that has not resolved yet has no\n // absolute form to offer.\n if (!this.resolvedBase) return undefined;\n return this.resolveAgainst(this.resolvedBase, inputPath);\n }\n\n // ── Command helper ─────────────────────────────────────────────────────\n\n private async exec(script: string): Promise<SandboxCommandResult> {\n return this.sandbox.executeCommand('sh', ['-c', script], { timeout: COMMAND_TIMEOUT_MS });\n }\n\n /**\n * Lexical guard catches `..` traversal, but a symlink inside the workdir can\n * still point outside it. After resolving a path that refers to an existing\n * entry, verify its realpath is still contained in the workdir.\n *\n * Canonicalization tries `realpath`, then `readlink -f` (GNU/busybox), then\n * `cd && pwd -P` for directories — covering GNU hosts, macOS/BSD, and\n * busybox. If the path exists but cannot be canonicalized we fail CLOSED:\n * returning without a check would let a symlink bypass containment.\n */\n private async assertContainedRealpath(abs: string, inputPath: string): Promise<void> {\n const result = await this.exec(\n [\n `p=${shellQuote(abs)}`,\n `if [ ! -e \"$p\" ] && [ ! -L \"$p\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n // The workdir itself may contain symlinked components (/tmp on macOS),\n // so canonicalize it as the comparison root.\n `root=$(cd ${shellQuote(this.basePath)} 2>/dev/null && pwd -P)`,\n `[ -n \"$root\" ] || exit 1`,\n `rp=$(realpath \"$p\" 2>/dev/null) || rp=$(readlink -f \"$p\" 2>/dev/null) || { [ -d \"$p\" ] && rp=$(cd \"$p\" 2>/dev/null && pwd -P); }`,\n `[ -n \"$rp\" ] || exit 1`,\n `printf '%s\\\\n%s' \"$root\" \"$rp\"`,\n ].join('\\n'),\n );\n // Path doesn't exist yet: nothing to canonicalize (writes to a fresh leaf\n // are covered by assertContainedDest checking the parent directory).\n if (result.exitCode === EXIT_NOT_FOUND) return;\n const [root, real] = result.stdout.split('\\n').map(s => s.trim());\n if (result.exitCode !== 0 || !root || !real) {\n throw new Error(`Unable to verify path stays within workspace root: ${inputPath}`);\n }\n if (real !== root && !real.startsWith(`${root}/`)) {\n throw new Error(`Path escapes workspace root (symlink): ${inputPath}`);\n }\n }\n\n /**\n * Guard for write destinations. The lexical guard catches `..`, but a symlink\n * inside the workdir can redirect a write outside it. For an existing target\n * we check its realpath; for a not-yet-existing target we check the realpath\n * of its nearest existing ancestor directory, since a symlinked parent is the\n * escape vector (e.g. `link -> /etc` then writing `link/passwd`).\n */\n private async assertContainedDest(abs: string, inputPath: string): Promise<void> {\n // First check the target itself (covers overwriting an existing symlink).\n await this.assertContainedRealpath(abs, inputPath);\n // Then check the parent directory's realpath; readlink -f resolves the\n // nearest existing ancestor when the leaf doesn't exist yet.\n const parent = posixPath.dirname(abs);\n if (parent && parent !== abs) {\n await this.assertContainedRealpath(parent, inputPath);\n }\n }\n\n private async execOk(script: string, context: string): Promise<SandboxCommandResult> {\n const result = await this.exec(script);\n if (result.exitCode !== 0) {\n throw new Error(`${context} failed (exit ${result.exitCode}): ${result.stderr.trim() || result.stdout.trim()}`);\n }\n return result;\n }\n\n // ── File operations ────────────────────────────────────────────────────\n\n async readFile(path: string, options?: ReadOptions): Promise<string | Buffer> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedRealpath(abs, path);\n // Guard clauses first: redirecting from a directory \"succeeds\" with empty\n // output on some shells, so classify before reading.\n const result = await this.exec(\n `if [ -d ${shellQuote(abs)} ]; then exit ${EXIT_IS_DIRECTORY}; elif [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; base64 < ${shellQuote(abs)}`,\n );\n if (result.exitCode === EXIT_IS_DIRECTORY) throw new IsDirectoryError(path);\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(path);\n if (result.exitCode !== 0) {\n throw new Error(`readFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n const buffer = Buffer.from(result.stdout.replace(/\\s/g, ''), 'base64');\n if (options?.encoding) {\n return buffer.toString(options.encoding);\n }\n return buffer;\n }\n\n async writeFile(path: string, content: FileContent, options?: WriteOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedDest(abs, path);\n const b64 = toBuffer(content).toString('base64');\n const dir = posixPath.dirname(abs);\n const mkdir = options?.recursive === false ? '' : `mkdir -p ${shellQuote(dir)} && `;\n if (options?.overwrite === false) {\n // `set -C` (noclobber) makes the redirect itself the exclusivity check —\n // no exists() pre-check that could race with a concurrent writer.\n const result = await this.exec(\n `${mkdir}{ (set -C; printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}) 2>/dev/null || { [ -e ${shellQuote(abs)} ] && exit ${EXIT_EXISTS} || exit 1; }; }`,\n );\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(path);\n if (result.exitCode !== 0) {\n throw new Error(`writeFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n await this.execOk(`${mkdir}printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}`, `writeFile ${path}`);\n }\n\n async appendFile(path: string, content: FileContent): Promise<void> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedDest(abs, path);\n const b64 = toBuffer(content).toString('base64');\n await this.execOk(\n `mkdir -p ${shellQuote(posixPath.dirname(abs))} && printf %s ${shellQuote(b64)} | base64 -d >> ${shellQuote(abs)}`,\n `appendFile ${path}`,\n );\n }\n\n async deleteFile(path: string, options?: RemoveOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n // Contain the parent's realpath: deleting `link/file` where `link` points\n // outside the workdir must fail, while deleting a symlink entry itself\n // (which lives inside the workdir) stays allowed.\n await this.assertContainedRealpath(posixPath.dirname(abs), path);\n if (options?.force) {\n // `rm -f` already succeeds for a missing file, but still fails for\n // directories and permission errors — surface those.\n await this.execOk(`rm -f ${shellQuote(abs)}`, `deleteFile ${path}`);\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; rm ${shellQuote(abs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(path);\n if (result.exitCode !== 0) {\n throw new Error(`deleteFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n async copyFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n const srcAbs = await this.resolveAsync(src);\n const destAbs = await this.resolveAsync(dest);\n await this.assertContainedRealpath(srcAbs, src);\n await this.assertContainedDest(destAbs, dest);\n const recursive = options?.recursive ? '-r ' : '';\n if (options?.overwrite === false) {\n // Atomic no-clobber: directories claim the destination with an exclusive\n // mkdir; files copy to a temp name then hardlink into place (link(2)\n // fails if the destination exists). No racy exists() pre-check.\n const result = await this.exec(\n [\n `src=${shellQuote(srcAbs)}`,\n `dest=${shellQuote(destAbs)}`,\n `if [ ! -e \"$src\" ] && [ ! -L \"$src\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n `mkdir -p ${shellQuote(posixPath.dirname(destAbs))} || exit 1`,\n `if [ -d \"$src\" ]; then`,\n ` mkdir \"$dest\" 2>/dev/null || exit ${EXIT_EXISTS}`,\n ` cp -R \"$src\"/. \"$dest\"/`,\n `else`,\n ` tmp=\"$dest.__cptmp$$\"`,\n ` cp \"$src\" \"$tmp\" || exit 1`,\n ` ln \"$tmp\" \"$dest\" 2>/dev/null || { rm -f \"$tmp\"; [ -e \"$dest\" ] && exit ${EXIT_EXISTS} || exit 1; }`,\n ` rm -f \"$tmp\"`,\n `fi`,\n ].join('\\n'),\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(dest);\n if (result.exitCode !== 0) {\n throw new Error(`copyFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(srcAbs)} ]; then exit ${EXIT_NOT_FOUND}; fi; mkdir -p ${shellQuote(posixPath.dirname(destAbs))} && cp ${recursive}${shellQuote(srcAbs)} ${shellQuote(destAbs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode !== 0) {\n throw new Error(`copyFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n async moveFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n const srcAbs = await this.resolveAsync(src);\n const destAbs = await this.resolveAsync(dest);\n await this.assertContainedRealpath(srcAbs, src);\n await this.assertContainedDest(destAbs, dest);\n if (options?.overwrite === false) {\n // `mv -n` exits 0 even when it skips, so detect a skipped move by the\n // source surviving. The no-clobber rename itself is atomic; no racy\n // exists() pre-check.\n const result = await this.exec(\n [\n `src=${shellQuote(srcAbs)}`,\n `dest=${shellQuote(destAbs)}`,\n `if [ ! -e \"$src\" ] && [ ! -L \"$src\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n `mkdir -p ${shellQuote(posixPath.dirname(destAbs))} || exit 1`,\n `mv -n \"$src\" \"$dest\" 2>/dev/null || exit 1`,\n `if [ -e \"$src\" ] || [ -L \"$src\" ]; then exit ${EXIT_EXISTS}; fi`,\n ].join('\\n'),\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(dest);\n if (result.exitCode !== 0) {\n throw new Error(`moveFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(srcAbs)} ]; then exit ${EXIT_NOT_FOUND}; fi; mkdir -p ${shellQuote(posixPath.dirname(destAbs))} && mv ${shellQuote(srcAbs)} ${shellQuote(destAbs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode !== 0) {\n throw new Error(`moveFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n // ── Directory operations ───────────────────────────────────────────────\n\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedDest(abs, path);\n const flag = options?.recursive === false ? '' : '-p ';\n await this.execOk(`mkdir ${flag}${shellQuote(abs)}`, `mkdir ${path}`);\n }\n\n async rmdir(path: string, options?: RemoveOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n // Same parent containment as deleteFile — `rm -r` through a symlinked\n // parent would otherwise delete outside the workspace.\n await this.assertContainedRealpath(posixPath.dirname(abs), path);\n if (options?.recursive) {\n const force = options?.force ? '-f ' : '';\n await this.execOk(`rm -r ${force}${shellQuote(abs)}`, `rmdir ${path}`);\n return;\n }\n const result = await this.exec(`rmdir ${shellQuote(abs)}`);\n if (result.exitCode !== 0 && !options?.force) {\n throw new Error(`Directory not empty or not found: ${path}`);\n }\n }\n\n async readdir(path: string, options?: ListOptions): Promise<FileEntry[]> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedRealpath(abs, path);\n if (options?.recursive) {\n // Recursive listing emitting \"type\\tpath\". `find -printf` is GNU-only\n // (fails on macOS/BSD hosts backing a local sandbox), so classify each\n // entry with a portable shell loop instead.\n const result = await this.exec(\n `test -d ${shellQuote(abs)} && find ${shellQuote(abs)} -mindepth 1 ${options.maxDepth ? `-maxdepth ${Number(options.maxDepth)} ` : ''}2>/dev/null | while IFS= read -r f; do if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`,\n );\n if (result.exitCode !== 0) throw new Error(`Directory not found: ${path}`);\n return this.parseFindOutput(result.stdout, abs, options);\n }\n // Non-recursive: list with name + type via a portable loop. Use printf,\n // not echo — bash-as-/bin/sh (macOS local sandboxes) does not expand \\t\n // in echo arguments.\n const result = await this.exec(\n `cd ${shellQuote(abs)} 2>/dev/null && for f in * .[!.]*; do [ -e \"$f\" ] || continue; if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`,\n );\n if (result.exitCode !== 0) throw new Error(`Directory not found: ${path}`);\n return this.parseListOutput(result.stdout, options);\n }\n\n private parseListOutput(stdout: string, options?: ListOptions): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const type = line.slice(0, tab) === 'd' ? 'directory' : 'file';\n const name = line.slice(tab + 1);\n if (!name || name === '.' || name === '..') continue;\n if (type === 'file' && !this.matchesExtension(name, options?.extension)) continue;\n entries.push({ name, type });\n }\n return entries;\n }\n\n private parseFindOutput(stdout: string, base: string, options?: ListOptions): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const type = line.slice(0, tab) === 'd' ? 'directory' : 'file';\n const fullPath = line.slice(tab + 1);\n const name = posixPath.relative(base, fullPath);\n if (!name) continue;\n if (type === 'file' && !this.matchesExtension(name, options?.extension)) continue;\n entries.push({ name, type });\n }\n return entries;\n }\n\n private matchesExtension(name: string, extension?: string | string[]): boolean {\n if (!extension) return true;\n const exts = Array.isArray(extension) ? extension : [extension];\n return exts.some(ext => name.endsWith(ext));\n }\n\n // ── Native walk / grep capabilities ────────────────────────────────────\n\n /**\n * Walk the tree in a single sandbox command instead of one readdir round\n * trip per directory. Uses `find` with a portable classification loop\n * (`find -printf` is GNU-only and fails on macOS/BSD hosts). `find` does\n * not follow symlinked directories by default, matching the host-side\n * walker's no-recursion-into-symlinks behavior.\n */\n async walk(path: string, options?: WalkOptions): Promise<WalkEntry[]> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedRealpath(abs, path);\n const maxDepth =\n options?.maxDepth !== undefined && Number.isFinite(options.maxDepth)\n ? `-maxdepth ${Math.max(0, Math.floor(options.maxDepth))} `\n : '';\n // Prune hidden entries in-sandbox when not requested, so a huge hidden\n // tree (e.g. `.git`) doesn't inflate the response.\n const hiddenPrune = options?.includeHidden ? '' : `-name '.*' -prune -o `;\n // Emit \"flag\\tpath[\\ttarget]\" — flag is d/f for regular entries, D/F for\n // symlinks (with the link target as a third field).\n const script =\n `root=${shellQuote(abs)}\\n` +\n `[ -e \"$root\" ] || [ -L \"$root\" ] || exit ${EXIT_NOT_FOUND}\\n` +\n `[ -d \"$root\" ] || exit ${EXIT_NOT_DIRECTORY}\\n` +\n `find \"$root\" -mindepth 1 ${maxDepth}${hiddenPrune}-print 2>/dev/null | while IFS= read -r f; do ` +\n `if [ -L \"$f\" ]; then if [ -d \"$f\" ]; then t=D; else t=F; fi; printf '%s\\\\t%s\\\\t%s\\\\n' \"$t\" \"$f\" \"$(readlink \"$f\")\"; ` +\n `elif [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`;\n const result = await this.exec(script);\n if (result.exitCode === EXIT_NOT_FOUND) throw new DirectoryNotFoundError(path);\n if (result.exitCode === EXIT_NOT_DIRECTORY) throw new NotDirectoryError(path);\n if (result.exitCode !== 0) {\n throw new Error(`walk ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n const entries: WalkEntry[] = [];\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const flag = line.slice(0, tab);\n const isSymlink = flag === 'D' || flag === 'F';\n let fullPath = line.slice(tab + 1);\n let symlinkTarget: string | undefined;\n if (isSymlink) {\n const tab2 = fullPath.lastIndexOf('\\t');\n if (tab2 >= 0) {\n symlinkTarget = fullPath.slice(tab2 + 1) || undefined;\n fullPath = fullPath.slice(0, tab2);\n }\n }\n const rel = posixPath.relative(abs, fullPath);\n if (!rel || rel.startsWith('..')) continue;\n entries.push({\n name: posixPath.basename(rel),\n type: flag === 'd' || flag === 'D' ? 'directory' : 'file',\n ...(isSymlink ? { isSymlink: true, ...(symlinkTarget ? { symlinkTarget } : {}) } : {}),\n path: rel,\n });\n }\n return entries;\n }\n\n /**\n * Content search executed inside the sandbox in one command. Prefers\n * ripgrep (`rg --json`) when installed; otherwise falls back to\n * `grep -rnE`. Patterns the ERE fallback can't express (PCRE-style classes,\n * word boundaries, lookarounds, non-greedy quantifiers) throw\n * {@link UnsupportedGrepPatternError} so callers use their host-side walk.\n *\n * Callers are expected to apply their own gitignore/hidden/glob filtering\n * to the returned paths; both engines run with ignore rules disabled so\n * results are a superset of what any host-side filter would keep.\n */\n async grep(options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const abs = await this.resolveAsync(options.path);\n await this.assertContainedRealpath(abs, options.path);\n if (await this.hasRipgrep()) {\n return this.grepWithRipgrep(abs, options);\n }\n return this.grepWithPosixGrep(abs, options);\n }\n\n private rgCheck: Promise<boolean> | undefined;\n\n private hasRipgrep(): Promise<boolean> {\n this.rgCheck ??= this.exec('command -v rg >/dev/null 2>&1').then(\n r => r.exitCode === 0,\n () => false,\n );\n return this.rgCheck;\n }\n\n private async grepWithRipgrep(abs: string, options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const args = [\n 'rg --json --no-ignore --hidden',\n // .git is filtered host-side too; exclude it here so its object files\n // don't inflate the response.\n `-g ${shellQuote('!.git/**')}`,\n options.caseSensitive ? '' : '-i',\n options.maxCountPerFile !== undefined ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : '',\n options.contextLines ? `-C ${Math.max(0, Math.floor(options.contextLines))}` : '',\n `-e ${shellQuote(options.pattern)}`,\n shellQuote(abs),\n ]\n .filter(Boolean)\n .join(' ');\n const result = await this.exec(args);\n // rg exits 1 when there are no matches, 2 on any error. A bad pattern\n // produces no output at all, but a per-file error (e.g. an unreadable\n // file) also yields exit 2 while still emitting matches for every other\n // file. Keep those partial results; only treat \"error with no matches\"\n // as an unsupported pattern so the caller falls back to the host walk.\n if (result.exitCode === 1) return [];\n const results = this.parseRipgrepJson(result.stdout, abs, options);\n if (result.exitCode !== 0 && results.length === 0) {\n throw new UnsupportedGrepPatternError(options.pattern);\n }\n return results;\n }\n\n private parseRipgrepJson(stdout: string, abs: string, options: FilesystemGrepOptions): FilesystemGrepResult[] {\n interface FileState {\n matches: Array<FilesystemGrepMatch & { lineNumber: number }>;\n linesByNumber: Map<number, string>;\n }\n const files = new Map<string, FileState>();\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n let event: any;\n try {\n event = JSON.parse(line);\n } catch {\n continue;\n }\n if (event.type !== 'match' && event.type !== 'context') continue;\n const filePath: string | undefined = event.data?.path?.text;\n const lineNumber: number | undefined = event.data?.line_number;\n if (!filePath || !lineNumber) continue;\n let state = files.get(filePath);\n if (!state) {\n state = { matches: [], linesByNumber: new Map() };\n files.set(filePath, state);\n }\n const text: string = (event.data?.lines?.text ?? '').replace(/\\r?\\n$/, '');\n state.linesByNumber.set(lineNumber, text);\n if (event.type === 'match') {\n // rg submatch offsets are byte offsets into the line; convert to a\n // UTF-16 (JS string) index for the capability contract.\n const byteStart: number = event.data?.submatches?.[0]?.start ?? 0;\n const column = Buffer.from(text, 'utf8').subarray(0, byteStart).toString('utf8').length;\n state.matches.push({ line: lineNumber, column, text, lineNumber });\n }\n }\n const contextLines = options.contextLines ?? 0;\n const results: FilesystemGrepResult[] = [];\n for (const [filePath, state] of files) {\n if (state.matches.length === 0) continue;\n const rel = posixPath.relative(abs, filePath) || posixPath.basename(filePath);\n const matches: FilesystemGrepMatch[] = state.matches.map(({ lineNumber, ...match }) => {\n if (contextLines <= 0) return match;\n const before: string[] = [];\n for (let n = lineNumber - 1; n >= Math.max(1, lineNumber - contextLines); n--) {\n const t = state.linesByNumber.get(n);\n if (t === undefined) break;\n before.unshift(t);\n }\n const after: string[] = [];\n for (let n = lineNumber + 1; n <= lineNumber + contextLines; n++) {\n const t = state.linesByNumber.get(n);\n if (t === undefined) break;\n after.push(t);\n }\n return { ...match, before, after };\n });\n results.push({ path: rel, matches });\n }\n return this.applyTotalCap(results, options.maxTotalMatches);\n }\n\n /**\n * Patterns whose meaning differs between POSIX ERE and JS RegExp. The grep\n * runs with ERE but match columns are recomputed with JS, so anything that\n * only one side understands (PCRE classes, lookarounds, lazy quantifiers,\n * POSIX bracket classes, GNU word anchors) must fall back to the host walk.\n */\n private static readonly ERE_UNSUPPORTED = /\\\\[dDwWsSbB<>]|\\(\\?|[*+?}]\\?|\\[:[a-z]+:\\]/;\n\n private async grepWithPosixGrep(abs: string, options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n if (SandboxFilesystem.ERE_UNSUPPORTED.test(options.pattern)) {\n throw new UnsupportedGrepPatternError(options.pattern);\n }\n let jsRegex: RegExp;\n try {\n jsRegex = new RegExp(options.pattern, options.caseSensitive ? '' : 'i');\n } catch {\n throw new UnsupportedGrepPatternError(options.pattern);\n }\n // Reconstructing per-match context from `grep -C` text output is not\n // reliable (separator lines are ambiguous); let the host walk handle it.\n if (options.contextLines) {\n throw new UnsupportedGrepPatternError(options.pattern);\n }\n const args = [\n 'grep -rnIE',\n options.caseSensitive ? '' : '-i',\n options.maxCountPerFile !== undefined ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : '',\n '--',\n shellQuote(options.pattern),\n shellQuote(abs),\n ]\n .filter(Boolean)\n .join(' ');\n const result = await this.exec(args);\n if (result.exitCode === 1) return [];\n if (result.exitCode !== 0) {\n throw new UnsupportedGrepPatternError(options.pattern);\n }\n // grep -n has no column output; recompute with the JS regex host-side so\n // columns are UTF-16 indices, consistent with the fallback implementation.\n const byFile = new Map<string, FilesystemGrepMatch[]>();\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const parsed = /^(.*?):(\\d+):(.*)$/.exec(line);\n if (!parsed) continue;\n const rel = posixPath.relative(abs, parsed[1]!) || posixPath.basename(parsed[1]!);\n const text = parsed[3]!;\n const column = jsRegex.exec(text)?.index;\n // grep matched this line but the JS regex did not: the two dialects\n // disagree on this pattern, so the columns would be wrong. Fall back.\n if (column === undefined) throw new UnsupportedGrepPatternError(options.pattern);\n let matches = byFile.get(rel);\n if (!matches) {\n matches = [];\n byFile.set(rel, matches);\n }\n matches.push({ line: Number(parsed[2]), column, text });\n }\n const results = [...byFile.entries()].map(([path, matches]) => ({ path, matches }));\n return this.applyTotalCap(results, options.maxTotalMatches);\n }\n\n private applyTotalCap(results: FilesystemGrepResult[], maxTotal?: number): FilesystemGrepResult[] {\n if (maxTotal === undefined) return results;\n const capped: FilesystemGrepResult[] = [];\n let total = 0;\n for (const file of results) {\n if (total >= maxTotal) break;\n const remaining = maxTotal - total;\n const matches = file.matches.slice(0, remaining);\n total += matches.length;\n capped.push({ path: file.path, matches });\n }\n return capped;\n }\n\n // ── Path / metadata ────────────────────────────────────────────────────\n\n async exists(path: string): Promise<boolean> {\n const abs = await this.resolveAsync(path);\n const result = await this.exec(`test -e ${shellQuote(abs)}`);\n return result.exitCode === 0;\n }\n\n async stat(path: string): Promise<FileStat> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedRealpath(abs, path);\n // GNU stat: %F=type, %s=size, %Y=mtime (epoch seconds), %W=birth (or -1).\n // BSD/macOS stat (local sandbox hosts) rejects `-c`; fall back to its\n // `-f` format with the same field order (%HT=type, %z=size, %m=mtime,\n // %B=birth). Delimit with `|` — neither stat interprets `\\t` escapes in\n // its format string.\n const result = await this.exec(\n `stat -c '%F|%s|%Y|%W' ${shellQuote(abs)} 2>/dev/null || stat -f '%HT|%z|%m|%B' ${shellQuote(abs)}`,\n );\n if (result.exitCode !== 0) {\n throw new FileNotFoundError(path);\n }\n const [kind, sizeStr, mtimeStr, ctimeStr] = result.stdout.trim().split('|');\n const type = kind && kind.toLowerCase().includes('directory') ? 'directory' : 'file';\n const size = Number(sizeStr) || 0;\n const mtime = Number(mtimeStr) || 0;\n const ctime = Number(ctimeStr);\n return {\n name: posixPath.basename(abs),\n path: `/${posixPath.relative(this.basePath, abs)}`,\n type,\n size: type === 'directory' ? 0 : size,\n modifiedAt: new Date(mtime * 1000),\n createdAt: new Date((ctime > 0 ? ctime : mtime) * 1000),\n };\n }\n\n // ── Lifecycle ──────────────────────────────────────────────────────────\n\n async init(): Promise<void> {\n await this.execOk(`mkdir -p ${shellQuote(await this.base())}`, 'init workdir');\n }\n\n async destroy(): Promise<void> {\n // The sandbox lifecycle is owned by the caller; nothing to tear down here.\n }\n\n async isReady(): Promise<boolean> {\n const result = await this.exec(`test -d ${shellQuote(await this.base())}`);\n return result.exitCode === 0;\n }\n\n getInfo(): FilesystemInfo {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n metadata: { basePath: this.basePath, sandboxId: this.sandbox.id },\n };\n }\n\n getInstructions(): string {\n return `Files are stored in a remote sandbox at ${this.basePath}. Use absolute workspace paths like /src/index.ts. All reads, writes and commands run inside the same sandbox.`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+CA,MAAM,iBAAiB;AACvB,MAAM,oBAAoB;AAC1B,MAAM,cAAc;AACpB,MAAM,qBAAqB;;AA+B3B,MAAM,qBAAqB;;AAG3B,SAAS,WAAW,OAAuB;CACzC,OAAO,IAAI,MAAM,QAAQ,MAAM,OAAO,EAAE;AAC1C;AAEA,SAAS,oBAAoB,SAAyC;CACpE,OAAO,OAAO,YAAY;AAC5B;AAEA,SAAS,SAAS,SAA8B;CAC9C,IAAI,oBAAoB,OAAO,GAAG,OAAO,OAAO,KAAK,SAAS,MAAM;CACpE,OAAO,OAAO,KAAK,OAAO;AAC5B;AAEA,IAAa,oBAAb,MAAa,kBAAiD;CAC5D;CACA,OAAgB;CAChB,WAAoB;CACpB,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OAAO,QAAQ;EAC7B,OAAO;GACL,MAAMA,MAAU,SAAS,GAAG;GAC5B,MAAM,IAAIA,MAAU,SAAS,KAAK,UAAU,GAAG;GAC/C;GACA,MAAM,SAAS,cAAc,IAAI;GACjC,4BAAY,IAAI,KAAK,QAAQ,GAAI;GACjC,2BAAW,IAAI,MAAM,QAAQ,IAAI,QAAQ,SAAS,GAAI;EACxD;CACF;CAIA,MAAM,OAAsB;EAC1B,MAAM,KAAK,OAAO,YAAY,WAAW,MAAM,KAAK,KAAK,CAAC,KAAK,cAAc;CAC/E;CAEA,MAAM,UAAyB,CAE/B;CAEA,MAAM,UAA4B;EAEhC,QAAO,MADc,KAAK,KAAK,WAAW,WAAW,MAAM,KAAK,KAAK,CAAC,GAAG,EAAA,CAC3D,aAAa;CAC7B;CAEA,UAA0B;EACxB,OAAO;GACL,IAAI,KAAK;GACT,MAAM,KAAK;GACX,UAAU,KAAK;GACf,QAAQ,KAAK;GACb,UAAU;IAAE,UAAU,KAAK;IAAU,WAAW,KAAK,QAAQ;GAAG;EAClE;CACF;CAEA,kBAA0B;EACxB,OAAO,2CAA2C,KAAK,SAAS;CAClE;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { MastraCompositeStore } from '@mastra/core/storage';
|
|
|
10
10
|
import type { MastraVector } from '@mastra/core/vector';
|
|
11
11
|
import { GithubSignals } from '@mastra/github-signals';
|
|
12
12
|
import { Observability } from '@mastra/observability';
|
|
13
|
+
import type { AgentConnectionsSignalProviderOptions } from './agent-connections/signal-provider.js';
|
|
13
14
|
import { resolveModel } from './agents/model.js';
|
|
14
15
|
import type { PostToolObserver, ToolLike } from './agents/tools.js';
|
|
15
16
|
import { AuthStorage } from './auth/storage.js';
|
|
@@ -111,6 +112,16 @@ export interface MastraCodeConfig {
|
|
|
111
112
|
unixSocketPubSub?: boolean;
|
|
112
113
|
/** Marks the configured PubSub as cross-process-safe, allowing Mastra Code to skip file thread locks. */
|
|
113
114
|
crossProcessPubSub?: boolean;
|
|
115
|
+
/** Agent connection state and discovery options. */
|
|
116
|
+
agentConnections?: AgentConnectionsSignalProviderOptions;
|
|
117
|
+
/**
|
|
118
|
+
* Enable experimental cross-agent communication: thread ownership
|
|
119
|
+
* advertisement, peer discovery, and the agent connection tools. Defaults to
|
|
120
|
+
* the `signals.experimentalCrossAgentSignals` global setting (off). This does
|
|
121
|
+
* not gate the PubSub transport itself — cross-agent communication simply
|
|
122
|
+
* uses the configured PubSub when enabled.
|
|
123
|
+
*/
|
|
124
|
+
crossAgentSignals?: boolean;
|
|
114
125
|
}
|
|
115
126
|
export declare function createAuthStorage(): AuthStorage;
|
|
116
127
|
export declare function createMastraCodeAgentController(config?: MastraCodeConfig): Promise<{
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,KAAK,EACV,eAAe,EACf,qBAAqB,EAErB,mBAAmB,EACnB,uBAAuB,EAEvB,OAAO,EACR,MAAM,+BAA+B,CAAC;AAEvC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGlD,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAS7C,OAAO,KAAK,EAAE,cAAc,EAAa,MAAM,yBAAyB,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAmB,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAE7E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGxD,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAA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AA+B,CAAC,CAAC,CAAC;IAClE,UAAU,EAAE,WAAW,CAAC,qBAAqB,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACjE,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B,CAAC,CA0CD;AAED;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,iCAA2B,CAAC;AACzD,cAAc,0BAA0B,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAE9D;;;;GAIG;AACH,OAAO,EACL,KAAK,EACL,QAAQ,EACR,eAAe,EACf,iBAAiB,EACjB,UAAU,EACV,sBAAsB,EACtB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EACV,YAAY,EACZ,WAAW,EACX,WAAW,EACX,UAAU,EACV,aAAa,EACb,eAAe,EACf,UAAU,EACV,kBAAkB,EAClB,KAAK,EACL,gBAAgB,EAChB,cAAc,GACf,MAAM,qBAAqB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -4,6 +4,8 @@ import { isKimiCodingDeviceId } from "./auth/providers/kimi-coding.js";
|
|
|
4
4
|
import { AuthStorage } from "./auth/storage.js";
|
|
5
5
|
import { setAuthStorage } from "./providers/openai-codex.js";
|
|
6
6
|
import { MASTRA_GATEWAY_PROVIDER, OBSERVABILITY_AUTH_PREFIX, loadSettings, resolveModelDefaults, resolveOmRoleModel, saveSettings } from "./onboarding/settings.js";
|
|
7
|
+
import { createThreadOwnershipManager } from "./agent-connections/ownership.js";
|
|
8
|
+
import { AgentConnectionsSignalProvider } from "./agent-connections/signal-provider.js";
|
|
7
9
|
import { hasCredentialStoreProvider } from "./agents/credential-resolver.js";
|
|
8
10
|
import { getDynamicWorkspace, getGoalJudgeTools } from "./agents/workspace.js";
|
|
9
11
|
import { createGitRefInstructionReader, createGitRefReminderReader, getStaticallyLoadedInstructionPaths } from "./agents/prompts/agent-instructions.js";
|
|
@@ -263,6 +265,7 @@ async function createMastraCodeAgentController(config) {
|
|
|
263
265
|
const signalsPubSub = configuredPubSub ?? (useUnixSocketPubSub ? createSignalsPubSub(project.resourceId) : void 0);
|
|
264
266
|
const crossProcessPubSub = config?.crossProcessPubSub ?? (!configuredPubSub && useUnixSocketPubSub);
|
|
265
267
|
if (crossProcessPubSub && !signalsPubSub) throw new Error("crossProcessPubSub requires a pubsub instance");
|
|
268
|
+
const useCrossAgentSignals = config?.crossAgentSignals ?? globalSettings.signals?.experimentalCrossAgentSignals ?? false;
|
|
266
269
|
const injectedStorage = isInjectedStorageInstance(config?.storage) ? config.storage : void 0;
|
|
267
270
|
const storageConfig = injectedStorage ? void 0 : config?.storage ?? getStorageConfig(project.rootPath, globalSettings.storage, configDir);
|
|
268
271
|
const storageResult = injectedStorage ? {
|
|
@@ -414,12 +417,17 @@ async function createMastraCodeAgentController(config) {
|
|
|
414
417
|
new ProviderHistoryCompat()
|
|
415
418
|
];
|
|
416
419
|
const taskSignalProvider = new TaskSignalProvider();
|
|
420
|
+
const agentConnectionsSignalProvider = useCrossAgentSignals ? new AgentConnectionsSignalProvider(config?.agentConnections) : void 0;
|
|
417
421
|
const NO_PLUGIN_PROCESSORS = {
|
|
418
422
|
input: [],
|
|
419
423
|
output: []
|
|
420
424
|
};
|
|
421
425
|
let pluginProcessorReadWarned = false;
|
|
422
|
-
const pluginSignalLane = pluginManager ? new PluginSignalLane({ reservedProviderIds: [
|
|
426
|
+
const pluginSignalLane = pluginManager ? new PluginSignalLane({ reservedProviderIds: [
|
|
427
|
+
taskSignalProvider.id,
|
|
428
|
+
...agentConnectionsSignalProvider ? [agentConnectionsSignalProvider.id] : [],
|
|
429
|
+
...githubSignals ? [githubSignals.id] : []
|
|
430
|
+
] }) : void 0;
|
|
423
431
|
let unsubscribePluginReload;
|
|
424
432
|
/**
|
|
425
433
|
* Plugin processors are read through a function so that enabling, disabling or
|
|
@@ -454,6 +462,7 @@ async function createMastraCodeAgentController(config) {
|
|
|
454
462
|
hasSubagents: subagents.length > 0
|
|
455
463
|
});
|
|
456
464
|
},
|
|
465
|
+
maxProcessorRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,
|
|
457
466
|
model: (ctx) => getDynamicModel(ctx, config?.settingsPath),
|
|
458
467
|
notifications: { deliveryPolicy: { decide: async (input) => {
|
|
459
468
|
const decision = defaultNotificationDeliveryDecision(input);
|
|
@@ -482,7 +491,11 @@ async function createMastraCodeAgentController(config) {
|
|
|
482
491
|
}
|
|
483
492
|
}
|
|
484
493
|
},
|
|
485
|
-
signals: [
|
|
494
|
+
signals: [
|
|
495
|
+
taskSignalProvider,
|
|
496
|
+
...agentConnectionsSignalProvider ? [agentConnectionsSignalProvider] : [],
|
|
497
|
+
...githubSignals ? [githubSignals] : []
|
|
498
|
+
],
|
|
486
499
|
goal: {
|
|
487
500
|
judge: (ctx) => getGoalJudgeModel(ctx, config?.settingsPath),
|
|
488
501
|
maxRuns: globalSettings.models.goalMaxTurns ?? 50,
|
|
@@ -664,6 +677,43 @@ async function createMastraCodeAgentController(config) {
|
|
|
664
677
|
release: releaseThreadLock
|
|
665
678
|
}
|
|
666
679
|
});
|
|
680
|
+
const sessionPeerCleanup = /* @__PURE__ */ new WeakMap();
|
|
681
|
+
if (useCrossAgentSignals) {
|
|
682
|
+
controller.onSessionCreated(async (session) => {
|
|
683
|
+
const threadOwnership = createThreadOwnershipManager((threadId) => controller.getCurrentAgent(session).claimThreadOwnership({
|
|
684
|
+
threadId,
|
|
685
|
+
resourceId: session.identity.getResourceId(),
|
|
686
|
+
streamOptions: () => session.machinery.buildStreamOptions({}),
|
|
687
|
+
peer: {
|
|
688
|
+
label: `${project.name} (${threadId})`,
|
|
689
|
+
title: project.name
|
|
690
|
+
}
|
|
691
|
+
}));
|
|
692
|
+
const claimThreadOwnership = async (threadId) => {
|
|
693
|
+
try {
|
|
694
|
+
await threadOwnership.claim(threadId);
|
|
695
|
+
} catch (error) {
|
|
696
|
+
console.error(`Failed to claim cross-agent thread ownership for ${threadId}`, error);
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
const unsubscribeSession = session.subscribe((event) => {
|
|
700
|
+
if (event.type === "thread_changed") claimThreadOwnership(event.threadId);
|
|
701
|
+
else if (event.type === "thread_created") claimThreadOwnership(event.thread.id);
|
|
702
|
+
});
|
|
703
|
+
sessionPeerCleanup.set(session, () => {
|
|
704
|
+
unsubscribeSession();
|
|
705
|
+
threadOwnership.close();
|
|
706
|
+
});
|
|
707
|
+
const initialThreadId = session.thread.getId();
|
|
708
|
+
if (initialThreadId) await Promise.race([claimThreadOwnership(initialThreadId), new Promise((resolve) => {
|
|
709
|
+
setTimeout(resolve, 5e3).unref?.();
|
|
710
|
+
})]);
|
|
711
|
+
}, { blocking: true });
|
|
712
|
+
controller.onSessionDeleted((session) => {
|
|
713
|
+
sessionPeerCleanup.get(session)?.();
|
|
714
|
+
sessionPeerCleanup.delete(session);
|
|
715
|
+
});
|
|
716
|
+
}
|
|
667
717
|
pluginRuntimeController = controller;
|
|
668
718
|
if (pluginSignalLane && pluginManager) {
|
|
669
719
|
pluginSignalLane.sync(pluginManager.getPluginSignalProviders());
|