@mastra/code-sdk 1.15.0-alpha.1 → 1.15.0-alpha.11

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 (112) hide show
  1. package/dist/acp/agent.d.ts.map +1 -1
  2. package/dist/acp/agent.js +1 -1
  3. package/dist/acp/agent.js.map +1 -1
  4. package/dist/acp/event-mapper.d.ts.map +1 -1
  5. package/dist/acp/event-mapper.js +1 -1
  6. package/dist/acp/event-mapper.js.map +1 -1
  7. package/dist/agent-connections/signal-provider.d.ts +1 -1
  8. package/dist/agent-connections/signal-provider.d.ts.map +1 -1
  9. package/dist/agent-connections/signal-provider.js.map +1 -1
  10. package/dist/agent-connections/state-processor.d.ts +2 -2
  11. package/dist/agent-connections/state-processor.d.ts.map +1 -1
  12. package/dist/agent-connections/state-processor.js.map +1 -1
  13. package/dist/agent-connections/thread-state.d.ts +1 -1
  14. package/dist/agent-connections/thread-state.d.ts.map +1 -1
  15. package/dist/agent-connections/thread-state.js.map +1 -1
  16. package/dist/agent-connections/tools.d.ts.map +1 -1
  17. package/dist/agent-connections/tools.js +1 -1
  18. package/dist/agent-connections/tools.js.map +1 -1
  19. package/dist/agents/background-completion.d.ts +15 -2
  20. package/dist/agents/background-completion.d.ts.map +1 -1
  21. package/dist/agents/background-completion.js +19 -2
  22. package/dist/agents/background-completion.js.map +1 -1
  23. package/dist/agents/credential-resolver.d.ts +6 -0
  24. package/dist/agents/credential-resolver.d.ts.map +1 -1
  25. package/dist/agents/credential-resolver.js +13 -4
  26. package/dist/agents/credential-resolver.js.map +1 -1
  27. package/dist/agents/memory.d.ts.map +1 -1
  28. package/dist/agents/memory.js +1 -1
  29. package/dist/agents/memory.js.map +1 -1
  30. package/dist/agents/sandbox-filesystem.d.ts +32 -10
  31. package/dist/agents/sandbox-filesystem.d.ts.map +1 -1
  32. package/dist/agents/sandbox-filesystem.js +208 -66
  33. package/dist/agents/sandbox-filesystem.js.map +1 -1
  34. package/dist/agents/workspace.d.ts.map +1 -1
  35. package/dist/agents/workspace.js +1 -0
  36. package/dist/agents/workspace.js.map +1 -1
  37. package/dist/experimental-agent.d.ts +1 -1
  38. package/dist/experimental-agent.d.ts.map +1 -1
  39. package/dist/experimental-agent.js.map +1 -1
  40. package/dist/factory/client.d.ts +41 -0
  41. package/dist/factory/client.d.ts.map +1 -0
  42. package/dist/factory/client.js +98 -0
  43. package/dist/factory/client.js.map +1 -0
  44. package/dist/factory/remote-controller.d.ts +34 -0
  45. package/dist/factory/remote-controller.d.ts.map +1 -0
  46. package/dist/factory/remote-controller.js +43 -0
  47. package/dist/factory/remote-controller.js.map +1 -0
  48. package/dist/factory/remote-session.d.ts +210 -0
  49. package/dist/factory/remote-session.d.ts.map +1 -0
  50. package/dist/factory/remote-session.js +420 -0
  51. package/dist/factory/remote-session.js.map +1 -0
  52. package/dist/headless/cli.d.ts +7 -0
  53. package/dist/headless/cli.d.ts.map +1 -1
  54. package/dist/headless/cli.js +19 -3
  55. package/dist/headless/cli.js.map +1 -1
  56. package/dist/headless/flags.d.ts.map +1 -1
  57. package/dist/headless/flags.js +2 -1
  58. package/dist/headless/flags.js.map +1 -1
  59. package/dist/headless/format.d.ts +2 -0
  60. package/dist/headless/format.d.ts.map +1 -1
  61. package/dist/headless/format.js +13 -1
  62. package/dist/headless/format.js.map +1 -1
  63. package/dist/headless/run-mc.d.ts.map +1 -1
  64. package/dist/headless/run-mc.js +48 -20
  65. package/dist/headless/run-mc.js.map +1 -1
  66. package/dist/index.d.ts +22 -1
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.js +69 -25
  69. package/dist/index.js.map +1 -1
  70. package/dist/onboarding/pack-activation.d.ts +2 -11
  71. package/dist/onboarding/pack-activation.d.ts.map +1 -1
  72. package/dist/onboarding/pack-activation.js.map +1 -1
  73. package/dist/onboarding/settings.d.ts +18 -0
  74. package/dist/onboarding/settings.d.ts.map +1 -1
  75. package/dist/onboarding/settings.js +28 -3
  76. package/dist/onboarding/settings.js.map +1 -1
  77. package/dist/platform/index.d.ts +74 -0
  78. package/dist/platform/index.d.ts.map +1 -0
  79. package/dist/platform/index.js +200 -0
  80. package/dist/platform/index.js.map +1 -0
  81. package/dist/process-memory-diagnostics.d.ts +2 -1
  82. package/dist/process-memory-diagnostics.d.ts.map +1 -1
  83. package/dist/process-memory-diagnostics.js.map +1 -1
  84. package/dist/providers/model-ids.d.ts +1 -0
  85. package/dist/providers/model-ids.d.ts.map +1 -1
  86. package/dist/providers/model-ids.js +6 -4
  87. package/dist/providers/model-ids.js.map +1 -1
  88. package/dist/tools/web-search.d.ts +1 -1
  89. package/dist/tools/web-search.d.ts.map +1 -1
  90. package/dist/tools/web-search.js.map +1 -1
  91. package/dist/tools/workflows/create-workflow.d.ts.map +1 -1
  92. package/dist/tools/workflows/create-workflow.js +5 -1
  93. package/dist/tools/workflows/create-workflow.js.map +1 -1
  94. package/dist/utils/local-observability.d.ts +19 -0
  95. package/dist/utils/local-observability.d.ts.map +1 -0
  96. package/dist/utils/local-observability.js +57 -0
  97. package/dist/utils/local-observability.js.map +1 -0
  98. package/dist/utils/notification-dispatch.d.ts +27 -12
  99. package/dist/utils/notification-dispatch.d.ts.map +1 -1
  100. package/dist/utils/notification-dispatch.js +46 -24
  101. package/dist/utils/notification-dispatch.js.map +1 -1
  102. package/dist/utils/signals-pubsub.d.ts +5 -3
  103. package/dist/utils/signals-pubsub.d.ts.map +1 -1
  104. package/dist/utils/signals-pubsub.js +8 -6
  105. package/dist/utils/signals-pubsub.js.map +1 -1
  106. package/dist/utils/wake-session.d.ts +44 -0
  107. package/dist/utils/wake-session.d.ts.map +1 -0
  108. package/dist/utils/wake-session.js +86 -0
  109. package/dist/utils/wake-session.js.map +1 -0
  110. package/dist/workflows/register-primitives.js +4 -1
  111. package/dist/workflows/register-primitives.js.map +1 -1
  112. package/package.json +23 -23
