@mastra/factory 0.12.0-alpha.6 → 0.12.0-alpha.8

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.
@@ -1 +1 @@
1
- {"version":3,"file":"session-sandbox.d.ts","sourceRoot":"","sources":["../../src/sandbox/session-sandbox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAChG,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AAG3E;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IACpC,gDAAgD;IAChD,SAAS,EAAE,MAAM,CAAC;IAClB,qEAAqE;IACrE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;;;;;;;;OAWG;IACH,mBAAmB,EAAE,CAAC,MAAM,OAAO,CAAC,gBAAgB,CAAC,CAAC,GAAG,SAAS,CAAC;CACpE;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,MAAM,0BAA0B,GAAG,CAAC,GAAG,EAAE,qBAAqB,KAAK,aAAa,CAAC;AAEvF,mFAAmF;AACnF,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAE5F;;;;;;;;;GASG;AACH,UAAU,mBAAmB;IAC3B,OAAO,EAAE,gBAAgB,CAAC;IAC1B;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAID;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAC/B,SAAS,EAAE,MAAM,EACjB,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,MAAM,gBAAgB,GAChC,mBAAmB,CAQrB;AAED;;;;;;;;GAQG;AACH,wBAAsB,qBAAqB,CACzC,S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js";
1
+ import { deriveLocalWorkdir, deriveRemoteRepoDir, repoDirUnder } from "./workdir.js";
2
2
  //#region src/sandbox/session-sandbox.ts
3
3
  const sessionSandboxes = /* @__PURE__ */ new Map();
4
4
  /**
@@ -31,7 +31,7 @@ function getSessionSandbox(sessionId, repoFullName, construct) {
31
31
  async function resolveSessionWorkdir(sessionId, sandbox, repoFullName) {
32
32
  const entry = sessionSandboxes.get(sessionId);
33
33
  if (entry?.workdir && entry.sandbox === sandbox) return entry.workdir;
34
- const workdir = deriveLocalWorkdir(sandbox, repoFullName) ?? remoteWorkdirFromHome(await probeHome(sandbox), repoFullName);
34
+ const workdir = deriveLocalWorkdir(sandbox, repoFullName) ?? deriveRemoteRepoDir(sandbox, repoFullName) ?? repoDirUnder(await probeHome(sandbox), repoFullName);
35
35
  if (entry && entry.sandbox === sandbox) entry.workdir = workdir;
36
36
  return workdir;
37
37
  }
@@ -1 +1 @@
1
- {"version":3,"file":"session-sandbox.js","names":[],"sources":["../../src/sandbox/session-sandbox.ts"],"sourcesContent":["import type { MastraSandbox, SandboxStartHook, WorkspaceSandbox } from '@mastra/core/workspace';\nimport type { RepositoryAccess } from '../capabilities/version-control.js';\nimport { deriveLocalWorkdir, remoteWorkdirFromHome } from './workdir.js';\n\n/**\n * Everything factory knows about a session's sandbox needs — the whole\n * contract between factory and the deployer's sandbox callback. Factory owns\n * intent; the provider owns resolving `sessionId` to a runnable VM.\n */\nexport interface FactorySandboxContext {\n /** Stable session id — the sandbox identity. */\n sessionId: string;\n /** owner/name of the repository, when the session is repo-backed. */\n repoFullName?: string;\n /**\n * Configured repo setup command, when present. Part of a repo template's\n * identity: a different setup command produces a different template.\n */\n setupCommand?: string;\n /**\n * Resolves the session repository's clone URL and a fresh short-lived\n * credential for it. Providers use it for authenticated work that runs\n * outside the VM — resolving a private repo's head, or cloning it during\n * a template build. The credential is minted per call (installation\n * tokens expire in ~1h); never an org PAT.\n *\n * `undefined` when the session has no repository, which is how a provider\n * knows to build no repo template. The key is always present so that\n * passing the whole context to a provider helper keeps working when this\n * field changes, instead of silently resolving to \"no repository\".\n */\n getRepositoryAccess: (() => Promise<RepositoryAccess>) | undefined;\n}\n\n/**\n * The deploy's sandbox configuration: construct a session's sandbox from\n * intent. The sandbox identity is the session id; the provider must honor\n * id-keyed getOrCreate on `start()` (reconnect/resume an existing VM for the\n * id, create otherwise). Construction must be cheap and side-effect-free —\n * VMs are provisioned on `start()` only. Local sandboxes should root their\n * `workingDirectory` at a per-session directory (e.g.\n * `join(root, ctx.sessionId)`); the repo checks out as a subdirectory of it.\n *\n * Returns a `MastraSandbox`, not the bare `WorkspaceSandbox` interface:\n * factory relies on the base class for the start lifecycle and the runtime\n * env, so providers extend it rather than reimplementing the contract.\n *\n * Factory attaches its own session setup to the returned sandbox, so the\n * callback never has to wire it up. A callback may still pass its own\n * `onStart`; it runs after factory's setup, against a prepared workspace.\n *\n * @example\n * ```typescript\n * sandbox: ({ sessionId }) => new E2BSandbox({ id: sessionId })\n * ```\n */\nexport type MastraFactorySandboxConfig = (ctx: FactorySandboxContext) => MastraSandbox;\n\n/** The session's setup work, run against a started sandbox. Must be idempotent. */\nexport type SessionSetupRun = (sandbox: WorkspaceSandbox, workdir: string) => Promise<void>;\n\n/**\n * Per-process session-id → sandbox instance memo.\n *\n * The provider contract is id-keyed getOrCreate, but provider find-then-create\n * has a real double-create race across independent instances. Memoizing the\n * instance per session makes the base class's per-instance start coalescing\n * apply process-wide per session — the same single-flight scope the fleet's\n * per-binding coalescing provided. Cross-replica races are accepted (the\n * fleet was also per-replica).\n */\ninterface SessionSandboxEntry {\n sandbox: WorkspaceSandbox;\n /**\n * The session's repo checkout root, recorded for passive readers (fs\n * routes, capture, authz). Local sandboxes derive it at construction;\n * remote sandboxes clone into the VM's own home, so it is undefined until\n * `resolveSessionWorkdir` probes the first started VM — passive readers\n * treat an unresolved workdir as \"nothing materialized\".\n */\n workdir?: string;\n}\n\nconst sessionSandboxes = new Map<string, SessionSandboxEntry>();\n\n/**\n * Get the session's memoized sandbox entry, constructing (and memoizing) it on\n * first access. Construction is cheap and side-effect-free by contract; VMs\n * are provisioned on `start()` only. Local sandboxes get their workdir here;\n * remote workdirs are a runtime fact of the VM, resolved on first start.\n */\nexport function getSessionSandbox(\n sessionId: string,\n repoFullName: string,\n construct: () => WorkspaceSandbox,\n): SessionSandboxEntry {\n const existing = sessionSandboxes.get(sessionId);\n if (existing) return existing;\n const sandbox = construct();\n const local = deriveLocalWorkdir(sandbox, repoFullName);\n const entry: SessionSandboxEntry = { sandbox, ...(local ? { workdir: local } : {}) };\n sessionSandboxes.set(sessionId, entry);\n return entry;\n}\n\n/**\n * Resolve (and memoize on the session entry) the session's repo checkout\n * root. Local sandboxes answer synchronously from their configured\n * `workingDirectory`; remote sandboxes clone into the VM's own default cwd,\n * so the first resolution probes it with one `pwd` — the VM tells us where\n * home is, we never invent a path. Calling this against a stopped sandbox\n * lazily starts it (the probe is a command), so passive readers must peek\n * `entry.workdir` instead.\n */\nexport async function resolveSessionWorkdir(\n sessionId: string,\n sandbox: WorkspaceSandbox,\n repoFullName: string,\n): Promise<string> {\n const entry = sessionSandboxes.get(sessionId);\n if (entry?.workdir && entry.sandbox === sandbox) return entry.workdir;\n const workdir =\n deriveLocalWorkdir(sandbox, repoFullName) ?? remoteWorkdirFromHome(await probeHome(sandbox), repoFullName);\n if (entry && entry.sandbox === sandbox) entry.workdir = workdir;\n return workdir;\n}\n\n/** One `pwd` in the VM's default shell cwd — its home dir, by provider convention. */\nasync function probeHome(sandbox: WorkspaceSandbox): Promise<string> {\n if (!sandbox.executeCommand) {\n throw new Error(`Sandbox '${sandbox.id}' cannot resolve its workdir: no executeCommand implementation`);\n }\n const probe = await sandbox.executeCommand('pwd');\n const home = probe.stdout.trim().split('\\n').pop()?.trim() ?? '';\n if (probe.exitCode !== 0 || !home.startsWith('/')) {\n throw new Error(\n `Sandbox '${sandbox.id}' default cwd probe failed (exit ${probe.exitCode}): ${\n probe.stderr.trim() || probe.stdout.trim() || 'empty output'\n }`,\n );\n }\n return home;\n}\n\n/**\n * The session's memoized sandbox (and its workdir) when one was already\n * constructed in this process, else undefined. Never constructs — passive\n * read paths use this so browsing files cannot provision a VM.\n */\nexport function peekSessionSandbox(sessionId: string): SessionSandboxEntry | undefined {\n return sessionSandboxes.get(sessionId);\n}\n\n/** Drop the memoized instance (on stop/destroy/retirement or construction failure). */\nexport function evictSessionSandbox(sessionId: string): void {\n sessionSandboxes.delete(sessionId);\n failedSetupCommands.delete(sessionId);\n}\n\n/** Test-only: reset the process-wide memo between tests. */\nexport function __clearSessionSandboxesForTests(): void {\n sessionSandboxes.clear();\n failedSetupCommands.clear();\n}\n\n/**\n * Setup commands that already failed once for a session. The first failure\n * fails the start loudly — the agent sees the real error in the tool result\n * that triggered it. Recording it lets the next start skip the known-bad\n * command instead of wedging the session behind a permanently failing\n * onStart: clone and checkout still run, and the agent can fix or re-run\n * the setup itself. Keyed by the exact command so an edited setup command\n * runs fresh. In-memory only — a server restart re-runs the (idempotent)\n * setup.\n */\nconst failedSetupCommands = new Map<string, string>();\n\nexport function recordFailedSetupCommand(sessionId: string, command: string): void {\n failedSetupCommands.set(sessionId, command);\n}\n\nexport function hasFailedSetupCommand(sessionId: string, command: string): boolean {\n return failedSetupCommands.get(sessionId) === command;\n}\n\n/**\n * Completion marker for the session setup. Factory owns this end-to-end:\n * the `onStart` hook and the post-start fallback guard the exact same path,\n * so setup never double-runs regardless of which layer executed it. It is a\n * skip cache, not a correctness mechanism — the setup work is idempotent by\n * construction (materialize probes the disk, checkout/setup re-run safely).\n */\nconst SESSION_SETUP_MARKER = '.mastra-factory/bootstrap';\n\nfunction markerShellPath(sandbox: Pick<WorkspaceSandbox, 'provider'>): string {\n // Local sandboxes exec with cwd = the session working directory; remote\n // VMs are one-per-session so $HOME is private to the session.\n return sandbox.provider === 'local' ? `./${SESSION_SETUP_MARKER}` : `$HOME/${SESSION_SETUP_MARKER}`;\n}\n\nasync function markerPresent(sandbox: WorkspaceSandbox, workdir: string): Promise<boolean> {\n // The marker is a skip cache — it sits beside the checkout, not inside it,\n // so it can outlive a removed checkout (e.g. a wiped local session dir or\n // a recovered VM). Trust it only when the checkout it describes exists.\n const probe = await sandbox.executeCommand!(`test -f \"${markerShellPath(sandbox)}\" && test -d \"${workdir}/.git\"`);\n return probe.exitCode === 0;\n}\n\nasync function writeMarker(sandbox: WorkspaceSandbox): Promise<void> {\n // Best-effort: a missing marker only re-runs the idempotent setup later.\n const marker = markerShellPath(sandbox);\n await sandbox.executeCommand!(`mkdir -p \"$(dirname \"${marker}\")\" && touch \"${marker}\"`).catch(() => {});\n}\n\n/**\n * Run the session setup, marker-guarded: skip when the marker exists (unless\n * the VM is known-fresh), otherwise run and write the marker only on\n * success. Setup failures propagate — no marker is written, so the next\n * attempt re-runs.\n */\nasync function runGuardedSetup(\n sandbox: WorkspaceSandbox,\n run: SessionSetupRun,\n { skipMarkerProbe, sessionId, repoFullName }: { skipMarkerProbe: boolean; sessionId: string; repoFullName: string },\n): Promise<void> {\n if (!sandbox.executeCommand) {\n throw new Error(`Sandbox '${sandbox.id}' cannot run the session setup: no executeCommand implementation`);\n }\n // Resolved from the live instance (the hook runs inside `start()`, so the\n // VM is up) and memoized on the session entry for passive readers.\n const workdir = await resolveSessionWorkdir(sessionId, sandbox, repoFullName);\n if (!skipMarkerProbe && (await markerPresent(sandbox, workdir))) return;\n await run(sandbox, workdir);\n await writeMarker(sandbox);\n}\n\n/**\n * Build the session setup hook, which factory attaches to the constructed\n * sandbox with `setOnStart`. Runs inside the sandbox start\n * lifecycle: a fresh VM (`outcome: 'created'`) runs setup with no probe; a\n * reconnect probes the marker first, which re-runs setup after a failed or\n * crash-interrupted attempt. Throwing fails `start()` loudly — core treats\n * onStart errors as fatal.\n */\nexport function createSessionSetupHook(\n run: SessionSetupRun,\n sessionId: string,\n repoFullName: string,\n): SandboxStartHook {\n return async ({ sandbox, outcome }) => {\n await runGuardedSetup(sandbox, run, { skipMarkerProbe: outcome === 'created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box.js","names":[],"sources":["../../src/sandbox/session-sandbox.ts"],"sourcesContent":["import type { MastraSandbox, SandboxStartHook, WorkspaceSandbox } from '@mastra/core/workspace';\nimport type { RepositoryAccess } from '../capabilities/version-control.js';\nimport { deriveLocalWorkdir, deriveRemoteRepoDir, repoDirUnder } from './workdir.js';\n\n/**\n * Everything factory knows about a session's sandbox needs — the whole\n * contract between factory and the deployer's sandbox callback. Factory owns\n * intent; the provider owns resolving `sessionId` to a runnable VM.\n */\nexport interface FactorySandboxContext {\n /** Stable session id — the sandbox identity. */\n sessionId: string;\n /** owner/name of the repository, when the session is repo-backed. */\n repoFullName?: string;\n /**\n * Configured repo setup command, when present. Part of a repo template's\n * identity: a different setup command produces a different template.\n */\n setupCommand?: string;\n /**\n * Resolves the session repository's clone URL and a fresh short-lived\n * credential for it. Providers use it for authenticated work that runs\n * outside the VM — resolving a private repo's head, or cloning it during\n * a template build. The credential is minted per call (installation\n * tokens expire in ~1h); never an org PAT.\n *\n * `undefined` when the session has no repository, which is how a provider\n * knows to build no repo template. The key is always present so that\n * passing the whole context to a provider helper keeps working when this\n * field changes, instead of silently resolving to \"no repository\".\n */\n getRepositoryAccess: (() => Promise<RepositoryAccess>) | undefined;\n}\n\n/**\n * The deploy's sandbox configuration: construct a session's sandbox from\n * intent. The sandbox identity is the session id; the provider must honor\n * id-keyed getOrCreate on `start()` (reconnect/resume an existing VM for the\n * id, create otherwise). Construction must be cheap and side-effect-free —\n * VMs are provisioned on `start()` only. Local sandboxes should root their\n * `workingDirectory` at a per-session directory (e.g.\n * `join(root, ctx.sessionId)`); the repo checks out as a subdirectory of it.\n *\n * Returns a `MastraSandbox`, not the bare `WorkspaceSandbox` interface:\n * factory relies on the base class for the start lifecycle and the runtime\n * env, so providers extend it rather than reimplementing the contract.\n *\n * Factory attaches its own session setup to the returned sandbox, so the\n * callback never has to wire it up. A callback may still pass its own\n * `onStart`; it runs after factory's setup, against a prepared workspace.\n *\n * @example\n * ```typescript\n * sandbox: ({ sessionId }) => new E2BSandbox({ id: sessionId })\n * ```\n */\nexport type MastraFactorySandboxConfig = (ctx: FactorySandboxContext) => MastraSandbox;\n\n/** The session's setup work, run against a started sandbox. Must be idempotent. */\nexport type SessionSetupRun = (sandbox: WorkspaceSandbox, workdir: string) => Promise<void>;\n\n/**\n * Per-process session-id → sandbox instance memo.\n *\n * The provider contract is id-keyed getOrCreate, but provider find-then-create\n * has a real double-create race across independent instances. Memoizing the\n * instance per session makes the base class's per-instance start coalescing\n * apply process-wide per session — the same single-flight scope the fleet's\n * per-binding coalescing provided. Cross-replica races are accepted (the\n * fleet was also per-replica).\n */\ninterface SessionSandboxEntry {\n sandbox: WorkspaceSandbox;\n /**\n * The session's repo checkout root, recorded for passive readers (fs\n * routes, capture, authz). Local sandboxes derive it at construction;\n * remote sandboxes clone into the VM's own home, so it is undefined until\n * `resolveSessionWorkdir` probes the first started VM — passive readers\n * treat an unresolved workdir as \"nothing materialized\".\n */\n workdir?: string;\n}\n\nconst sessionSandboxes = new Map<string, SessionSandboxEntry>();\n\n/**\n * Get the session's memoized sandbox entry, constructing (and memoizing) it on\n * first access. Construction is cheap and side-effect-free by contract; VMs\n * are provisioned on `start()` only. Local sandboxes get their workdir here;\n * remote workdirs are a runtime fact of the VM, resolved on first start.\n */\nexport function getSessionSandbox(\n sessionId: string,\n repoFullName: string,\n construct: () => WorkspaceSandbox,\n): SessionSandboxEntry {\n const existing = sessionSandboxes.get(sessionId);\n if (existing) return existing;\n const sandbox = construct();\n const local = deriveLocalWorkdir(sandbox, repoFullName);\n const entry: SessionSandboxEntry = { sandbox, ...(local ? { workdir: local } : {}) };\n sessionSandboxes.set(sessionId, entry);\n return entry;\n}\n\n/**\n * Resolve (and memoize on the session entry) the session's repo checkout\n * root. Local sandboxes answer synchronously from their configured\n * `workingDirectory`; remote sandboxes clone into the VM's own default cwd,\n * so the first resolution probes it with one `pwd` — the VM tells us where\n * home is, we never invent a path. Calling this against a stopped sandbox\n * lazily starts it (the probe is a command), so passive readers must peek\n * `entry.workdir` instead.\n */\nexport async function resolveSessionWorkdir(\n sessionId: string,\n sandbox: WorkspaceSandbox,\n repoFullName: string,\n): Promise<string> {\n const entry = sessionSandboxes.get(sessionId);\n if (entry?.workdir && entry.sandbox === sandbox) return entry.workdir;\n const workdir =\n deriveLocalWorkdir(sandbox, repoFullName) ??\n deriveRemoteRepoDir(sandbox, repoFullName) ??\n repoDirUnder(await probeHome(sandbox), repoFullName);\n if (entry && entry.sandbox === sandbox) entry.workdir = workdir;\n return workdir;\n}\n\n/** One `pwd` in the VM's default shell cwd — its home dir, by provider convention. */\nasync function probeHome(sandbox: WorkspaceSandbox): Promise<string> {\n if (!sandbox.executeCommand) {\n throw new Error(`Sandbox '${sandbox.id}' cannot resolve its workdir: no executeCommand implementation`);\n }\n const probe = await sandbox.executeCommand('pwd');\n const home = probe.stdout.trim().split('\\n').pop()?.trim() ?? '';\n if (probe.exitCode !== 0 || !home.startsWith('/')) {\n throw new Error(\n `Sandbox '${sandbox.id}' default cwd probe failed (exit ${probe.exitCode}): ${\n probe.stderr.trim() || probe.stdout.trim() || 'empty output'\n }`,\n );\n }\n return home;\n}\n\n/**\n * The session's memoized sandbox (and its workdir) when one was already\n * constructed in this process, else undefined. Never constructs — passive\n * read paths use this so browsing files cannot provision a VM.\n */\nexport function peekSessionSandbox(sessionId: string): SessionSandboxEntry | undefined {\n return sessionSandboxes.get(sessionId);\n}\n\n/** Drop the memoized instance (on stop/destroy/retirement or construction failure). */\nexport function evictSessionSandbox(sessionId: string): void {\n sessionSandboxes.delete(sessionId);\n failedSetupCommands.delete(sessionId);\n}\n\n/** Test-only: reset the process-wide memo between tests. */\nexport function __clearSessionSandboxesForTests(): void {\n sessionSandboxes.clear();\n failedSetupCommands.clear();\n}\n\n/**\n * Setup commands that already failed once for a session. The first failure\n * fails the start loudly — the agent sees the real error in the tool result\n * that triggered it. Recording it lets the next start skip the known-bad\n * command instead of wedging the session behind a permanently failing\n * onStart: clone and checkout still run, and the agent can fix or re-run\n * the setup itself. Keyed by the exact command so an edited setup command\n * runs fresh. In-memory only — a server restart re-runs the (idempotent)\n * setup.\n */\nconst failedSetupCommands = new Map<string, string>();\n\nexport function recordFailedSetupCommand(sessionId: string, command: string): void {\n failedSetupCommands.set(sessionId, command);\n}\n\nexport function hasFailedSetupCommand(sessionId: string, command: string): boolean {\n return failedSetupCommands.get(sessionId) === command;\n}\n\n/**\n * Completion marker for the session setup. Factory owns this end-to-end:\n * the `onStart` hook and the post-start fallback guard the exact same path,\n * so setup never double-runs regardless of which layer executed it. It is a\n * skip cache, not a correctness mechanism — the setup work is idempotent by\n * construction (materialize probes the disk, checkout/setup re-run safely).\n */\nconst SESSION_SETUP_MARKER = '.mastra-factory/bootstrap';\n\nfunction markerShellPath(sandbox: Pick<WorkspaceSandbox, 'provider'>): string {\n // Local sandboxes exec with cwd = the session working directory; remote\n // VMs are one-per-session so $HOME is private to the session.\n return sandbox.provider === 'local' ? `./${SESSION_SETUP_MARKER}` : `$HOME/${SESSION_SETUP_MARKER}`;\n}\n\nasync function markerPresent(sandbox: WorkspaceSandbox, workdir: string): Promise<boolean> {\n // The marker is a skip cache — it sits beside the checkout, not inside it,\n // so it can outlive a removed checkout (e.g. a wiped local session dir or\n // a recovered VM). Trust it only when the checkout it describes exists.\n const probe = await sandbox.executeCommand!(`test -f \"${markerShellPath(sandbox)}\" && test -d \"${workdir}/.git\"`);\n return probe.exitCode === 0;\n}\n\nasync function writeMarker(sandbox: WorkspaceSandbox): Promise<void> {\n // Best-effort: a missing marker only re-runs the idempotent setup later.\n const marker = markerShellPath(sandbox);\n await sandbox.executeCommand!(`mkdir -p \"$(dirname \"${marker}\")\" && touch \"${marker}\"`).catch(() => {});\n}\n\n/**\n * Run the session setup, marker-guarded: skip when the marker exists (unless\n * the VM is known-fresh), otherwise run and write the marker only on\n * success. Setup failures propagate — no marker is written, so the next\n * attempt re-runs.\n */\nasync function runGuardedSetup(\n sandbox: WorkspaceSandbox,\n run: SessionSetupRun,\n { skipMarkerProbe, sessionId, repoFullName }: { skipMarkerProbe: boolean; sessionId: string; repoFullName: string },\n): Promise<void> {\n if (!sandbox.executeCommand) {\n throw new Error(`Sandbox '${sandbox.id}' cannot run the session setup: no executeCommand implementation`);\n }\n // Resolved from the live instance (the hook runs inside `start()`, so the\n // VM is up) and memoized on the session entry for passive readers.\n const workdir = await resolveSessionWorkdir(sessionId, sandbox, repoFullName);\n if (!skipMarkerProbe && (await markerPresent(sandbox, workdir))) return;\n await run(sandbox, workdir);\n await writeMarker(sandbox);\n}\n\n/**\n * Build the session setup hook, which factory attaches to the constructed\n * sandbox with `setOnStart`. Runs inside the sandbox start\n * lifecycle: a fresh VM (`outcome: 'created'`) runs setup with no probe; a\n * reconnect probes the marker first, which re-runs setup after a failed or\n * crash-interrupted attempt. Throwing fails `start()` loudly — core treats\n * onStart errors as fatal.\n */\nexport function createSessionSetupHook(\n run: SessionSetupRun,\n sessionId: string,\n repoFullName: string,\n): SandboxStartHook {\n return async ({ sandbox, outcome }) => {\n await runGuardedSetup(sandbox, run, { skipMarkerProbe: outcome === 'created', sessionId, repoFullName });\n };\n}\n"],"mappings":";;AAmFA,MAAM,mCAAmB,IAAI,IAAiC;;;;;;;AAQ9D,SAAgB,kBACd,WACA,cACA,WACqB;CACrB,MAAM,WAAW,iBAAiB,IAAI,SAAS;CAC/C,IAAI,UAAU,OAAO;CACrB,MAAM,UAAU,UAAU;CAC1B,MAAM,QAAQ,mBAAmB,SAAS,YAAY;CACtD,MAAM,QAA6B;EAAE;EAAS,GAAI,QAAQ,EAAE,SAAS,MAAM,IAAI,CAAC;CAAG;CACnF,iBAAiB,IAAI,WAAW,KAAK;CACrC,OAAO;AACT;;;;;;;;;;AAWA,eAAsB,sBACpB,WACA,SACA,cACiB;CACjB,MAAM,QAAQ,iBAAiB,IAAI,SAAS;CAC5C,IAAI,OAAO,WAAW,MAAM,YAAY,SAAS,OAAO,MAAM;CAC9D,MAAM,UACJ,mBAAmB,SAAS,YAAY,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gB,QAAQ,OAAO,EAAA,CACnG,aAAa;AAC5B;AAEA,eAAe,YAAY,SAA0C;CAEnE,MAAM,SAAS,gBAAgB,OAAO;CACtC,MAAM,QAAQ,eAAgB,wBAAwB,OAAO,gBAAgB,OAAO,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC;AACxG;;;;;;;AAQA,eAAe,gBACb,SACA,KACA,EAAE,iBAAiB,WAAW,gBACf;CACf,IAAI,CAAC,QAAQ,gBACX,MAAM,IAAI,MAAM,YAAY,QAAQ,GAAG,iEAAiE;CAI1G,MAAM,UAAU,MAAM,sBAAsB,WAAW,SAAS,YAAY;CAC5E,IAAI,CAAC,mBAAoB,MAAM,cAAc,SAAS,OAAO,GAAI;CACjE,MAAM,IAAI,SAAS,OAAO;CAC1B,MAAM,YAAY,OAAO;AAC3B;;;;;;;;;AAUA,SAAgB,uBACd,KACA,WACA,cACkB;CAClB,OAAO,OAAO,EAAE,SAAS,cAAc;EACrC,MAAM,gBAAgB,SAAS,KAAK;GAAE,iBAAiB,YAAY;GAAW;GAAW;EAAa,CAAC;CACzG;AACF"}
@@ -23,8 +23,13 @@ export declare function deriveLocalWorkdir(sandbox: {
23
23
  provider: string;
24
24
  workingDirectory?: unknown;
25
25
  }, repoFullName: string): string | undefined;
26
- /** `<home>/<repo>` where a remote VM's default-cwd clone lands. */
27
- export declare function remoteWorkdirFromHome(home: string, repoFullName: string): string;
26
+ /** Derive `<workingDirectory>/<repo>` when a remote sandbox declares an absolute root. */
27
+ export declare function deriveRemoteRepoDir(sandbox: {
28
+ provider: string;
29
+ workingDirectory?: unknown;
30
+ }, repoFullName: string): string | undefined;
31
+ /** Join a parent directory and sanitized repository name. */
32
+ export declare function repoDirUnder(parent: string, repoFullName: string): string;
28
33
  /** Resolve a workdir under `root`, refusing any path that escapes the configured root. */
29
34
  export declare function resolveContainedLocalWorkdir(root: string, ...segments: string[]): string;
30
35
  //# sourceMappingURL=workdir.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"workdir.d.ts","sourceRoot":"","sources":["../../src/sandbox/workdir.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AAEH,+EAA+E;AAC/E,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAGvD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAE,EACzD,YAAY,EAAE,MAAM,GACnB,MAAM,GAAG,SAAS,CAOpB;AAED,qEAAqE;AACrE,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAGhF;AAED,0FAA0F;AAC1F,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,CAKxF"}
1
+ {"version":3,"file":"workdir.d.ts","sourceRoot":"","sources":["../../src/sandbox/workdir.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AAEH,+EAA+E;AAC/E,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAGvD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAE,EACzD,YAAY,EAAE,MAAM,GACnB,MAAM,GAAG,SAAS,CAOpB;AAED,0FAA0F;AAC1F,wBAAgB,mBAAmB,CACjC,OAAO,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAE,EACzD,YAAY,EAAE,MAAM,GACnB,MAAM,GAAG,SAAS,CAMpB;AAED,6DAA6D;AAC7D,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAKzE;AAED,0FAA0F;AAC1F,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,CAKxF"}
@@ -30,10 +30,17 @@ function deriveLocalWorkdir(sandbox, repoFullName) {
30
30
  return resolveContainedLocalWorkdir(wd, sanitizeSegment(name || "repo"));
31
31
  }
32
32
  }
33
- /** `<home>/<repo>` where a remote VM's default-cwd clone lands. */
34
- function remoteWorkdirFromHome(home, repoFullName) {
33
+ /** Derive `<workingDirectory>/<repo>` when a remote sandbox declares an absolute root. */
34
+ function deriveRemoteRepoDir(sandbox, repoFullName) {
35
+ const wd = sandbox.workingDirectory;
36
+ if (sandbox.provider !== "local" && typeof wd === "string" && wd.startsWith("/")) return repoDirUnder(wd, repoFullName);
37
+ }
38
+ /** Join a parent directory and sanitized repository name. */
39
+ function repoDirUnder(parent, repoFullName) {
35
40
  const [, name] = repoFullName.split("/", 2);
36
- return `${home.replace(/\/+$/, "")}/${sanitizeSegment(name || "repo")}`;
41
+ let end = parent.length;
42
+ while (end > 0 && parent[end - 1] === "/") end--;
43
+ return `${parent.slice(0, end)}/${sanitizeSegment(name || "repo")}`;
37
44
  }
38
45
  /** Resolve a workdir under `root`, refusing any path that escapes the configured root. */
39
46
  function resolveContainedLocalWorkdir(root, ...segments) {
@@ -43,6 +50,6 @@ function resolveContainedLocalWorkdir(root, ...segments) {
43
50
  throw new Error(`Refusing to use local sandbox path outside configured root: ${resolved}`);
44
51
  }
45
52
  //#endregion
46
- export { deriveLocalWorkdir, remoteWorkdirFromHome, resolveContainedLocalWorkdir, sanitizeSegment };
53
+ export { deriveLocalWorkdir, deriveRemoteRepoDir, repoDirUnder, resolveContainedLocalWorkdir, sanitizeSegment };
47
54
 
48
55
  //# sourceMappingURL=workdir.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"workdir.js","names":["path"],"sources":["../../src/sandbox/workdir.ts"],"sourcesContent":["import * as path from 'node:path';\n\n/**\n * Session workdir derivation. Workdirs are never persisted or trusted from\n * storage or client input — the stale-workdir class of production bugs came\n * from reading `session.sandboxWorkdir` written under a different provider.\n *\n * Local sandboxes derive their workdir synchronously from the sandbox's own\n * `workingDirectory` (the per-session directory the deploy's callback chose).\n * Remote sandboxes have no invented path: the repo clones into the VM's own\n * default cwd (its home dir), so the workdir is only knowable once a VM is\n * running — resolved lazily by `resolveSessionWorkdir` via a one-time `pwd`\n * probe and memoized on the session entry.\n */\n\n/** Keep each path piece a single safe segment (no separators or traversal). */\nexport function sanitizeSegment(segment: string): string {\n const cleaned = segment.replace(/[^A-Za-z0-9._-]/g, '-').replace(/^\\.+/, '');\n return cleaned || 'repo';\n}\n\n/**\n * Synchronously derivable workdir: local sandboxes expose their host\n * `workingDirectory`; the repo checks out as a contained subdirectory so the\n * setup marker sits beside the clone instead of polluting `git status`\n * inside it. Returns undefined for remote providers, whose workdir is a\n * runtime fact of the VM (`<home>/<repo>`).\n */\nexport function deriveLocalWorkdir(\n sandbox: { provider: string; workingDirectory?: unknown },\n repoFullName: string,\n): string | undefined {\n const wd = sandbox.workingDirectory;\n if (sandbox.provider === 'local' && typeof wd === 'string' && wd.length > 0) {\n const [, name] = repoFullName.split('/', 2);\n return resolveContainedLocalWorkdir(wd, sanitizeSegment(name || 'repo'));\n }\n return undefined;\n}\n\n/** `<home>/<repo>` where a remote VM's default-cwd clone lands. */\nexport function remoteWorkdirFromHome(home: string, repoFullName: string): string {\n const [, name] = repoFullName.split('/', 2);\n return `${home.replace(/\\/+$/, '')}/${sanitizeSegment(name || 'repo')}`;\n}\n\n/** Resolve a workdir under `root`, refusing any path that escapes the configured root. */\nexport function resolveContainedLocalWorkdir(root: string, ...segments: string[]): string {\n const resolvedRoot = path.resolve(root);\n const resolved = path.resolve(resolvedRoot, ...segments);\n if (resolved !== resolvedRoot && resolved.startsWith(`${resolvedRoot}${path.sep}`)) return resolved;\n throw new Error(`Refusing to use local sandbox path outside configured root: ${resolved}`);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,SAAgB,gBAAgB,SAAyB;CAEvD,OADgB,QAAQ,QAAQ,oBAAoB,GAAG,CAAC,CAAC,QAAQ,QAAQ,EAC5D,KAAK;AACpB;;;;;;;;AASA,SAAgB,mBACd,SACA,cACoB;CACpB,MAAM,KAAK,QAAQ;CACnB,IAAI,QAAQ,aAAa,WAAW,OAAO,OAAO,YAAY,GAAG,SAAS,GAAG;EAC3E,MAAM,GAAG,QAAQ,aAAa,MAAM,KAAK,CAAC;EAC1C,OAAO,6BAA6B,IAAI,gBAAgB,QAAQ,MAAM,CAAC;CACzE;AAEF;;AAGA,SAAgB,sBAAsB,MAAc,cAA8B;CAChF,MAAM,GAAG,QAAQ,aAAa,MAAM,KAAK,CAAC;CAC1C,OAAO,GAAG,KAAK,QAAQ,QAAQ,EAAE,EAAE,GAAG,gBAAgB,QAAQ,MAAM;AACtE;;AAGA,SAAgB,6BAA6B,MAAc,GAAG,UAA4B;CACxF,MAAM,eAAeA,OAAK,QAAQ,IAAI;CACtC,MAAM,WAAWA,OAAK,QAAQ,cAAc,GAAG,QAAQ;CACvD,IAAI,aAAa,gBAAgB,SAAS,WAAW,GAAG,eAAeA,OAAK,KAAK,GAAG,OAAO;CAC3F,MAAM,IAAI,MAAM,+DAA+D,UAAU;AAC3F"}
1
+ {"version":3,"file":"workdir.js","names":["path"],"sources":["../../src/sandbox/workdir.ts"],"sourcesContent":["import * as path from 'node:path';\n\n/**\n * Session workdir derivation. Workdirs are never persisted or trusted from\n * storage or client input — the stale-workdir class of production bugs came\n * from reading `session.sandboxWorkdir` written under a different provider.\n *\n * Local sandboxes derive their workdir synchronously from the sandbox's own\n * `workingDirectory` (the per-session directory the deploy's callback chose).\n * Remote sandboxes have no invented path: the repo clones into the VM's own\n * default cwd (its home dir), so the workdir is only knowable once a VM is\n * running — resolved lazily by `resolveSessionWorkdir` via a one-time `pwd`\n * probe and memoized on the session entry.\n */\n\n/** Keep each path piece a single safe segment (no separators or traversal). */\nexport function sanitizeSegment(segment: string): string {\n const cleaned = segment.replace(/[^A-Za-z0-9._-]/g, '-').replace(/^\\.+/, '');\n return cleaned || 'repo';\n}\n\n/**\n * Synchronously derivable workdir: local sandboxes expose their host\n * `workingDirectory`; the repo checks out as a contained subdirectory so the\n * setup marker sits beside the clone instead of polluting `git status`\n * inside it. Returns undefined for remote providers, whose workdir is a\n * runtime fact of the VM (`<home>/<repo>`).\n */\nexport function deriveLocalWorkdir(\n sandbox: { provider: string; workingDirectory?: unknown },\n repoFullName: string,\n): string | undefined {\n const wd = sandbox.workingDirectory;\n if (sandbox.provider === 'local' && typeof wd === 'string' && wd.length > 0) {\n const [, name] = repoFullName.split('/', 2);\n return resolveContainedLocalWorkdir(wd, sanitizeSegment(name || 'repo'));\n }\n return undefined;\n}\n\n/** Derive `<workingDirectory>/<repo>` when a remote sandbox declares an absolute root. */\nexport function deriveRemoteRepoDir(\n sandbox: { provider: string; workingDirectory?: unknown },\n repoFullName: string,\n): string | undefined {\n const wd = sandbox.workingDirectory;\n if (sandbox.provider !== 'local' && typeof wd === 'string' && wd.startsWith('/')) {\n return repoDirUnder(wd, repoFullName);\n }\n return undefined;\n}\n\n/** Join a parent directory and sanitized repository name. */\nexport function repoDirUnder(parent: string, repoFullName: string): string {\n const [, name] = repoFullName.split('/', 2);\n let end = parent.length;\n while (end > 0 && parent[end - 1] === '/') end--;\n return `${parent.slice(0, end)}/${sanitizeSegment(name || 'repo')}`;\n}\n\n/** Resolve a workdir under `root`, refusing any path that escapes the configured root. */\nexport function resolveContainedLocalWorkdir(root: string, ...segments: string[]): string {\n const resolvedRoot = path.resolve(root);\n const resolved = path.resolve(resolvedRoot, ...segments);\n if (resolved !== resolvedRoot && resolved.startsWith(`${resolvedRoot}${path.sep}`)) return resolved;\n throw new Error(`Refusing to use local sandbox path outside configured root: ${resolved}`);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,SAAgB,gBAAgB,SAAyB;CAEvD,OADgB,QAAQ,QAAQ,oBAAoB,GAAG,CAAC,CAAC,QAAQ,QAAQ,EAC5D,KAAK;AACpB;;;;;;;;AASA,SAAgB,mBACd,SACA,cACoB;CACpB,MAAM,KAAK,QAAQ;CACnB,IAAI,QAAQ,aAAa,WAAW,OAAO,OAAO,YAAY,GAAG,SAAS,GAAG;EAC3E,MAAM,GAAG,QAAQ,aAAa,MAAM,KAAK,CAAC;EAC1C,OAAO,6BAA6B,IAAI,gBAAgB,QAAQ,MAAM,CAAC;CACzE;AAEF;;AAGA,SAAgB,oBACd,SACA,cACoB;CACpB,MAAM,KAAK,QAAQ;CACnB,IAAI,QAAQ,aAAa,WAAW,OAAO,OAAO,YAAY,GAAG,WAAW,GAAG,GAC7E,OAAO,aAAa,IAAI,YAAY;AAGxC;;AAGA,SAAgB,aAAa,QAAgB,cAA8B;CACzE,MAAM,GAAG,QAAQ,aAAa,MAAM,KAAK,CAAC;CAC1C,IAAI,MAAM,OAAO;CACjB,OAAO,MAAM,KAAK,OAAO,MAAM,OAAO,KAAK;CAC3C,OAAO,GAAG,OAAO,MAAM,GAAG,GAAG,EAAE,GAAG,gBAAgB,QAAQ,MAAM;AAClE;;AAGA,SAAgB,6BAA6B,MAAc,GAAG,UAA4B;CACxF,MAAM,eAAeA,OAAK,QAAQ,IAAI;CACtC,MAAM,WAAWA,OAAK,QAAQ,cAAc,GAAG,QAAQ;CACvD,IAAI,aAAa,gBAAgB,SAAS,WAAW,GAAG,eAAeA,OAAK,KAAK,GAAG,OAAO;CAC3F,MAAM,IAAI,MAAM,+DAA+D,UAAU;AAC3F"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/factory",
3
- "version": "0.12.0-alpha.6",
3
+ "version": "0.12.0-alpha.8",
4
4
  "description": "Mastra Software Factory module: the server core behind the Mastra Software Factory — storage domains, integrations, and surfaces for agent-powered software delivery",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -52,9 +52,9 @@
52
52
  "zod": "^4.3.6",
53
53
  "@mastra/auth-studio": "1.3.5-alpha.0",
54
54
  "@mastra/auth-workos": "1.6.5-alpha.0",
55
- "@mastra/code-sdk": "1.6.0-alpha.4",
56
- "@mastra/core": "1.64.0-alpha.2",
57
- "@mastra/slack": "1.6.3-alpha.0"
55
+ "@mastra/core": "1.64.0-alpha.4",
56
+ "@mastra/slack": "1.6.3-alpha.0",
57
+ "@mastra/code-sdk": "1.6.0-alpha.6"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@types/node": "22.20.1",
@@ -64,8 +64,8 @@
64
64
  "typescript-eslint": "^8.57.0",
65
65
  "vitest": "4.1.10",
66
66
  "@internal/lint": "0.0.129",
67
- "@mastra/libsql": "1.22.3-alpha.0",
68
67
  "@mastra/pg": "1.22.3-alpha.0",
68
+ "@mastra/libsql": "1.22.3-alpha.0",
69
69
  "@internal/types-builder": "0.0.104"
70
70
  },
71
71
  "engines": {