@@ -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 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(\n command: string,\n args?: string[],\n options?: { timeout?: number; maxRetainedBytes?: number },\n ): 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 // File reads come back as base64 on stdout and listings/grep are parsed\n // line by line, so dropping the oldest output would corrupt results.\n return this.sandbox.executeCommand('sh', ['-c', script], {\n timeout: COMMAND_TIMEOUT_MS,\n maxRetainedBytes: Infinity,\n });\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;;AAmC3B,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,SAAyB;CAEzB;CACA;CACA;CACA;CAEA,YAAY,SAAmC;EAC7C,KAAK,UAAU,QAAQ;EACvB,KAAK,gBAAgB,QAAQ;EAC7B,IAAI,OAAO,QAAQ,YAAY,UAAU,KAAK,eAAe,QAAQ;EAIrE,KAAK,KACH,QAAQ,OACP,OAAO,QAAQ,YAAY,WACxB,cAAc,QAAQ,QAAQ,GAAG,GAAG,QAAQ,YAC5C,cAAc,QAAQ,QAAQ;CACtC;;CAGA,IAAI,WAAmB;EACrB,OAAO,KAAK,gBAAgB;CAC9B;;CAGA,MAAc,OAAwB;EACpC,IAAI,KAAK,cAAc,OAAO,KAAK;EACnC,MAAM,SAAS,KAAK;EACpB,IAAI,OAAO,WAAW,UAAU,OAAQ,KAAK,eAAe;EAC5D,KAAK,kBAAkB,QAAQ,QAAQ,CAAC,CACrC,KAAK,MAAM,CAAC,CACZ,MAAK,aAAY;GAChB,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,0DAA0D;GACzF,OAAQ,KAAK,eAAe;EAC9B,CAAC,CAAC,CACD,cAAc;G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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(\n command: string,\n args?: string[],\n options?: { timeout?: number; maxRetainedBytes?: number },\n ): 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/**\n * Explain why a native grep command failed so callers can tell a timeout or\n * broken toolchain apart from a pattern the engine cannot express.\n */\nfunction describeGrepFailure(result: SandboxCommandResult): string {\n if (result.exitCode === 124) return `timed out after ${COMMAND_TIMEOUT_MS / 1000}s`;\n const stderrLine = result.stderr\n .split('\\n')\n .map(line => line.trim())\n .find(Boolean);\n const detail = stderrLine ? `: ${stderrLine.length > 200 ? `${stderrLine.slice(0, 200)}…` : stderrLine}` : '';\n return `exit code ${result.exitCode}${detail}`;\n}\n\n/** Single-quote a string for safe POSIX shell interpolation. */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\ninterface SearchTools {\n rg: boolean;\n gnuGrep: boolean;\n git: boolean;\n /** `grep -P` works, and so does `git grep -P` when git is present. */\n pcre: boolean;\n}\n\n/** One command that reports which search tools the sandbox has, one name per line. */\nconst SEARCH_TOOLS_PROBE =\n 'command -v rg >/dev/null 2>&1 && echo rg; ' +\n \"grep --version 2>/dev/null | head -n 1 | grep -q 'GNU grep' && echo gnu-grep; \" +\n \"printf 'a1\\\\n' | grep -qP '\\\\d(?=)' 2>/dev/null && echo grep-pcre; \" +\n 'if command -v git >/dev/null 2>&1; then echo git; ' +\n // git can be built without PCRE; check it on a throwaway repository.\n 'd=$(mktemp -d 2>/dev/null) && { ' +\n \"(cd \\\"$d\\\" && git init -q && printf 'a1\\\\n' >f && git grep -q --untracked -P -e '\\\\d(?=)') >/dev/null 2>&1 && echo git-pcre; \" +\n 'rm -rf \"$d\"; }; fi; true';\n\nfunction isInsideNodeModules(path: string): boolean {\n return path.split('/').includes('node_modules');\n}\n\n/** Lines a grep engine printed for one file: matches plus surrounding context. */\ninterface GrepFileLines {\n matches: FilesystemGrepMatch[];\n linesByNumber: Map<number, string>;\n}\n\nfunction fileLines(files: Map<string, GrepFileLines>, filePath: string): GrepFileLines {\n let state = files.get(filePath);\n if (!state) {\n state = { matches: [], linesByNumber: new Map() };\n files.set(filePath, state);\n }\n return state;\n}\n\n/** Turn per-file lines into results relative to `abs`, attaching before/after context. */\nfunction toGrepResults(files: Map<string, GrepFileLines>, abs: string, contextLines: number): FilesystemGrepResult[] {\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 = state.matches.map(match => {\n if (contextLines <= 0) return match;\n const before: string[] = [];\n for (let n = match.line - 1; n >= Math.max(1, match.line - contextLines); n--) {\n const text = state.linesByNumber.get(n);\n if (text === undefined) break;\n before.unshift(text);\n }\n const after: string[] = [];\n for (let n = match.line + 1; n <= match.line + contextLines; n++) {\n const text = state.linesByNumber.get(n);\n if (text === undefined) break;\n after.push(text);\n }\n return { ...match, before, after };\n });\n results.push({ path: rel, matches });\n }\n return results;\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 // File reads come back as base64 on stdout and listings/grep are parsed\n // line by line, so dropping the oldest output would corrupt results.\n return this.sandbox.executeCommand('sh', ['-c', script], {\n timeout: COMMAND_TIMEOUT_MS,\n maxRetainedBytes: Infinity,\n });\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. `.gitignore` files\n // still come back when the caller applies them.\n const keepGitignore = options?.includeGitignoreFiles ? `! \\\\( -type f -name .gitignore \\\\) ` : '';\n const hiddenPrune = options?.includeHidden ? '' : `\\\\( -name '.*' ${keepGitignore}\\\\) -prune -o `;\n // Skip directories like node_modules entirely instead of listing them\n // only for the caller to filter them out.\n const skipNames = options?.skipDirectoryNames?.filter(Boolean) ?? [];\n const skipPrune = skipNames.length\n ? `\\\\( -type d \\\\( ${skipNames.map(name => `-name ${shellQuote(name)}`).join(' -o ')} \\\\) \\\\) -prune -o `\n : '';\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}${skipPrune}-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, using the best\n * engine the sandbox has: ripgrep, then GNU grep (with git choosing files\n * inside repositories), then POSIX `grep -rnE`. Patterns the grep engines\n * can't express (PCRE-style classes, word boundaries, lookarounds,\n * non-greedy quantifiers) throw {@link UnsupportedGrepPatternError} so\n * callers use their host-side walk.\n *\n * ripgrep and GNU grep apply every `.gitignore` in the tree, relative to the\n * directory that holds it, and skip `node_modules` unless the search path\n * is inside one. Callers still apply their own hidden/glob filtering.\n */\n async grep(options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const abs = await this.resolveAsync(options.path);\n await this.assertContainedRealpath(abs, options.path);\n const tools = await this.searchTools();\n if (tools.rg) return this.grepWithRipgrep(abs, options);\n if (tools.gnuGrep) return this.grepWithGnuGrep(abs, options, tools);\n return this.grepWithPosixGrep(abs, options);\n }\n\n private toolsCheck: Promise<SearchTools> | undefined;\n\n private searchTools(): Promise<SearchTools> {\n const check = (this.toolsCheck ??= this.exec(SEARCH_TOOLS_PROBE).then(result => {\n if (result.exitCode !== 0) throw new Error(`search tool probe exited with ${result.exitCode}`);\n const found = new Set(result.stdout.split('\\n').map(line => line.trim()));\n const git = found.has('git');\n return {\n rg: found.has('rg'),\n gnuGrep: found.has('gnu-grep'),\n git,\n pcre: found.has('grep-pcre') && (!git || found.has('git-pcre')),\n };\n }));\n // Only a successful probe is cached; a failed one (e.g. the sandbox wasn't\n // ready) is retried on the next search instead of pinning the slow path.\n return check.catch(() => {\n if (this.toolsCheck === check) this.toolsCheck = undefined;\n return { rg: false, gnuGrep: false, git: false, pcre: false };\n });\n }\n\n private async grepWithRipgrep(abs: string, options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const args = [\n // --no-require-git applies .gitignore files outside a git checkout too\n // (e.g. a multi-repo root). A path passed explicitly is searched even\n // when ignored, so targeting `dist/` or `node_modules/x` still works.\n 'rg --json --hidden --no-require-git',\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 isInsideNodeModules(abs) ? '' : `-g ${shellQuote('!**/node_modules/**')}`,\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, describeGrepFailure(result));\n }\n return results;\n }\n\n private parseRipgrepJson(stdout: string, abs: string, options: FilesystemGrepOptions): FilesystemGrepResult[] {\n const files = new Map<string, GrepFileLines>();\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 const state = fileLines(files, filePath);\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 });\n }\n }\n return this.applyTotalCap(toGrepResults(files, abs, options.contextLines ?? 0), 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 /**\n * Escapes that `grep -P` (PCRE) and JS RegExp (without the `u` flag) both\n * accept but read differently, e.g. `\\A` is \"start of subject\" in PCRE and\n * a literal `A` in JS, plus POSIX bracket classes. PCRE-only syntax that JS\n * rejects (inline flags, possessive quantifiers, atomic groups) already\n * fails the JS compile below.\n */\n private static readonly PCRE_UNSUPPORTED = /\\\\[AzZGKQEhHvVRXNCpPe]|\\[:[a-z]+:\\]/;\n\n /** Reject patterns grep can't run with the same meaning as JS; return the JS regex used for columns. */\n private static grepRegex(options: FilesystemGrepOptions, pcre = false): RegExp {\n if (\n pcre\n ? SandboxFilesystem.PCRE_UNSUPPORTED.test(options.pattern)\n : SandboxFilesystem.ERE_UNSUPPORTED.test(options.pattern)\n ) {\n throw new UnsupportedGrepPatternError(\n options.pattern,\n pcre ? 'grep -P reads this syntax differently from JavaScript' : 'POSIX ERE cannot express this syntax',\n );\n }\n try {\n return new RegExp(options.pattern, options.caseSensitive ? '' : 'i');\n } catch {\n throw new UnsupportedGrepPatternError(options.pattern, 'invalid regular expression');\n }\n }\n\n /**\n * GNU grep without ripgrep. Inside a git checkout, `git grep` picks the\n * files (tracked plus untracked, every `.gitignore` applied) and GNU grep\n * prints them with context. Outside a checkout (e.g. a multi-repo root),\n * each child repository is searched the same way and plain grep covers the\n * remaining files, skipping `node_modules`. `--null` ends each file name\n * with NUL, so match (`N:`) and context (`N-`) lines parse unambiguously.\n * When grep and git support it, patterns run as PCRE (`-P`), so `\\d`,\n * `\\w`, `\\s`, `\\b`, and lookarounds don't need the host walk.\n */\n private async grepWithGnuGrep(\n abs: string,\n options: FilesystemGrepOptions,\n tools: SearchTools,\n ): Promise<FilesystemGrepResult[]> {\n const hasGit = tools.git;\n const mode = tools.pcre ? '-P' : '-E';\n const jsRegex = SandboxFilesystem.grepRegex(options, tools.pcre);\n const contextLines = Math.max(0, Math.floor(options.contextLines ?? 0));\n const grepFlags = [\n `-HnI${mode.slice(1)} --null`,\n options.caseSensitive ? '' : '-i',\n options.maxCountPerFile !== undefined ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : '',\n contextLines > 0 ? `-C ${contextLines}` : '',\n ]\n .filter(Boolean)\n .join(' ');\n const skipNodeModules = !isInsideNodeModules(abs);\n const nodeModulesPathspec = skipNodeModules ? ` ${shellQuote(':(exclude,glob)**/node_modules/**')}` : '';\n const pruneNames = skipNodeModules ? '-name .git -o -name node_modules' : '-name .git';\n const script = [\n `pat=${shellQuote(options.pattern)}`,\n `root=${shellQuote(abs)}`,\n // xargs exit codes can't tell \"no match\" from \"bad pattern\"; check first.\n `grep ${mode} -e \"$pat\" </dev/null >/dev/null 2>&1`,\n 'if [ $? -eq 2 ]; then echo \"grep: invalid regular expression\" >&2; exit 2; fi',\n 'tmp=$(mktemp -d) || exit 1',\n `trap 'rm -rf \"$tmp\"' EXIT`,\n `search_files() { xargs -0 -r grep ${grepFlags} -e \"$pat\" -- 2>/dev/null; }`,\n // A line starting with NUL names the directory later paths are relative to.\n 'search_repo() {',\n ` git -C \"$1\" grep -l -z -I --untracked ${options.caseSensitive ? '' : '-i '}${mode} -e \"$pat\" -- .${nodeModulesPathspec} >\"$tmp/files\" 2>/dev/null`,\n ' [ $? -gt 1 ] && return 1',\n ` printf '\\\\0%s\\\\n' \"$1\"`,\n ' (cd \"$1\" && search_files) <\"$tmp/files\"',\n '}',\n ...(hasGit\n ? [\n 'if git -C \"$root\" rev-parse --is-inside-work-tree >/dev/null 2>&1 && ! git -C \"$root\" check-ignore -q . 2>/dev/null; then',\n ' search_repo \"$root\" && exit 0',\n 'fi',\n `find \"$root\" -mindepth 1 -maxdepth 3 \\\\( ${skipNodeModules ? '-name node_modules -prune' : '-false'} \\\\) -o \\\\( -name .git -prune -print \\\\) >\"$tmp/repos\" 2>/dev/null`,\n ': >\"$tmp/done\"',\n 'while IFS= read -r g; do',\n ' d=${g%/.git}',\n ' search_repo \"$d\" && printf \\'%s\\\\n\\' \"$d\" >>\"$tmp/done\"',\n 'done <\"$tmp/repos\"',\n 'set --',\n 'while IFS= read -r d; do set -- \"$@\" -o -path \"$d\"; done <\"$tmp/done\"',\n ]\n : ['set --']),\n `printf '\\\\0%s\\\\n' \"$root\"`,\n `find \"$root\" -mindepth 1 \\\\( ${pruneNames} \"$@\" \\\\) -prune -o -type f -print0 2>/dev/null | search_files`,\n 'exit 0',\n ].join('\\n');\n const result = await this.exec(script);\n if (result.exitCode !== 0) {\n throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));\n }\n const files = new Map<string, GrepFileLines>();\n let base = abs;\n for (const line of result.stdout.split('\\n')) {\n if (!line || line === '--') continue;\n if (line.startsWith('\\0')) {\n base = line.slice(1);\n continue;\n }\n const nul = line.indexOf('\\0');\n if (nul <= 0) continue;\n const parsed = /^(\\d+)([:-])(.*)$/s.exec(line.slice(nul + 1));\n if (!parsed) continue;\n const lineNumber = Number(parsed[1]);\n const text = parsed[3]!;\n const state = fileLines(files, posixPath.resolve(base, line.slice(0, nul)));\n state.linesByNumber.set(lineNumber, text);\n if (parsed[2] !== ':') continue;\n const column = jsRegex.exec(text)?.index;\n if (column === undefined) {\n throw new UnsupportedGrepPatternError(options.pattern, 'POSIX ERE and JS RegExp disagree on this pattern');\n }\n state.matches.push({ line: lineNumber, column, text });\n }\n return this.applyTotalCap(toGrepResults(files, abs, contextLines), options.maxTotalMatches);\n }\n\n private async grepWithPosixGrep(abs: string, options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const jsRegex = SandboxFilesystem.grepRegex(options);\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, 'context lines are not supported by POSIX grep');\n }\n const args = [\n 'grep -rnIE',\n // .git is filtered host-side too; skip it so object files are not scanned.\n '--exclude-dir=.git',\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 // Like rg, grep exits 2 on per-file errors (e.g. an unreadable file) while\n // still printing matches for the rest; keep those partial results.\n if (result.exitCode !== 0 && !(result.exitCode === 2 && result.stdout.trim())) {\n throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));\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) {\n throw new UnsupportedGrepPatternError(options.pattern, 'POSIX ERE and JS RegExp disagree on this pattern');\n }\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;;AAmC3B,MAAM,qBAAqB;;;;;AAM3B,SAAS,oBAAoB,QAAsC;CACjE,IAAI,OAAO,aAAa,KAAK,OAAO,mBAAmB,qBAAqB,IAAK;CACjF,MAAM,aAAa,OAAO,OACvB,MAAM,IAAI,CAAC,CACX,KAAI,SAAQ,KAAK,KAAK,CAAC,CAAC,CACxB,KAAK,OAAO;CACf,MAAM,SAAS,aAAa,KAAK,WAAW,SAAS,MAAM,GAAG,WAAW,MAAM,GAAG,GAAG,EAAE,KAAK,eAAe;CAC3G,OAAO,aAAa,OAAO,WAAW;AACxC;;AAGA,SAAS,WAAW,OAAuB;CACzC,OAAO,IAAI,MAAM,QAAQ,MAAM,OAAO,EAAE;AAC1C;;AAWA,MAAM,qBACJ;AASF,SAAS,oBAAoB,MAAuB;CAClD,OAAO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,EAAE,EAAE,MAAM,CAAC;IACX,uFAAuF;IACvF,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,6EAA6E;IAC7E,YAAY,EAAE,CAAC,QAAQ,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC;CACpF;AA2BD,wBAAsB,mBAAmB,CAAC,EACxC,cAAc,EACd,MAAM,EACN,cAAc,EACd,sBAA8B,GAC/B,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,cAAc,CAAC,EAAE,uBAAuB,CAAC;IACzC,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAClC,gEA2EA;AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,EACtC,cAAc,EACd,MAAM,GACP,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAclC"}
@@ -167,6 +167,7 @@ async function getDynamicWorkspace({ requestContext, mastra, skillExtension, bac
167
167
  name: "Mastra Code Workspace",
168
168
  filesystem,
169
169
  sandbox: new LocalSandbox({
170
+ timeout: 3e4,
170
171
  workingDirectory: projectPath,
171
172
  env: buildSandboxEnv()
172
173
  }),
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.js","names":[],"sources":["../../src/agents/workspace.ts"],"sourcesContent":["import fs, { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from '@mastra/core/workspace';\nimport type { LSPConfig, SkillSource } from '@mastra/core/workspace';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { loadSettings, resolveLspSetting } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathWithinRoot } from '../utils/path-security.js';\nimport { getPlansDir } from '../utils/plans.js';\n\nimport { createMastraCodeWorkspaceTools, GOAL_JUDGE_READONLY_TOOLS } from './tool-availability.js';\n\n// =============================================================================\n// Sandbox Environment\n// =============================================================================\n\nfunction buildSandboxEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n // Explicit overrides for non-interactive subprocess execution\n FORCE_COLOR: '1',\n CLICOLOR_FORCE: '1',\n TERM: process.env.TERM || 'xterm-256color',\n CI: 'true',\n NONINTERACTIVE: '1',\n DEBIAN_FRONTEND: 'noninteractive',\n };\n}\n\n// =============================================================================\n// Create Workspace with Skills\n// =============================================================================\n\n// We support multiple skill locations for compatibility:\n// 1. Project-local: <configDir>/skills (project-specific mastracode skills)\n// 2. Project-local: .claude/skills (Claude Code compatible skills)\n// 3. Project-local: .agents/skills (Agent Skills spec compatible)\n// 4. Global: ~/<configDir>/skills (user-wide mastracode skills)\n// 5. Global: ~/.claude/skills (user-wide Claude Code skills)\n// 6. Global: ~/.agents/skills (user-wide Agent Skills spec compatible)\n\n// Mastra's LocalSkillSource.readdir uses Node's Dirent.isDirectory() which\n// returns false for symlinks. Tools like `npx skills add` install skills as\n// symlinks, so we need to resolve them. For each symlinked skill directory,\n// we add the real (resolved) parent path as an additional skill scan path.\nfunction collectSkillPaths(skillsDirs: string[], allowedRoot?: string): string[] {\n const paths: string[] = [];\n const seen = new Set<string>();\n let realAllowedRoot: string | undefined;\n\n if (allowedRoot) {\n try {\n realAllowedRoot = fs.realpathSync(allowedRoot);\n } catch {\n return [];\n }\n }\n\n for (const skillsDir of skillsDirs) {\n const skillsDirExists = fs.existsSync(skillsDir);\n if (skillsDirExists && realAllowedRoot) {\n try {\n const realSkillsDir = fs.realpathSync(skillsDir);\n if (!isPathWithinRoot(realSkillsDir, realAllowedRoot)) continue;\n } catch {\n continue;\n }\n }\n\n const resolved = path.resolve(skillsDir);\n if (!seen.has(resolved)) {\n seen.add(resolved);\n paths.push(skillsDir);\n }\n\n if (!skillsDirExists) continue;\n\n try {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n try {\n const linkPath = path.join(skillsDir, entry.name);\n const realPath = fs.realpathSync(linkPath);\n if (realAllowedRoot && !isPathWithinRoot(realPath, realAllowedRoot)) continue;\n const stat = fs.statSync(realPath);\n if (stat.isDirectory()) {\n const realParent = path.dirname(realPath);\n if (realAllowedRoot && !isPathWithinRoot(realParent, realAllowedRoot)) continue;\n if (!seen.has(realParent)) {\n seen.add(realParent);\n paths.push(realParent);\n }\n }\n } catch {\n continue;\n }\n }\n }\n } catch {\n // Ignore errors during symlink resolution\n }\n }\n\n return paths;\n}\n\n// Build skill paths dynamically based on configDir and projectPath\nexport function buildSkillPaths(\n projectPath: string,\n configDir: string,\n homeDir = os.homedir(),\n pluginSkillPaths: string[] = [],\n): string[] {\n const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, 'skills');\n const claudeLocalSkillsPath = path.join(projectPath, '.claude', 'skills');\n const agentSkillsLocalPath = path.join(projectPath, '.agents', 'skills');\n const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, 'skills');\n const claudeGlobalSkillsPath = path.join(homeDir, '.claude', 'skills');\n const agentSkillsGlobalPath = path.join(homeDir, '.agents', 'skills');\n\n const paths = [\n ...collectSkillPaths([mastraCodeLocalSkillsPath, claudeLocalSkillsPath, agentSkillsLocalPath], projectPath),\n ...collectSkillPaths([mastraCodeGlobalSkillsPath, claudeGlobalSkillsPath, agentSkillsGlobalPath]),\n ...pluginSkillPaths.flatMap(pluginSkillPath => collectSkillPaths([pluginSkillPath], pluginSkillPath)),\n ];\n\n const seenPaths = new Set<string>();\n return paths.filter(skillPath => {\n let resolved: string;\n try {\n resolved = fs.realpathSync(skillPath);\n } catch {\n resolved = path.resolve(skillPath);\n }\n if (seenPaths.has(resolved)) return false;\n seenPaths.add(resolved);\n return true;\n });\n}\n\nexport interface WorkspaceSkillExtension {\n /** Distinguishes extended workspaces from the default resolver cache. */\n id: string;\n /** Additional read-only skill roots prepended to normal project/global skill roots. */\n paths: string[];\n /** Compose the additional roots with the workspace's normal skill source. */\n createSource: (fallback: SkillSource, fallbackSkillRoots: string[]) => SkillSource;\n}\n\n/**\n * Paths the agent is always allowed to access (in addition to the project root\n * and any per-thread sandboxAllowedPaths). The OS temp directory is included\n * so the agent can use it as a scratchpad without requesting access every time.\n */\nconst DEFAULT_ALLOWED_PATHS: string[] = [os.tmpdir(), '/tmp', getPlansDir()].reduce<string[]>((acc, p) => {\n const resolved = path.resolve(p);\n if (!acc.includes(resolved)) acc.push(resolved);\n return acc;\n}, []);\n\nconst WORKSPACE_ID_PREFIX = 'mastra-code-workspace';\n\n/**\n * Detect the project's package runner from lock files.\n * Used as a fallback packageRunner for LSP when no binary is found locally or on PATH.\n */\nfunction detectPackageRunner(projectPath: string): string | undefined {\n if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm dlx';\n if (existsSync(join(projectPath, 'bun.lockb')) || existsSync(join(projectPath, 'bun.lock'))) return 'bunx';\n if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn dlx';\n if (existsSync(join(projectPath, 'package-lock.json'))) return 'npx --yes';\n return 'npx --yes';\n}\n\nexport async function getDynamicWorkspace({\n requestContext,\n mastra,\n skillExtension,\n backgroundToolsEnabled = false,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n backgroundToolsEnabled?: boolean;\n}) {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = ctx?.getState();\n\n const rawProjectPath = state?.projectPath;\n\n if (!rawProjectPath) {\n throw new Error('Project path is required');\n }\n\n const projectPath = path.resolve(rawProjectPath);\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const projectSkillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}${extensionId}`;\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n const allowedPaths = [\n ...projectSkillPaths,\n ...DEFAULT_ALLOWED_PATHS,\n ...sandboxPaths.map((p: string) => path.resolve(p)),\n ];\n\n // All modes share the same workspace tool configuration. Per-mode tool\n // visibility is enforced at LLM-call time via `availableTools` /\n // `activeTools` on the AgentController, not by mutating workspace capabilities.\n const workspaceTools = createMastraCodeWorkspaceTools(backgroundToolsEnabled);\n\n // Reuse existing workspace if already registered (preserves ProcessManager state)\n let existing: Workspace<LocalFilesystem, LocalSandbox> | undefined;\n try {\n existing = mastra?.getWorkspaceById(workspaceId) as Workspace<LocalFilesystem, LocalSandbox>;\n } catch {\n // Not registered yet\n }\n\n if (existing) {\n existing.filesystem.setAllowedPaths(allowedPaths);\n existing.setToolsConfig(workspaceTools);\n return existing;\n }\n\n // LSP is opt-in. When disabled we pass `false` so core skips the dependency\n // check, the LSP manager, and the `lsp_inspect` tool entirely.\n const userLsp = resolveLspSetting(loadSettings().lsp);\n let lspConfig: LSPConfig | false = false;\n if (userLsp !== false) {\n const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), '..');\n lspConfig = {\n maxOpenClients: 4,\n ...userLsp,\n packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath), // Detected runner is the fallback — user's packageRunner always wins\n searchPaths: [mcModulePath, ...(userLsp.searchPaths ?? [])],\n };\n }\n\n // First call for this project — create the workspace\n const filesystem = new LocalFilesystem({\n basePath: projectPath,\n allowedPaths,\n });\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Workspace',\n filesystem,\n sandbox: new LocalSandbox({\n workingDirectory: projectPath,\n env: buildSandboxEnv(),\n }),\n tools: workspaceTools,\n skills: skillPaths,\n ...(skillExtension ? { skillSource: skillExtension.createSource(filesystem, projectSkillPaths) } : {}),\n lsp: lspConfig,\n });\n}\n\n/**\n * Resolver for the agent's `goal.tools` config. Builds the request's workspace\n * (same per-request resolution as the agent's own tools) and returns only the\n * read-only verification subset, remapped to mastracode's tool names (`view`,\n * `search_content`, etc.). Returns `undefined` when no workspace can be resolved\n * (e.g. no project path), keeping the default judge text-only rather than\n * throwing inside the goal step.\n */\nexport async function getGoalJudgeTools({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}): Promise<ToolsInput | undefined> {\n let workspace: Workspace;\n try {\n workspace = await getDynamicWorkspace({ requestContext, mastra });\n } catch {\n return undefined;\n }\n\n const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });\n const readonly: ToolsInput = {};\n for (const name of GOAL_JUDGE_READONLY_TOOLS) {\n if (allTools[name]) readonly[name] = allTools[name];\n }\n return Object.keys(readonly).length > 0 ? readonly : undefined;\n}\n"],"mappings":";;;;;;;;;;;AAsBA,SAAS,kBAAqC;CAC5C,OAAO;EACL,GAAG,QAAQ;EAEX,aAAa;EACb,gBAAgB;EAChB,MAAM,QAAQ,IAAI,QAAQ;EAC1B,IAAI;EACJ,gBAAgB;EAChB,iBAAiB;CACnB;AACF;AAkBA,SAAS,kBAAkB,YAAsB,aAAgC;CAC/E,MAAM,QAAkB,CAAC;CACzB,MAAM,uBAAO,IAAI,IAAY;CAC7B,IAAI;CAEJ,IAAI,aACF,IAAI;EACF,kBAAkB,GAAG,aAAa,WAAW;CAC/C,QAAQ;EACN,OAAO,CAAC;CACV;CAGF,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,kBAAkB,GAAG,WAAW,SAAS;EAC/C,IAAI,mBAAmB,iBACrB,IAAI;GAEF,IAAI,CAAC,iBADiB,GAAG,aAAa,SACJ,GAAG,eAAe,GAAG;EACzD,QAAQ;GACN;EACF;EAGF,MAAM,WAAW,KAA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oB;GAAE;GAAgB;EAAO,CAAC;CAClE,QAAQ;EACN;CACF;CAEA,MAAM,WAAW,MAAM,qBAAqB,WAAW;EAAE;EAAgB;CAAU,CAAC;CACpF,MAAM,WAAuB,CAAC;CAC9B,KAAK,MAAM,QAAQ,2BACjB,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS;CAEhD,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,IAAI,WAAW,KAAA;AACvD"}
1
+ {"version":3,"file":"workspace.js","names":[],"sources":["../../src/agents/workspace.ts"],"sourcesContent":["import fs, { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from '@mastra/core/workspace';\nimport type { LSPConfig, SkillSource } from '@mastra/core/workspace';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { loadSettings, resolveLspSetting } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathWithinRoot } from '../utils/path-security.js';\nimport { getPlansDir } from '../utils/plans.js';\n\nimport { createMastraCodeWorkspaceTools, GOAL_JUDGE_READONLY_TOOLS } from './tool-availability.js';\n\n// =============================================================================\n// Sandbox Environment\n// =============================================================================\n\nfunction buildSandboxEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n // Explicit overrides for non-interactive subprocess execution\n FORCE_COLOR: '1',\n CLICOLOR_FORCE: '1',\n TERM: process.env.TERM || 'xterm-256color',\n CI: 'true',\n NONINTERACTIVE: '1',\n DEBIAN_FRONTEND: 'noninteractive',\n };\n}\n\n// =============================================================================\n// Create Workspace with Skills\n// =============================================================================\n\n// We support multiple skill locations for compatibility:\n// 1. Project-local: <configDir>/skills (project-specific mastracode skills)\n// 2. Project-local: .claude/skills (Claude Code compatible skills)\n// 3. Project-local: .agents/skills (Agent Skills spec compatible)\n// 4. Global: ~/<configDir>/skills (user-wide mastracode skills)\n// 5. Global: ~/.claude/skills (user-wide Claude Code skills)\n// 6. Global: ~/.agents/skills (user-wide Agent Skills spec compatible)\n\n// Mastra's LocalSkillSource.readdir uses Node's Dirent.isDirectory() which\n// returns false for symlinks. Tools like `npx skills add` install skills as\n// symlinks, so we need to resolve them. For each symlinked skill directory,\n// we add the real (resolved) parent path as an additional skill scan path.\nfunction collectSkillPaths(skillsDirs: string[], allowedRoot?: string): string[] {\n const paths: string[] = [];\n const seen = new Set<string>();\n let realAllowedRoot: string | undefined;\n\n if (allowedRoot) {\n try {\n realAllowedRoot = fs.realpathSync(allowedRoot);\n } catch {\n return [];\n }\n }\n\n for (const skillsDir of skillsDirs) {\n const skillsDirExists = fs.existsSync(skillsDir);\n if (skillsDirExists && realAllowedRoot) {\n try {\n const realSkillsDir = fs.realpathSync(skillsDir);\n if (!isPathWithinRoot(realSkillsDir, realAllowedRoot)) continue;\n } catch {\n continue;\n }\n }\n\n const resolved = path.resolve(skillsDir);\n if (!seen.has(resolved)) {\n seen.add(resolved);\n paths.push(skillsDir);\n }\n\n if (!skillsDirExists) continue;\n\n try {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n try {\n const linkPath = path.join(skillsDir, entry.name);\n const realPath = fs.realpathSync(linkPath);\n if (realAllowedRoot && !isPathWithinRoot(realPath, realAllowedRoot)) continue;\n const stat = fs.statSync(realPath);\n if (stat.isDirectory()) {\n const realParent = path.dirname(realPath);\n if (realAllowedRoot && !isPathWithinRoot(realParent, realAllowedRoot)) continue;\n if (!seen.has(realParent)) {\n seen.add(realParent);\n paths.push(realParent);\n }\n }\n } catch {\n continue;\n }\n }\n }\n } catch {\n // Ignore errors during symlink resolution\n }\n }\n\n return paths;\n}\n\n// Build skill paths dynamically based on configDir and projectPath\nexport function buildSkillPaths(\n projectPath: string,\n configDir: string,\n homeDir = os.homedir(),\n pluginSkillPaths: string[] = [],\n): string[] {\n const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, 'skills');\n const claudeLocalSkillsPath = path.join(projectPath, '.claude', 'skills');\n const agentSkillsLocalPath = path.join(projectPath, '.agents', 'skills');\n const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, 'skills');\n const claudeGlobalSkillsPath = path.join(homeDir, '.claude', 'skills');\n const agentSkillsGlobalPath = path.join(homeDir, '.agents', 'skills');\n\n const paths = [\n ...collectSkillPaths([mastraCodeLocalSkillsPath, claudeLocalSkillsPath, agentSkillsLocalPath], projectPath),\n ...collectSkillPaths([mastraCodeGlobalSkillsPath, claudeGlobalSkillsPath, agentSkillsGlobalPath]),\n ...pluginSkillPaths.flatMap(pluginSkillPath => collectSkillPaths([pluginSkillPath], pluginSkillPath)),\n ];\n\n const seenPaths = new Set<string>();\n return paths.filter(skillPath => {\n let resolved: string;\n try {\n resolved = fs.realpathSync(skillPath);\n } catch {\n resolved = path.resolve(skillPath);\n }\n if (seenPaths.has(resolved)) return false;\n seenPaths.add(resolved);\n return true;\n });\n}\n\nexport interface WorkspaceSkillExtension {\n /** Distinguishes extended workspaces from the default resolver cache. */\n id: string;\n /** Additional read-only skill roots prepended to normal project/global skill roots. */\n paths: string[];\n /** Compose the additional roots with the workspace's normal skill source. */\n createSource: (fallback: SkillSource, fallbackSkillRoots: string[]) => SkillSource;\n}\n\n/**\n * Paths the agent is always allowed to access (in addition to the project root\n * and any per-thread sandboxAllowedPaths). The OS temp directory is included\n * so the agent can use it as a scratchpad without requesting access every time.\n */\nconst DEFAULT_ALLOWED_PATHS: string[] = [os.tmpdir(), '/tmp', getPlansDir()].reduce<string[]>((acc, p) => {\n const resolved = path.resolve(p);\n if (!acc.includes(resolved)) acc.push(resolved);\n return acc;\n}, []);\n\nconst WORKSPACE_ID_PREFIX = 'mastra-code-workspace';\n\n/**\n * Detect the project's package runner from lock files.\n * Used as a fallback packageRunner for LSP when no binary is found locally or on PATH.\n */\nfunction detectPackageRunner(projectPath: string): string | undefined {\n if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm dlx';\n if (existsSync(join(projectPath, 'bun.lockb')) || existsSync(join(projectPath, 'bun.lock'))) return 'bunx';\n if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn dlx';\n if (existsSync(join(projectPath, 'package-lock.json'))) return 'npx --yes';\n return 'npx --yes';\n}\n\nexport async function getDynamicWorkspace({\n requestContext,\n mastra,\n skillExtension,\n backgroundToolsEnabled = false,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n backgroundToolsEnabled?: boolean;\n}) {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = ctx?.getState();\n\n const rawProjectPath = state?.projectPath;\n\n if (!rawProjectPath) {\n throw new Error('Project path is required');\n }\n\n const projectPath = path.resolve(rawProjectPath);\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const projectSkillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}${extensionId}`;\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n const allowedPaths = [\n ...projectSkillPaths,\n ...DEFAULT_ALLOWED_PATHS,\n ...sandboxPaths.map((p: string) => path.resolve(p)),\n ];\n\n // All modes share the same workspace tool configuration. Per-mode tool\n // visibility is enforced at LLM-call time via `availableTools` /\n // `activeTools` on the AgentController, not by mutating workspace capabilities.\n const workspaceTools = createMastraCodeWorkspaceTools(backgroundToolsEnabled);\n\n // Reuse existing workspace if already registered (preserves ProcessManager state)\n let existing: Workspace<LocalFilesystem, LocalSandbox> | undefined;\n try {\n existing = mastra?.getWorkspaceById(workspaceId) as Workspace<LocalFilesystem, LocalSandbox>;\n } catch {\n // Not registered yet\n }\n\n if (existing) {\n existing.filesystem.setAllowedPaths(allowedPaths);\n existing.setToolsConfig(workspaceTools);\n return existing;\n }\n\n // LSP is opt-in. When disabled we pass `false` so core skips the dependency\n // check, the LSP manager, and the `lsp_inspect` tool entirely.\n const userLsp = resolveLspSetting(loadSettings().lsp);\n let lspConfig: LSPConfig | false = false;\n if (userLsp !== false) {\n const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), '..');\n lspConfig = {\n maxOpenClients: 4,\n ...userLsp,\n packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath), // Detected runner is the fallback — user's packageRunner always wins\n searchPaths: [mcModulePath, ...(userLsp.searchPaths ?? [])],\n };\n }\n\n // First call for this project — create the workspace\n const filesystem = new LocalFilesystem({\n basePath: projectPath,\n allowedPaths,\n });\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Workspace',\n filesystem,\n sandbox: new LocalSandbox({\n timeout: 30_000,\n workingDirectory: projectPath,\n env: buildSandboxEnv(),\n }),\n tools: workspaceTools,\n skills: skillPaths,\n ...(skillExtension ? { skillSource: skillExtension.createSource(filesystem, projectSkillPaths) } : {}),\n lsp: lspConfig,\n });\n}\n\n/**\n * Resolver for the agent's `goal.tools` config. Builds the request's workspace\n * (same per-request resolution as the agent's own tools) and returns only the\n * read-only verification subset, remapped to mastracode's tool names (`view`,\n * `search_content`, etc.). Returns `undefined` when no workspace can be resolved\n * (e.g. no project path), keeping the default judge text-only rather than\n * throwing inside the goal step.\n */\nexport async function getGoalJudgeTools({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}): Promise<ToolsInput | undefined> {\n let workspace: Workspace;\n try {\n workspace = await getDynamicWorkspace({ requestContext, mastra });\n } catch {\n return undefined;\n }\n\n const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });\n const readonly: ToolsInput = {};\n for (const name of GOAL_JUDGE_READONLY_TOOLS) {\n if (allTools[name]) readonly[name] = allTools[name];\n }\n return Object.keys(readonly).length > 0 ? readonly : undefined;\n}\n"],"mappings":";;;;;;;;;;;AAsBA,SAAS,kBAAqC;CAC5C,OAAO;EACL,GAAG,QAAQ;EAEX,aAAa;EACb,gBAAgB;EAChB,MAAM,QAAQ,IAAI,QAAQ;EAC1B,IAAI;EACJ,gBAAgB;EAChB,iBAAiB;CACnB;AACF;AAkBA,SAAS,kBAAkB,YAAsB,aAAgC;CAC/E,MAAM,QAAkB,CAAC;CACzB,MAAM,uBAAO,IAAI,IAAY;CAC7B,IAAI;CAEJ,IAAI,aACF,IAAI;EACF,kBAAkB,GAAG,aAAa,WAAW;CAC/C,QAAQ;EACN,OAAO,CAAC;CACV;CAGF,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,kBAAkB,GAAG,WAAW,SAAS;EAC/C,IAAI,mBAAmB,iBACrB,IAAI;GAEF,IAAI,CAAC,iBADiB,GAAG,aAAa,SACJ,GAAG,eAAe,GAAG;EACzD,QAAQ;GACN;EACF;EAGF,MAAM,WAAW,KAAK,QAAQ,SAAS;EACvC,IAAI,CAAC,KAAK,IAAI,QAAQ,GAAG;GACvB,KAAK,IAAI,QAAQ;GACjB,MAAM,KAAK,SAAS;EACtB;EAEA,IAAI,CAAC,iBAAiB;EAEtB,IAAI;GACF,MAAM,UAAU,GAAG,YAAY,WAAW,EAAE,eAAe,KAAK,CAAC;GACjE,KAAK,MAAM,SAAS,SAClB,IAAI,MAAM,eAAe,GACvB,IAAI;IACF,MAAM,WAAW,KAAK,KAAK,WAAW,MAAM,IAAI;IAChD,MAAM,WAAW,GAAG,aAAa,QAAQ;IACzC,IAAI,mBAAmB,CAAC,iBAAiB,UAAU,eAAe,GAAG;IAErE,IADa,GAAG,SAAS,QAClB,CAAC,CAAC,YAAY,GAAG;KACtB,MAAM,aAAa,KAAK,QAAQ,QAAQ;KACxC,IAAI,mBAAmB,CAAC,iBAAiB,YAA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,aAAa,CAAC,CAAC,GAAG;CACpD,IAAI,YAA+B;CACnC,IAAI,YAAY,OAAO;EACrB,MAAM,eAAe,KAAK,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC,GAAG,IAAI;EACvE,YAAY;GACV,gBAAgB;GAChB,GAAG;GACH,eAAe,QAAQ,iBAAiB,oBAAoB,WAAW;GACvE,aAAa,CAAC,cAAc,GAAI,QAAQ,eAAe,CAAC,CAAE;EAC5D;CACF;CAGA,MAAM,aAAa,IAAI,gBAAgB;EACrC,UAAU;EACV;CACF,CAAC;CACD,OAAO,IAAI,UAAU;EACnB,IAAI;EACJ,MAAM;EACN;EACA,SAAS,IAAI,aAAa;GACxB,SAAS;GACT,kBAAkB;GAClB,KAAK,gBAAgB;EACvB,CAAC;EACD,OAAO;EACP,QAAQ;EACR,GAAI,iBAAiB,EAAE,aAAa,eAAe,aAAa,YAAY,iBAAiB,EAAE,IAAI,CAAC;EACpG,KAAK;CACP,CAAC;AACH;;;;;;;;;AAUA,eAAsB,kBAAkB,EACtC,gBACA,UAIkC;CAClC,IAAI;CACJ,IAAI;EACF,YAAY,MAAM,oBAAoB;GAAE;GAAgB;EAAO,CAAC;CAClE,QAAQ;EACN;CACF;CAEA,MAAM,WAAW,MAAM,qBAAqB,WAAW;EAAE;EAAgB;CAAU,CAAC;CACpF,MAAM,WAAuB,CAAC;CAC9B,KAAK,MAAM,QAAQ,2BACjB,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS;CAEhD,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,IAAI,WAAW,KAAA;AACvD"}
@@ -1,6 +1,6 @@
1
1
  import type { Agent } from '@mastra/core/agent';
2
2
  import type { Mastra } from '@mastra/core/mastra';
3
- import { type ExperimentalAgent, type GlobalSettings } from './onboarding/settings.js';
3
+ import type { ExperimentalAgent, GlobalSettings } from './onboarding/settings.js';
4
4
  export interface ExperimentalAgentEnvironment {
5
5
  MASTRACODE_EXPERIMENTAL_AGENT?: string;
6
6
  }
@@ -1 +1 @@
1
- {"version":3,"file":"experimental-agent.d.ts","sourceRoot":"","sources":["../src/experimental-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAElD,OAAO,EAAiC,KAAK,iBAAiB,EAAE,KAAK,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAEtH,MAAM,WAAW,4BAA4B;IAC3C,6BAA6B,CAAC,EAAE,MAAM,CAAC;CACxC;AAID,wBAAgB,iCAAiC,CAC/C,GAAG,GAAE,4BAA0C,GAC9C,iBAAiB,GAAG,IAAI,CAK1B;AAED,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,IAAI,CAAC,cAAc,EAAE,mBAAmB,GAAG,gCAAgC,CAAC,EACtF,GAAG,GAAE,4BAA0C,GAC9C,iBAAiB,GAAG,IAAI,CAK1B;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,iBAAiB,GAAG,IAAI,GAAG,KAAK,CAI9F;AAMD,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,KAAK,EACZ,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,MAAM,GAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAmB,GAC/C,IAAI,CAiCN"}
1
+ {"version":3,"file":"experimental-agent.d.ts","sourceRoot":"","sources":["../src/experimental-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGlD,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAElF,MAAM,WAAW,4BAA4B;IAC3C,6BAA6B,CAAC,EAAE,MAAM,CAAC;CACxC;AAID,wBAAgB,iCAAiC,CAC/C,GAAG,GAAE,4BAA0C,GAC9C,iBAAiB,GAAG,IAAI,CAK1B;AAED,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,IAAI,CAAC,cAAc,EAAE,mBAAmB,GAAG,gCAAgC,CAAC,EACtF,GAAG,GAAE,4BAA0C,GAC9C,iBAAiB,GAAG,IAAI,CAK1B;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,iBAAiB,GAAG,IAAI,GAAG,KAAK,CAI9F;AAMD,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,KAAK,EACZ,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,MAAM,GAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAmB,GAC/C,IAAI,CAiCN"}
@@ -1 +1 @@
1
- {"version":3,"file":"experimental-agent.js","names":[],"sources":["../src/experimental-agent.ts"],"sourcesContent":["import type { Agent } from '@mastra/core/agent';\nimport { createDurableAgent, createEventedAgent, isDurableAgent, isEventedAgent } from '@mastra/core/agent/durable';\nimport type { Mastra } from '@mastra/core/mastra';\n\nimport { parseExperimentalAgentSetting, type ExperimentalAgent, type GlobalSettings } from './onboarding/settings.js';\n\nexport interface ExperimentalAgentEnvironment {\n MASTRACODE_EXPERIMENTAL_AGENT?: string;\n}\n\nconst ACCEPTED_VALUES = '\"durable\", \"evented\", or unset';\n\nexport function parseExperimentalAgentEnvironment(\n env: ExperimentalAgentEnvironment = process.env,\n): ExperimentalAgent | null {\n const value = env.MASTRACODE_EXPERIMENTAL_AGENT;\n if (value === undefined || value === '') return null;\n if (value === 'durable' || value === 'evented') return value;\n throw new Error(`Invalid MASTRACODE_EXPERIMENTAL_AGENT value ${JSON.stringify(value)}. Expected ${ACCEPTED_VALUES}.`);\n}\n\nexport function resolveExperimentalAgent(\n settings: Pick<GlobalSettings, 'experimentalAgent' | '_experimentalAgentSettingsPath'>,\n env: ExperimentalAgentEnvironment = process.env,\n): ExperimentalAgent | null {\n const environmentSelection = parseExperimentalAgentEnvironment(env);\n if (environmentSelection) return environmentSelection;\n\n return parseExperimentalAgentSetting(settings.experimentalAgent, settings._experimentalAgentSettingsPath);\n}\n\nexport function wrapExperimentalAgent(agent: Agent, selection: ExperimentalAgent | null): Agent {\n if (selection === 'durable') return createDurableAgent({ agent }) as unknown as Agent;\n if (selection === 'evented') return createEventedAgent({ agent }) as unknown as Agent;\n return agent;\n}\n\ninterface WorkflowBackedAgent extends Agent {\n getWorkflow(): { engineType?: string };\n}\n\nexport function validateExperimentalAgent(\n agent: Agent,\n mastra: Mastra | undefined,\n report: (message: string) => void = console.info,\n): void {\n const selection: ExperimentalAgent | null = isEventedAgent(agent)\n ? 'evented'\n : isDurableAgent(agent)\n ? 'durable'\n : null;\n if (!selection) return;\n\n if (selection === 'evented' && (!mastra || agent.getMastraInstance() !== mastra)) {\n throw new Error(\n 'Experimental agent \"evented\" requires the coding agent to be registered on a Mastra host before startup.',\n );\n }\n\n const workflowsStore = mastra?.getStorage()?.stores?.workflows;\n if (!workflowsStore) {\n throw new Error(`Experimental agent \"${selection}\" requires a configured workflow storage domain.`);\n }\n if (selection === 'evented' && workflowsStore.supportsConcurrentUpdates?.() !== true) {\n throw new Error(\n 'Experimental agent \"evented\" requires workflow storage with atomic concurrent updates (supportsConcurrentUpdates() must return true).',\n );\n }\n\n const engineType = (agent as WorkflowBackedAgent).getWorkflow().engineType;\n const expectedEngine = selection === 'evented' ? 'evented' : 'default';\n if (engineType !== expectedEngine) {\n throw new Error(\n `Experimental agent \"${selection}\" resolved workflow engine ${JSON.stringify(engineType)} instead of \"${expectedEngine}\".`,\n );\n }\n\n report(`Experimental agent: ${selection} (workflow engine: ${engineType})`);\n}\n"],"mappings":";;;AAUA,MAAM,kBAAkB;AAExB,SAAgB,kCACd,MAAoC,QAAQ,KAClB;CAC1B,MAAM,QAAQ,IAAI;CAClB,IAAI,UAAU,KAAA,KAAa,UAAU,IAAI,OAAO;CAChD,IAAI,UAAU,aAAa,UAAU,WAAW,OAAO;CACvD,MAAM,IAAI,MAAM,+CAA+C,KAAK,UAAU,KAAK,EAAE,aAAa,gBAAgB,EAAE;AACtH;AAEA,SAAgB,yBACd,UACA,MAAoC,QAAQ,KAClB;CAC1B,MAAM,uBAAuB,kCAAkC,GAAG;CAClE,IAAI,sBAAsB,OAAO;CAEjC,OAAO,8BAA8B,SAAS,mBAAmB,SAAS,8BAA8B;AAC1G;AAEA,SAAgB,sBAAsB,OAAc,WAA4C;CAC9F,IAAI,cAAc,WAAW,OAAO,mBAAmB,EAAE,MAAM,CAAC;CAChE,IAAI,cAAc,WAAW,OAAO,mBAAmB,EAAE,MAAM,CAAC;CAChE,OAAO;AACT;AAMA,SAAgB,0BACd,OACA,QACA,SAAoC,QAAQ,MACtC;CACN,MAAM,YAAsC,eAAe,KAAK,IAC5D,YACA,eAAe,KAAK,IAClB,YACA;CACN,IAAI,CAAC,WAAW;CAEhB,IAAI,cAAc,cAAc,CAAC,UAAU,MAAM,kBAAkB,MAAM,SACvE,MAAM,IAAI,MACR,4GACF;CAGF,MAAM,iBAAiB,QAAQ,WAAW,CAAC,EAAE,QAAQ;CACrD,IAAI,CAAC,gBACH,MAAM,IAAI,MAAM,uBAAuB,UAAU,iDAAiD;CAEpG,IAAI,cAAc,aAAa,eAAe,4BAA4B,MAAM,MAC9E,MAAM,IAAI,MACR,yIACF;CAGF,MAAM,aAAc,MAA8B,YAAY,CAAC,CAAC;CAChE,MAAM,iBAAiB,cAAc,YAAY,YAAY;CAC7D,IAAI,eAAe,gBACjB,MAAM,IAAI,MACR,uBAAuB,UAAU,6BAA6B,KAAK,UAAU,UAAU,EAAE,eAAe,eAAe,GACzH;CAGF,OAAO,uBAAuB,UAAU,qBAAqB,WAAW,EAAE;AAC5E"}
1
+ {"version":3,"file":"experimental-agent.js","names":[],"sources":["../src/experimental-agent.ts"],"sourcesContent":["import type { Agent } from '@mastra/core/agent';\nimport { createDurableAgent, createEventedAgent, isDurableAgent, isEventedAgent } from '@mastra/core/agent/durable';\nimport type { Mastra } from '@mastra/core/mastra';\n\nimport { parseExperimentalAgentSetting } from './onboarding/settings.js';\nimport type { ExperimentalAgent, GlobalSettings } from './onboarding/settings.js';\n\nexport interface ExperimentalAgentEnvironment {\n MASTRACODE_EXPERIMENTAL_AGENT?: string;\n}\n\nconst ACCEPTED_VALUES = '\"durable\", \"evented\", or unset';\n\nexport function parseExperimentalAgentEnvironment(\n env: ExperimentalAgentEnvironment = process.env,\n): ExperimentalAgent | null {\n const value = env.MASTRACODE_EXPERIMENTAL_AGENT;\n if (value === undefined || value === '') return null;\n if (value === 'durable' || value === 'evented') return value;\n throw new Error(`Invalid MASTRACODE_EXPERIMENTAL_AGENT value ${JSON.stringify(value)}. Expected ${ACCEPTED_VALUES}.`);\n}\n\nexport function resolveExperimentalAgent(\n settings: Pick<GlobalSettings, 'experimentalAgent' | '_experimentalAgentSettingsPath'>,\n env: ExperimentalAgentEnvironment = process.env,\n): ExperimentalAgent | null {\n const environmentSelection = parseExperimentalAgentEnvironment(env);\n if (environmentSelection) return environmentSelection;\n\n return parseExperimentalAgentSetting(settings.experimentalAgent, settings._experimentalAgentSettingsPath);\n}\n\nexport function wrapExperimentalAgent(agent: Agent, selection: ExperimentalAgent | null): Agent {\n if (selection === 'durable') return createDurableAgent({ agent }) as unknown as Agent;\n if (selection === 'evented') return createEventedAgent({ agent }) as unknown as Agent;\n return agent;\n}\n\ninterface WorkflowBackedAgent extends Agent {\n getWorkflow(): { engineType?: string };\n}\n\nexport function validateExperimentalAgent(\n agent: Agent,\n mastra: Mastra | undefined,\n report: (message: string) => void = console.info,\n): void {\n const selection: ExperimentalAgent | null = isEventedAgent(agent)\n ? 'evented'\n : isDurableAgent(agent)\n ? 'durable'\n : null;\n if (!selection) return;\n\n if (selection === 'evented' && (!mastra || agent.getMastraInstance() !== mastra)) {\n throw new Error(\n 'Experimental agent \"evented\" requires the coding agent to be registered on a Mastra host before startup.',\n );\n }\n\n const workflowsStore = mastra?.getStorage()?.stores?.workflows;\n if (!workflowsStore) {\n throw new Error(`Experimental agent \"${selection}\" requires a configured workflow storage domain.`);\n }\n if (selection === 'evented' && workflowsStore.supportsConcurrentUpdates?.() !== true) {\n throw new Error(\n 'Experimental agent \"evented\" requires workflow storage with atomic concurrent updates (supportsConcurrentUpdates() must return true).',\n );\n }\n\n const engineType = (agent as WorkflowBackedAgent).getWorkflow().engineType;\n const expectedEngine = selection === 'evented' ? 'evented' : 'default';\n if (engineType !== expectedEngine) {\n throw new Error(\n `Experimental agent \"${selection}\" resolved workflow engine ${JSON.stringify(engineType)} instead of \"${expectedEngine}\".`,\n );\n }\n\n report(`Experimental agent: ${selection} (workflow engine: ${engineType})`);\n}\n"],"mappings":";;;AAWA,MAAM,kBAAkB;AAExB,SAAgB,kCACd,MAAoC,QAAQ,KAClB;CAC1B,MAAM,QAAQ,IAAI;CAClB,IAAI,UAAU,KAAA,KAAa,UAAU,IAAI,OAAO;CAChD,IAAI,UAAU,aAAa,UAAU,WAAW,OAAO;CACvD,MAAM,IAAI,MAAM,+CAA+C,KAAK,UAAU,KAAK,EAAE,aAAa,gBAAgB,EAAE;AACtH;AAEA,SAAgB,yBACd,UACA,MAAoC,QAAQ,KAClB;CAC1B,MAAM,uBAAuB,kCAAkC,GAAG;CAClE,IAAI,sBAAsB,OAAO;CAEjC,OAAO,8BAA8B,SAAS,mBAAmB,SAAS,8BAA8B;AAC1G;AAEA,SAAgB,sBAAsB,OAAc,WAA4C;CAC9F,IAAI,cAAc,WAAW,OAAO,mBAAmB,EAAE,MAAM,CAAC;CAChE,IAAI,cAAc,WAAW,OAAO,mBAAmB,EAAE,MAAM,CAAC;CAChE,OAAO;AACT;AAMA,SAAgB,0BACd,OACA,QACA,SAAoC,QAAQ,MACtC;CACN,MAAM,YAAsC,eAAe,KAAK,IAC5D,YACA,eAAe,KAAK,IAClB,YACA;CACN,IAAI,CAAC,WAAW;CAEhB,IAAI,cAAc,cAAc,CAAC,UAAU,MAAM,kBAAkB,MAAM,SACvE,MAAM,IAAI,MACR,4GACF;CAGF,MAAM,iBAAiB,QAAQ,WAAW,CAAC,EAAE,QAAQ;CACrD,IAAI,CAAC,gBACH,MAAM,IAAI,MAAM,uBAAuB,UAAU,iDAAiD;CAEpG,IAAI,cAAc,aAAa,eAAe,4BAA4B,MAAM,MAC9E,MAAM,IAAI,MACR,yIACF;CAGF,MAAM,aAAc,MAA8B,YAAY,CAAC,CAAC;CAChE,MAAM,iBAAiB,cAAc,YAAY,YAAY;CAC7D,IAAI,eAAe,gBACjB,MAAM,IAAI,MACR,uBAAuB,UAAU,6BAA6B,KAAK,UAAU,UAAU,EAAE,eAAe,eAAe,GACzH;CAGF,OAAO,uBAAuB,UAAU,qBAAqB,WAAW,EAAE;AAC5E"}
@@ -0,0 +1,41 @@
1
+ import { MastraClient } from '@mastra/client-js';
2
+ import type { PlatformSession } from '../platform/index.js';
3
+ /** The agent controller every Factory serves its coding sessions under. */
4
+ export declare const FACTORY_CONTROLLER_ID = "code";
5
+ export interface FactoryAddress {
6
+ url: string;
7
+ session: PlatformSession;
8
+ }
9
+ export interface FactoryRepository {
10
+ projectRepositoryId: string;
11
+ slug: string;
12
+ branch?: string;
13
+ }
14
+ export interface FactoryProject {
15
+ id: string;
16
+ name: string;
17
+ repositories: FactoryRepository[];
18
+ }
19
+ export interface FactoryUserSession {
20
+ sessionId: string;
21
+ projectRepositoryId: string;
22
+ title?: string;
23
+ branch: string;
24
+ updatedAt: string;
25
+ }
26
+ export declare function factoryHeaders({ session }: FactoryAddress): Record<string, string>;
27
+ /** List the org's Factory projects with their linked repositories. */
28
+ export declare function listFactoryProjects(address: FactoryAddress): Promise<FactoryProject[]>;
29
+ /**
30
+ * Create a Factory user session. Factory assigns the session ID and its
31
+ * `user/session-<id>` branch, cut from the repository's default branch.
32
+ */
33
+ export declare function createFactoryUserSession(address: FactoryAddress, projectRepositoryId: string, title?: string): Promise<FactoryUserSession>;
34
+ /**
35
+ * Platform access tokens expire while a long-lived TUI is open. On a 401,
36
+ * refresh the session and replay the request once with the new token; a
37
+ * rejected request never ran, so the replay cannot duplicate a command.
38
+ */
39
+ export declare function refreshingFetch(address: FactoryAddress, refresh?: () => Promise<PlatformSession | null>, baseFetch?: typeof fetch): typeof fetch;
40
+ export declare function createFactoryClient(address: FactoryAddress): MastraClient;
41
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/factory/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,2EAA2E;AAC3E,eAAO,MAAM,qBAAqB,SAAS,CAAC;AAI5C,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,eAAe,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IAChC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,iBAAiB,EAAE,CAAC;CACnC;AAED,MAAM,WAAW,kBAAkB;IACjC,SAAS,EAAE,MAAM,CAAC;IAClB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,cAAc,CAAC,EAAE,OAAO,EAAE,EAAE,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAElF;AA4BD,sEAAsE;AACtE,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CAwB5F;AAED;;;GAGG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,cAAc,EACvB,mBAAmB,EAAE,MAAM,EAC3B,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,kBAAkB,CAAC,CAO7B;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,cAAc,EACvB,OAAO,GAAE,MAAM,OAAO,CAAC,eAAe,GAAG,IAAI,CAAsB,EACnE,SAAS,GAAE,OAAO,KAAa,GAC9B,OAAO,KAAK,CAsBd;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,cAAc,GAAG,YAAY,CAGzE"}
@@ -0,0 +1,98 @@
1
+ import { getPlatformSession } from "../platform/index.js";
2
+ import { MastraClient } from "@mastra/client-js";
3
+ //#region src/factory/client.ts
4
+ /** The agent controller every Factory serves its coding sessions under. */
5
+ const FACTORY_CONTROLLER_ID = "code";
6
+ const ORGANIZATION_ID_HEADER = "X-Mastra-Organization-Id";
7
+ function factoryHeaders({ session }) {
8
+ return {
9
+ Authorization: `Bearer ${session.token}`,
10
+ [ORGANIZATION_ID_HEADER]: session.orgId
11
+ };
12
+ }
13
+ async function factoryFetch(address, path, init) {
14
+ const res = await refreshingFetch(address)(`${address.url.replace(/\/$/, "")}${path}`, {
15
+ method: init?.method ?? "GET",
16
+ headers: {
17
+ Accept: "application/json",
18
+ ...init?.body !== void 0 ? { "content-type": "application/json" } : {}
19
+ },
20
+ body: init?.body !== void 0 ? JSON.stringify(init.body) : void 0
21
+ });
22
+ if (!res.ok) {
23
+ const body = await res.json().catch(() => ({}));
24
+ throw new Error(`Factory request ${path} failed (${res.status})${body.message || body.error ? `: ${body.message ?? body.error}` : ""}`);
25
+ }
26
+ return await res.json();
27
+ }
28
+ /** List the org's Factory projects with their linked repositories. */
29
+ async function listFactoryProjects(address) {
30
+ const { projects } = await factoryFetch(address, "/web/factory/projects");
31
+ return Promise.all(projects.map(async (project) => {
32
+ const { connections } = await factoryFetch(address, `/web/factory/projects/${encodeURIComponent(project.id)}/source-control-connections`);
33
+ return {
34
+ id: project.id,
35
+ name: project.name,
36
+ repositories: connections.flatMap((connection) => connection.repositories.map((link) => ({
37
+ projectRepositoryId: link.id,
38
+ slug: link.repository?.slug ?? project.name,
39
+ branch: link.branch ?? link.repository?.defaultBranch
40
+ })))
41
+ };
42
+ }));
43
+ }
44
+ /**
45
+ * Create a Factory user session. Factory assigns the session ID and its
46
+ * `user/session-<id>` branch, cut from the repository's default branch.
47
+ */
48
+ async function createFactoryUserSession(address, projectRepositoryId, title) {
49
+ const { session } = await factoryFetch(address, `/web/source-control/projects/${encodeURIComponent(projectRepositoryId)}/sessions`, {
50
+ method: "POST",
51
+ body: title ? { title } : {}
52
+ });
53
+ return {
54
+ ...session,
55
+ title: session.title ?? void 0
56
+ };
57
+ }
58
+ /**
59
+ * Platform access tokens expire while a long-lived TUI is open. On a 401,
60
+ * refresh the session and replay the request once with the new token; a
61
+ * rejected request never ran, so the replay cannot duplicate a command.
62
+ */
63
+ function refreshingFetch(address, refresh = getPlatformSession, baseFetch = fetch) {
64
+ const withAuth = (init) => {
65
+ const headers = new Headers(init?.headers);
66
+ for (const [key, value] of Object.entries(factoryHeaders(address))) headers.set(key, value);
67
+ return {
68
+ ...init,
69
+ headers
70
+ };
71
+ };
72
+ let refreshing;
73
+ return async (input, init) => {
74
+ const sentToken = address.session.token;
75
+ const res = await baseFetch(input, withAuth(init));
76
+ if (res.status !== 401) return res;
77
+ if (address.session.token === sentToken) {
78
+ refreshing ??= refresh().finally(() => {
79
+ refreshing = void 0;
80
+ });
81
+ const session = await refreshing;
82
+ if (!session || session.token === sentToken) return res;
83
+ address.session = session;
84
+ }
85
+ return baseFetch(input, withAuth(init));
86
+ };
87
+ }
88
+ function createFactoryClient(address) {
89
+ return new MastraClient({
90
+ baseUrl: address.url.replace(/\/$/, ""),
91
+ retries: 0,
92
+ fetch: refreshingFetch(address)
93
+ });
94
+ }
95
+ //#endregion
96
+ export { FACTORY_CONTROLLER_ID, createFactoryClient, createFactoryUserSession, factoryHeaders, listFactoryProjects, refreshingFetch };
97
+
98
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../src/factory/client.ts"],"sourcesContent":["import { MastraClient } from '@mastra/client-js';\n\nimport { getPlatformSession } from '../platform/index.js';\nimport type { PlatformSession } from '../platform/index.js';\n\n/** The agent controller every Factory serves its coding sessions under. */\nexport const FACTORY_CONTROLLER_ID = 'code';\n\nconst ORGANIZATION_ID_HEADER = 'X-Mastra-Organization-Id';\n\nexport interface FactoryAddress {\n url: string;\n session: PlatformSession;\n}\n\nexport interface FactoryRepository {\n projectRepositoryId: string;\n slug: string;\n branch?: string;\n}\n\nexport interface FactoryProject {\n id: string;\n name: string;\n repositories: FactoryRepository[];\n}\n\nexport interface FactoryUserSession {\n sessionId: string;\n projectRepositoryId: string;\n title?: string;\n branch: string;\n updatedAt: string;\n}\n\nexport function factoryHeaders({ session }: FactoryAddress): Record<string, string> {\n return { Authorization: `Bearer ${session.token}`, [ORGANIZATION_ID_HEADER]: session.orgId };\n}\n\nasync function factoryFetch<T>(address: FactoryAddress, path: string, init?: { method?: string; body?: unknown }) {\n const res = await refreshingFetch(address)(`${address.url.replace(/\\/$/, '')}${path}`, {\n method: init?.method ?? 'GET',\n headers: {\n Accept: 'application/json',\n ...(init?.body !== undefined ? { 'content-type': 'application/json' } : {}),\n },\n body: init?.body !== undefined ? JSON.stringify(init.body) : undefined,\n });\n if (!res.ok) {\n const body = (await res.json().catch(() => ({}))) as { error?: string; message?: string };\n throw new Error(\n `Factory request ${path} failed (${res.status})${body.message || body.error ? `: ${body.message ?? body.error}` : ''}`,\n );\n }\n return (await res.json()) as T;\n}\n\ninterface ProjectConnectionPayload {\n repositories: Array<{\n id: string;\n branch: string | null;\n repository: { slug: string; defaultBranch: string } | null;\n }>;\n}\n\n/** List the org's Factory projects with their linked repositories. */\nexport async function listFactoryProjects(address: FactoryAddress): Promise<FactoryProject[]> {\n const { projects } = await factoryFetch<{ projects: Array<{ id: string; name: string }> }>(\n address,\n '/web/factory/projects',\n );\n return Promise.all(\n projects.map(async project => {\n const { connections } = await factoryFetch<{ connections: ProjectConnectionPayload[] }>(\n address,\n `/web/factory/projects/${encodeURIComponent(project.id)}/source-control-connections`,\n );\n return {\n id: project.id,\n name: project.name,\n repositories: connections.flatMap(connection =>\n connection.repositories.map(link => ({\n projectRepositoryId: link.id,\n slug: link.repository?.slug ?? project.name,\n branch: link.branch ?? link.repository?.defaultBranch,\n })),\n ),\n };\n }),\n );\n}\n\n/**\n * Create a Factory user session. Factory assigns the session ID and its\n * `user/session-<id>` branch, cut from the repository's default branch.\n */\nexport async function createFactoryUserSession(\n address: FactoryAddress,\n projectRepositoryId: string,\n title?: string,\n): Promise<FactoryUserSession> {\n const { session } = await factoryFetch<{ session: FactoryUserSession & { title?: string | null } }>(\n address,\n `/web/source-control/projects/${encodeURIComponent(projectRepositoryId)}/sessions`,\n { method: 'POST', body: title ? { title } : {} },\n );\n return { ...session, title: session.title ?? undefined };\n}\n\n/**\n * Platform access tokens expire while a long-lived TUI is open. On a 401,\n * refresh the session and replay the request once with the new token; a\n * rejected request never ran, so the replay cannot duplicate a command.\n */\nexport function refreshingFetch(\n address: FactoryAddress,\n refresh: () => Promise<PlatformSession | null> = getPlatformSession,\n baseFetch: typeof fetch = fetch,\n): typeof fetch {\n const withAuth = (init: RequestInit | undefined) => {\n const headers = new Headers(init?.headers);\n for (const [key, value] of Object.entries(factoryHeaders(address))) headers.set(key, value);\n return { ...init, headers };\n };\n // Concurrent 401s share one refresh so the token is not rotated repeatedly.\n let refreshing: Promise<PlatformSession | null> | undefined;\n return async (input, init) => {\n const sentToken = address.session.token;\n const res = await baseFetch(input, withAuth(init));\n if (res.status !== 401) return res;\n if (address.session.token === sentToken) {\n refreshing ??= refresh().finally(() => {\n refreshing = undefined;\n });\n const session = await refreshing;\n if (!session || session.token === sentToken) return res;\n address.session = session;\n }\n return baseFetch(input, withAuth(init));\n };\n}\n\nexport function createFactoryClient(address: FactoryAddress): MastraClient {\n // Session commands are not idempotent; a silent retry would duplicate messages.\n return new MastraClient({ baseUrl: address.url.replace(/\\/$/, ''), retries: 0, fetch: refreshingFetch(address) });\n}\n"],"mappings":";;;;AAMA,MAAa,wBAAwB;AAErC,MAAM,yBAAyB;AA2B/B,SAAgB,eAAe,EAAE,WAAmD;CAClF,OAAO;EAAE,eAAe,UAAU,QAAQ;GAAU,yBAAyB,QAAQ;CAAM;AAC7F;AAEA,eAAe,aAAgB,SAAyB,MAAc,MAA4C;CAChH,MAAM,MAAM,MAAM,gBAAgB,OAAO,CAAC,CAAC,GAAG,QAAQ,IAAI,QAAQ,OAAO,EAAE,IAAI,QAAQ;EACrF,QAAQ,MAAM,UAAU;EACxB,SAAS;GACP,QAAQ;GACR,GAAI,MAAM,SAAS,KAAA,IAAY,EAAE,gBAAgB,mBAAmB,IAAI,CAAC;EAC3E;EACA,MAAM,MAAM,SAAS,KAAA,IAAY,KAAK,UAAU,KAAK,IAAI,IAAI,KAAA;CAC/D,CAAC;CACD,IAAI,CAAC,IAAI,IAAI;EACX,MAAM,OAAQ,MAAM,IAAI,KAAK,CAAC,CAAC,aAAa,CAAC,EAAE;EAC/C,MAAM,IAAI,MACR,mBAAmB,KAAK,WAAW,IAAI,OAAO,GAAG,KAAK,WAAW,KAAK,QAAQ,KAAK,KAAK,WAAW,KAAK,UAAU,IACpH;CACF;CACA,OAAQ,MAAM,IAAI,KAAK;AACzB;;AAWA,eAAsB,oBAAoB,SAAoD;CAC5F,MAAM,EAAE,aAAa,MAAM,aACzB,SACA,uBACF;CACA,OAAO,QAAQ,IACb,SAAS,IAAI,OAAM,YAAW;EAC5B,MAAM,EAAE,gBAAgB,MAAM,aAC5B,SACA,yBAAyB,mBAAmB,QAAQ,EAAE,EAAE,4BAC1D;EACA,OAAO;GACL,IAAI,QAAQ;GACZ,MAAM,QAAQ;GACd,cAAc,YAAY,SAAQ,eAChC,WAAW,aAAa,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