@mastra/factory 0.21.1-alpha.3 → 0.22.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/capabilities/version-control.d.ts +13 -8
- package/dist/capabilities/version-control.d.ts.map +1 -1
- package/dist/environment/build-runner.d.ts +72 -0
- package/dist/environment/build-runner.d.ts.map +1 -0
- package/dist/environment/build-runner.js +131 -0
- package/dist/environment/build-runner.js.map +1 -0
- package/dist/environment/build-schedule.d.ts +40 -0
- package/dist/environment/build-schedule.d.ts.map +1 -0
- package/dist/environment/build-schedule.js +94 -0
- package/dist/environment/build-schedule.js.map +1 -0
- package/dist/environment/build-workflow.d.ts +62 -0
- package/dist/environment/build-workflow.d.ts.map +1 -0
- package/dist/environment/build-workflow.js +149 -0
- package/dist/environment/build-workflow.js.map +1 -0
- package/dist/environment/build.d.ts +111 -0
- package/dist/environment/build.d.ts.map +1 -0
- package/dist/environment/build.js +344 -0
- package/dist/environment/build.js.map +1 -0
- package/dist/environment/heads.d.ts +36 -0
- package/dist/environment/heads.d.ts.map +1 -0
- package/dist/environment/heads.js +60 -0
- package/dist/environment/heads.js.map +1 -0
- package/dist/factory.d.ts +18 -4
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +89 -15
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/integrations/base.d.ts +17 -2
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/github/commits.d.ts +11 -0
- package/dist/integrations/github/commits.d.ts.map +1 -1
- package/dist/integrations/github/commits.js +20 -1
- package/dist/integrations/github/commits.js.map +1 -1
- package/dist/integrations/github/config.d.ts +3 -3
- package/dist/integrations/github/config.d.ts.map +1 -1
- package/dist/integrations/github/config.js +1 -1
- package/dist/integrations/github/config.js.map +1 -1
- package/dist/integrations/github/routes.d.ts +2 -2
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +6 -5
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +3 -1
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +31 -1
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts +35 -0
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +203 -2
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/github/session-subscriptions.d.ts.map +1 -1
- package/dist/integrations/github/session-subscriptions.js +117 -62
- package/dist/integrations/github/session-subscriptions.js.map +1 -1
- package/dist/integrations/github/token-refresh.d.ts +7 -0
- package/dist/integrations/github/token-refresh.d.ts.map +1 -1
- package/dist/integrations/github/token-refresh.js.map +1 -1
- package/dist/integrations/github/webhook.js.map +1 -1
- package/dist/integrations/gitlab/agent-tools.js +1 -1
- package/dist/integrations/gitlab/routes.d.ts +2 -2
- package/dist/integrations/gitlab/routes.d.ts.map +1 -1
- package/dist/integrations/gitlab/routes.js.map +1 -1
- package/dist/integrations/gitlab/session-subscriptions.d.ts.map +1 -1
- package/dist/integrations/gitlab/session-subscriptions.js +8 -7
- package/dist/integrations/gitlab/session-subscriptions.js.map +1 -1
- package/dist/integrations/incidentio/agent-tools.js +1 -1
- package/dist/integrations/jira/agent-tools.js +1 -1
- package/dist/integrations/linear/agent-tools.js +1 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +46 -2
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/jira/agent-tools.js +1 -1
- package/dist/integrations/slack/slack.d.ts.map +1 -1
- package/dist/integrations/slack/slack.js +15 -16
- package/dist/integrations/slack/slack.js.map +1 -1
- package/dist/integrations/subscription-session.js +1 -1
- package/dist/packages/_internals/workspace/dist/index.js +21 -1
- package/dist/packages/_internals/workspace/dist/index.js.map +1 -1
- package/dist/routes/contracts.d.ts +386 -2
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +166 -1
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/fs.d.ts +25 -0
- package/dist/routes/fs.d.ts.map +1 -1
- package/dist/routes/fs.js +142 -46
- package/dist/routes/fs.js.map +1 -1
- package/dist/routes/projects.d.ts +6 -0
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +344 -1
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/source-control-sessions.d.ts +2 -0
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +36 -1
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/supervisor.js +1 -1
- package/dist/routes/surface.d.ts +6 -3
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +21 -34
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/binding-context.d.ts +1 -1
- package/dist/rules/binding-context.d.ts.map +1 -1
- package/dist/rules/binding-context.js +1 -1
- package/dist/rules/binding-context.js.map +1 -1
- package/dist/rules/review-source-tool.js +1 -1
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +7 -2
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/tools.js +1 -1
- package/dist/sandbox/callback-factory-sandbox.d.ts +15 -0
- package/dist/sandbox/callback-factory-sandbox.d.ts.map +1 -0
- package/dist/sandbox/callback-factory-sandbox.js +22 -0
- package/dist/sandbox/callback-factory-sandbox.js.map +1 -0
- package/dist/sandbox/local-factory-sandbox.d.ts +20 -0
- package/dist/sandbox/local-factory-sandbox.d.ts.map +1 -0
- package/dist/sandbox/local-factory-sandbox.js +27 -0
- package/dist/sandbox/local-factory-sandbox.js.map +1 -0
- package/dist/sandbox/session-retirement.d.ts.map +1 -1
- package/dist/sandbox/session-retirement.js +23 -3
- package/dist/sandbox/session-retirement.js.map +1 -1
- package/dist/sandbox/session-sandbox.d.ts +82 -40
- package/dist/sandbox/session-sandbox.d.ts.map +1 -1
- package/dist/sandbox/session-sandbox.js +130 -13
- package/dist/sandbox/session-sandbox.js.map +1 -1
- package/dist/sandbox/workdir.d.ts +10 -0
- package/dist/sandbox/workdir.d.ts.map +1 -1
- package/dist/sandbox/workdir.js +10 -1
- package/dist/sandbox/workdir.js.map +1 -1
- package/dist/session/environment-repositories.d.ts +31 -0
- package/dist/session/environment-repositories.d.ts.map +1 -0
- package/dist/session/environment-repositories.js +89 -0
- package/dist/session/environment-repositories.js.map +1 -0
- package/dist/session/environment-state-processor.d.ts +59 -0
- package/dist/session/environment-state-processor.d.ts.map +1 -0
- package/dist/session/environment-state-processor.js +105 -0
- package/dist/session/environment-state-processor.js.map +1 -0
- package/dist/session/factory-session.d.ts +26 -35
- package/dist/session/factory-session.d.ts.map +1 -1
- package/dist/session/factory-session.js +34 -71
- package/dist/session/factory-session.js.map +1 -1
- package/dist/session/filesystem-capture.d.ts +13 -0
- package/dist/session/filesystem-capture.d.ts.map +1 -1
- package/dist/session/filesystem-capture.js +73 -14
- package/dist/session/filesystem-capture.js.map +1 -1
- package/dist/session/source-control-tools.d.ts +1 -1
- package/dist/session/source-control-tools.d.ts.map +1 -1
- package/dist/session/source-control-tools.js +144 -71
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/spa-static.js +2 -2
- package/dist/storage/domains/audit/agent-audit.d.ts +6 -1
- package/dist/storage/domains/audit/agent-audit.d.ts.map +1 -1
- package/dist/storage/domains/audit/agent-audit.js +31 -13
- package/dist/storage/domains/audit/agent-audit.js.map +1 -1
- package/dist/storage/domains/projects/base.d.ts +115 -2
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +219 -12
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +123 -7
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +406 -33
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +19 -6
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +90 -2
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +12 -5
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/supervisor/read-tools.js +1 -1
- package/dist/supervisor/write-tools.js +1 -1
- package/dist/workspace.d.ts +50 -7
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +344 -24
- package/dist/workspace.js.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-sandbox.js","names":[],"sources":["../../src/sandbox/session-sandbox.ts"],"sourcesContent":["import path from 'node:path';\nimport { SETUP_MARKER_PATH, setupMarkerContent } from '@internal/workspace';\n\nimport type { MastraSandbox, SandboxStartHook, WorkspaceSandbox } from '@mastra/core/workspace';\nimport type { RepositoryAccess } from '../capabilities/version-control.js';\nimport { timedPhase } from '../timing.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 /**\n * The provider's physical sandbox id persisted from a prior start, when the\n * session has been started before. Providers that reattach by physical id\n * (e.g. Railway) MUST forward it to the sandbox constructor so resume\n * reattaches the original VM instead of provisioning a replacement. E2B and\n * Platform accept it as a deterministic-reattach optimization. Undefined on\n * a session's first ever start.\n */\n sandboxId?: 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 * Forward `ctx.sandboxId` to providers that reattach by physical id so resume\n * reattaches the original VM instead of provisioning a replacement.\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, sandboxId }) => new E2BSandbox({ id: sessionId, sandboxId })\n * ```\n */\nexport type MastraFactorySandboxConfig = (ctx: FactorySandboxContext) => MastraSandbox;\n\n/**\n * What the start hook learned about the setup command before running the\n * session setup, and how to record its completion afterwards.\n */\nexport interface SessionSetupGate {\n /** True when the sandbox already carries a marker for the current setup command. */\n setupDone: boolean;\n /** Write the marker once the setup command succeeded. Best-effort. */\n markSetupDone: () => Promise<void>;\n}\n\n/**\n * The session's setup work, run against a started sandbox on EVERY start.\n * Materialize and checkout are idempotent and must always run (a warm boot\n * still needs its pull); only the setup command consults `gate`.\n */\nexport type SessionSetupRun = (sandbox: WorkspaceSandbox, workdir: string, gate: SessionSetupGate) => 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 * The setup completion marker is a convention shared with the repo templates\n * (`@internal/workspace`): `.mastra-sandbox/setup` beside the checkout,\n * containing a digest of the setup commands. Templates write it as their last\n * build step, so a sandbox booted from a warm image already carries it; the\n * start hook writes it after a successful runtime setup. It is a skip cache,\n * not a correctness mechanism: the setup command is assumed idempotent, and a\n * missing or mismatched marker only re-runs it.\n *\n * The working directory is the parent of the repo dir, which is also the\n * template's build cwd, so this is the file the template's marker step wrote.\n */\nfunction markerShellPath(workdir: string): string {\n return `${path.posix.dirname(workdir)}/${SETUP_MARKER_PATH}`;\n}\n\nasync function markerMatches(sandbox: WorkspaceSandbox, workdir: string, content: string): Promise<boolean> {\n // The marker sits beside the checkout, not inside it, so it can outlive a\n // removed checkout (a wiped local session dir, a recovered VM). Trust it\n // only when the checkout it describes exists and it names this command.\n const marker = markerShellPath(workdir);\n const probe = await sandbox.executeCommand!(\n `test -d \"${workdir}/.git\" && test -f \"${marker}\" && [ \"$(cat \"${marker}\")\" = \"${content}\" ]`,\n );\n return probe.exitCode === 0;\n}\n\nasync function writeMarker(sandbox: WorkspaceSandbox, workdir: string, content: string): Promise<void> {\n // Best-effort: a missing marker only re-runs the idempotent setup later.\n const marker = markerShellPath(workdir);\n await sandbox.executeCommand!(`mkdir -p \"$(dirname \"${marker}\")\" && printf '%s' '${content}' > \"${marker}\"`).catch(\n () => {},\n );\n}\n\n/**\n * Build the session setup hook, which factory attaches to the constructed\n * sandbox with `setOnStart`. Runs inside the sandbox start lifecycle on\n * every start, fresh VM or reconnect: materialize and checkout always run,\n * and the setup command runs unless the sandbox already carries the marker\n * for it (a warm template image, or an earlier successful start). Throwing\n * fails `start()` loudly; core treats onStart errors as fatal.\n */\nexport function createSessionSetupHook(\n run: SessionSetupRun,\n sessionId: string,\n repoFullName: string,\n setupCommand: string | undefined,\n): SandboxStartHook {\n // No command, no marker: nothing to gate.\n const marker = setupCommand?.trim() ? setupMarkerContent(setupCommand) : undefined;\n return async ({ sandbox }) => {\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 // Probed before materialize so a wiped checkout reads as \"not done\" even\n // though materialize is about to restore it.\n const setupDone = marker\n ? await timedPhase('workspace.setup-marker', () => markerMatches(sandbox, workdir, marker))\n : true;\n if (marker) {\n process.stderr.write(\n `[factory:setup] ${setupDone ? 'marker matches, skipping setup command' : 'no matching marker, setup command will run'} (${markerShellPath(workdir)})\\n`,\n );\n }\n await run(sandbox, workdir, {\n setupDone,\n markSetupDone: () => (marker ? writeMarker(sandbox, workdir, marker) : Promise.resolve()),\n });\n };\n}\n"],"mappings":";;;;;AAkHA,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,KACxC,oBAAoB,SAAS,YAAY,KACzC,aAAa,MAAM,UAAU,OAAO,GAAG,YAAY;CACrD,IAAI,SAAS,MAAM,YAAY,SAAS,MAAM,UA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iB,SAAgC;CAErG,MAAM,SAAS,gBAAgB,OAAO;CACtC,MAAM,QAAQ,eAAgB,wBAAwB,OAAO,sBAAsB,QAAQ,OAAO,OAAO,EAAE,CAAC,CAAC,YACrG,CAAC,CACT;AACF;;;;;;;;;AAUA,SAAgB,uBACd,KACA,WACA,cACA,cACkB;CAElB,MAAM,SAAS,cAAc,KAAK,IAAI,mBAAmB,YAAY,IAAI,KAAA;CACzE,OAAO,OAAO,EAAE,cAAc;EAC5B,IAAI,CAAC,QAAQ,gBACX,MAAM,IAAI,MAAM,YAAY,QAAQ,GAAG,iEAAiE;EAI1G,MAAM,UAAU,MAAM,sBAAsB,WAAW,SAAS,YAAY;EAG5E,MAAM,YAAY,SACd,MAAM,WAAW,gCAAgC,cAAc,SAAS,SAAS,MAAM,CAAC,IACxF;EACJ,IAAI,QACF,QAAQ,OAAO,MACb,mBAAmB,YAAY,2CAA2C,6CAA6C,IAAI,gBAAgB,OAAO,EAAE,IACtJ;EAEF,MAAM,IAAI,SAAS,SAAS;GAC1B;GACA,qBAAsB,SAAS,YAAY,SAAS,SAAS,MAAM,IAAI,QAAQ,QAAQ;EACzF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"session-sandbox.js","names":[],"sources":["../../src/sandbox/session-sandbox.ts"],"sourcesContent":["import path from 'node:path';\nimport {\n SETUP_FAILED_MARKER_PATH,\n SETUP_MARKER_PATH,\n WORKSPACE_SETUP_MARKER_PATH,\n repoSetupMarkerPath,\n setupMarkerContent,\n} from '@internal/workspace';\n\nimport type {\n FactorySandbox,\n FactorySandboxContext as CoreFactorySandboxContext,\n MastraSandbox,\n SandboxStartHook,\n WorkspaceSandbox,\n} from '@mastra/core/workspace';\nimport { timedPhase } from '../timing.js';\nimport { deriveLocalWorkdir, deriveRemoteRepoDir, repoDirUnder, repositoryDirectoryName } from './workdir.js';\n\n/**\n * Everything factory knows about a session's sandbox needs: the whole contract\n * between factory and the host's FactorySandbox. Factory owns intent; the\n * provider owns resolving `sessionId` to a runnable VM. Defined in\n * `@mastra/core/workspace` so provider packages can implement it without\n * depending on factory.\n */\nexport type FactorySandboxContext = CoreFactorySandboxContext;\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 * Forward `ctx.sandboxId` to providers that reattach by physical id so resume\n * reattaches the original VM instead of provisioning a replacement.\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, sandboxId }) => new E2BSandbox({ id: sessionId, sandboxId })\n * ```\n *\n * A FactorySandbox instance (for example `new E2BFactorySandbox({ apiKey })`)\n * additionally exposes settings and template builds to the environment.\n */\nexport type MastraFactorySandboxConfig = (ctx: FactorySandboxContext) => MastraSandbox;\n\n/**\n * The `sandbox` option of `MastraFactoryConfig`: a FactorySandbox instance\n * (it owns the session sandbox constructor, the repo template and the\n * environment settings schema) or a bare callback, which the factory wraps as a `provider: 'custom'` sandbox with no settings.\n */\nexport type MastraFactorySandboxOption = FactorySandbox | MastraFactorySandboxConfig;\n\n/**\n * What the start hook learned about the setup command before running the\n * session setup, and how to record its completion afterwards.\n */\nexport interface SessionSetupGate {\n /** True when the sandbox already carries a marker for the current setup command. */\n setupDone: boolean;\n /** Write the marker once the setup command succeeded. Best-effort. */\n markSetupDone: () => Promise<void>;\n}\n\n/**\n * The session's setup work, run against a started sandbox on EVERY start.\n * Materialize and checkout are idempotent and must always run (a warm boot\n * still needs its pull); only the setup command consults `gate`.\n */\nexport type SessionSetupRun = (sandbox: WorkspaceSandbox, workdir: string, gate: SessionSetupGate) => Promise<void>;\n\n/** One environment repository as the boot hook needs it: its slug and setup command. */\nexport interface SessionEnvironmentRepository {\n slug: string;\n setupCommand?: string;\n}\n\n/** What the environment hook learned about one repository before the boot runs. */\nexport interface SessionEnvironmentRepositoryGate extends SessionEnvironmentRepository {\n /** `<root>/<repoDir>`, the directory the template cloned this repository into. */\n dir: string;\n gate: SessionSetupGate;\n}\n\n/** The environment hook's view of the workspace: the root, every repository in position order, the workspace gate. */\nexport interface SessionEnvironmentGate {\n /** The workspace root, parent of every repository directory. */\n root: string;\n repos: SessionEnvironmentRepositoryGate[];\n /** Gate for `workspaceSetupCommand`; `setupDone` when there is no command or its marker matches. */\n workspace: SessionSetupGate;\n}\n\n/** The list-form session boot: run on every start, like `SessionSetupRun`. */\nexport type SessionEnvironmentSetupRun = (\n sandbox: WorkspaceSandbox,\n environment: SessionEnvironmentGate,\n) => 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 /** The session's own repository, the only one `workdir` is ever recorded for. */\n ownRepo: string;\n /** Environment repositories in position order; the session's own repository is among them. */\n repos?: string[];\n}\n\nconst sessionSandboxes = new Map<string, SessionSandboxEntry>();\n\n/** One environment repository as the file readers see it. */\nexport interface SessionLayoutRepository {\n slug: string;\n /** Absolute checkout directory. */\n dir: string;\n /** Path prefix of this checkout under the layout root: empty for a single-repository session, `<dir>/` otherwise. */\n prefix: string;\n}\n\n/**\n * Where a session's files are read from. A session with one repository is\n * rooted at that checkout, as before environments existed; a session with\n * several is rooted at the workspace root with each checkout as a directory\n * beneath it.\n */\nexport interface SessionLayout {\n root: string;\n repos: SessionLayoutRepository[];\n}\n\n/** The layout of a memoized session, `undefined` until its workdir resolved. */\nexport function sessionLayout(entry: SessionSandboxEntry | undefined): SessionLayout | undefined {\n if (!entry?.workdir) return undefined;\n const slugs = entry.repos?.length ? entry.repos : [entry.ownRepo];\n if (slugs.length === 1) {\n return { root: entry.workdir, repos: [{ slug: slugs[0]!, dir: entry.workdir, prefix: '' }] };\n }\n const root = path.posix.dirname(entry.workdir);\n return {\n root,\n repos: slugs.map(slug => {\n const dir = slug.toLowerCase() === entry.ownRepo.toLowerCase() ? entry.workdir! : repoDirUnder(root, slug);\n return { slug, dir, prefix: `${path.posix.basename(dir)}/` };\n }),\n };\n}\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 repos?: string[],\n): SessionSandboxEntry {\n const existing = sessionSandboxes.get(sessionId);\n if (existing) {\n // The environment can change between boots; the layout follows the latest.\n if (repos) existing.repos = repos;\n return existing;\n }\n const sandbox = construct();\n const local = deriveLocalWorkdir(sandbox, repoFullName);\n const entry: SessionSandboxEntry = {\n sandbox,\n ownRepo: repoFullName,\n ...(local ? { workdir: local } : {}),\n ...(repos ? { repos } : {}),\n };\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. The memo is the session's own checkout; another\n * environment repository lives beside it under the same root, so it is\n * answered from the memo's parent without a second probe.\n */\nexport async function resolveSessionWorkdir(\n sessionId: string,\n sandbox: WorkspaceSandbox,\n repoFullName: string,\n): Promise<string> {\n const entry = sessionSandboxes.get(sessionId);\n const memo = entry && entry.sandbox === sandbox ? entry : undefined;\n if (memo && memo.ownRepo !== repoFullName) {\n // Passive readers take `workdir` as the session's own checkout, so a\n // sibling never lands in the memo: resolve the own checkout (cold memo\n // included) and answer the sibling beside it.\n const own = await resolveSessionWorkdir(sessionId, sandbox, memo.ownRepo);\n return repoDirUnder(path.posix.dirname(own), repoFullName);\n }\n if (memo?.workdir) return memo.workdir;\n const workdir =\n deriveLocalWorkdir(sandbox, repoFullName) ??\n deriveRemoteRepoDir(sandbox, repoFullName) ??\n repoDirUnder(await probeHome(sandbox), repoFullName);\n if (memo) memo.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, one entry per failed command, so an\n * edited setup command runs fresh. In-memory only — a server restart re-runs the (idempotent)\n * setup.\n */\nconst failedSetupCommands = new Map<string, Set<string>>();\n\nexport function recordFailedSetupCommand(sessionId: string, command: string): void {\n const failed = failedSetupCommands.get(sessionId) ?? new Set<string>();\n failed.add(command);\n failedSetupCommands.set(sessionId, failed);\n}\n\nexport function hasFailedSetupCommand(sessionId: string, command: string): boolean {\n return failedSetupCommands.get(sessionId)?.has(command) ?? false;\n}\n\n/**\n * The setup completion marker is a convention shared with the repo templates\n * (`@internal/workspace`): `.mastra-sandbox/setup` beside the checkout,\n * containing a digest of the setup commands. Templates write it as their last\n * build step, so a sandbox booted from a warm image already carries it; the\n * start hook writes it after a successful runtime setup. It is a skip cache,\n * not a correctness mechanism: the setup command is assumed idempotent, and a\n * missing or mismatched marker only re-runs it.\n *\n * The working directory is the parent of the repo dir, which is also the\n * template's build cwd, so this is the file the template's marker step wrote.\n */\nfunction markerShellPath(workdir: string): string {\n return `${path.posix.dirname(workdir)}/${SETUP_MARKER_PATH}`;\n}\n\nasync function markerMatches(sandbox: WorkspaceSandbox, workdir: string, content: string): Promise<boolean> {\n // The marker sits beside the checkout, not inside it, so it can outlive a\n // removed checkout (a wiped local session dir, a recovered VM). Trust it\n // only when the checkout it describes exists and it names this command.\n const marker = markerShellPath(workdir);\n const probe = await sandbox.executeCommand!(\n `test -d \"${workdir}/.git\" && test -f \"${marker}\" && [ \"$(cat \"${marker}\")\" = \"${content}\" ]`,\n );\n return probe.exitCode === 0;\n}\n\nasync function writeMarker(sandbox: WorkspaceSandbox, workdir: string, content: string): Promise<void> {\n // Best-effort: a missing marker only re-runs the idempotent setup later.\n const marker = markerShellPath(workdir);\n await sandbox.executeCommand!(`mkdir -p \"$(dirname \"${marker}\")\" && printf '%s' '${content}' > \"${marker}\"`).catch(\n () => {},\n );\n}\n\n/**\n * Build the session setup hook, which factory attaches to the constructed\n * sandbox with `setOnStart`. Runs inside the sandbox start lifecycle on\n * every start, fresh VM or reconnect: materialize and checkout always run,\n * and the setup command runs unless the sandbox already carries the marker\n * for it (a warm template image, or an earlier successful start). Throwing\n * fails `start()` loudly; core treats onStart errors as fatal.\n */\nexport function createSessionSetupHook(\n run: SessionSetupRun,\n sessionId: string,\n repoFullName: string,\n setupCommand: string | undefined,\n): SandboxStartHook {\n // No command, no marker: nothing to gate.\n const marker = setupCommand?.trim() ? setupMarkerContent(setupCommand) : undefined;\n return async ({ sandbox }) => {\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 // Probed before materialize so a wiped checkout reads as \"not done\" even\n // though materialize is about to restore it.\n const setupDone = marker\n ? await timedPhase('workspace.setup-marker', () => markerMatches(sandbox, workdir, marker))\n : true;\n if (marker) {\n process.stderr.write(\n `[factory:setup] ${setupDone ? 'marker matches, skipping setup command' : 'no matching marker, setup command will run'} (${markerShellPath(workdir)})\\n`,\n );\n }\n await run(sandbox, workdir, {\n setupDone,\n markSetupDone: () => (marker ? writeMarker(sandbox, workdir, marker) : Promise.resolve()),\n });\n };\n}\n\n/**\n * Shell-quote one marker file's content. Marker contents are digests, but\n * the quoting keeps an edited command's digest from ever reaching the shell\n * unquoted.\n */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * The list-form marker probe: trust a repository's marker only when its\n * checkout exists, the marker names this command, and the template did not\n * record the repository in `setup-failed` (a failed per-repo setup still\n * writes the marker because every step ran; the failure list says it failed).\n */\nasync function repoMarkerMatches(\n sandbox: WorkspaceSandbox,\n root: string,\n repoDir: string,\n content: string,\n): Promise<boolean> {\n const marker = `${root}/${repoSetupMarkerPath(repoDir)}`;\n const failed = `${root}/${SETUP_FAILED_MARKER_PATH}`;\n const probe = await sandbox.executeCommand!(\n `test -d \"${root}/${repoDir}/.git\" && test -f \"${marker}\" && [ \"$(cat \"${marker}\")\" = ${shellQuote(content)} ] && ! grep -qxF -- ${shellQuote(repoDir)} \"${failed}\" 2>/dev/null`,\n );\n return probe.exitCode === 0;\n}\n\n/** Write a repository's marker and drop it from `setup-failed`. Best-effort, like `writeMarker`. */\nasync function writeRepoMarker(\n sandbox: WorkspaceSandbox,\n root: string,\n repoDir: string,\n content: string,\n): Promise<void> {\n const marker = `${root}/${repoSetupMarkerPath(repoDir)}`;\n const failed = `${root}/${SETUP_FAILED_MARKER_PATH}`;\n await sandbox.executeCommand!(\n `mkdir -p \"$(dirname \"${marker}\")\" && printf '%s' ${shellQuote(content)} > \"${marker}\" && { test -f \"${failed}\" && { grep -vxF -- ${shellQuote(repoDir)} \"${failed}\" > \"${failed}.tmp\" || true; } && mv \"${failed}.tmp\" \"${failed}\" || true; }`,\n ).catch(() => {});\n}\n\nasync function workspaceMarkerMatches(sandbox: WorkspaceSandbox, root: string, content: string): Promise<boolean> {\n const marker = `${root}/${WORKSPACE_SETUP_MARKER_PATH}`;\n const probe = await sandbox.executeCommand!(\n `test -f \"${marker}\" && [ \"$(cat \"${marker}\")\" = ${shellQuote(content)} ]`,\n );\n return probe.exitCode === 0;\n}\n\nasync function writeWorkspaceMarker(sandbox: WorkspaceSandbox, root: string, content: string): Promise<void> {\n const marker = `${root}/${WORKSPACE_SETUP_MARKER_PATH}`;\n await sandbox.executeCommand!(\n `mkdir -p \"$(dirname \"${marker}\")\" && printf '%s' ${shellQuote(content)} > \"${marker}\"`,\n ).catch(() => {});\n}\n\n/**\n * The list-form start hook for a session whose factory has an environment:\n * the same lifecycle as `createSessionSetupHook`, with one gate per\n * repository plus one for the workspace setup command. The markers are the\n * ones the multi-repo templates write (`.mastra-sandbox/repos/<repoDir>`,\n * `.mastra-sandbox/workspace-setup`, `.mastra-sandbox/setup-failed`), all\n * under the workspace root, which is the parent of the primary repository's\n * directory: `resolveSessionWorkdir` keeps answering that directory so the\n * PR tools and passive readers see the primary checkout, and the root is\n * derived from it rather than probed twice.\n *\n * `repos` is in position order and must include the primary (`repoFullName`).\n */\nexport function createEnvironmentSetupHook(\n run: SessionEnvironmentSetupRun,\n sessionId: string,\n repoFullName: string,\n environment: { repos: SessionEnvironmentRepository[]; workspaceSetupCommand?: string },\n): SandboxStartHook {\n const workspaceCommand = environment.workspaceSetupCommand?.trim() ? environment.workspaceSetupCommand : undefined;\n const workspaceMarker = workspaceCommand ? setupMarkerContent(workspaceCommand) : undefined;\n return async ({ sandbox }) => {\n if (!sandbox.executeCommand) {\n throw new Error(`Sandbox '${sandbox.id}' cannot run the session setup: no executeCommand implementation`);\n }\n const workdir = await resolveSessionWorkdir(sessionId, sandbox, repoFullName);\n const root = path.posix.dirname(workdir);\n const repos: SessionEnvironmentRepositoryGate[] = [];\n for (const repo of environment.repos) {\n const repoDir = repositoryDirectoryName(repo.slug);\n const marker = repo.setupCommand?.trim() ? setupMarkerContent(repo.setupCommand) : undefined;\n const setupDone = marker\n ? await timedPhase(`workspace.setup-marker(${repoDir})`, () =>\n repoMarkerMatches(sandbox, root, repoDir, marker),\n )\n : true;\n if (marker) {\n process.stderr.write(\n `[factory:setup] ${repo.slug}: ${setupDone ? 'marker matches, skipping setup command' : 'no matching marker, setup command will run'} (${root}/${repoSetupMarkerPath(repoDir)})\\n`,\n );\n }\n repos.push({\n ...repo,\n dir: `${root}/${repoDir}`,\n gate: {\n setupDone,\n markSetupDone: () => (marker ? writeRepoMarker(sandbox, root, repoDir, marker) : Promise.resolve()),\n },\n });\n }\n const workspaceDone = workspaceMarker\n ? await timedPhase('workspace.setup-marker(workspace)', () =>\n workspaceMarkerMatches(sandbox, root, workspaceMarker),\n )\n : true;\n await run(sandbox, {\n root,\n repos,\n workspace: {\n setupDone: workspaceDone,\n markSetupDone: () =>\n workspaceMarker ? writeWorkspaceMarker(sandbox, root, workspaceMarker) : Promise.resolve(),\n },\n });\n };\n}\n"],"mappings":";;;;;AAyIA,MAAM,mCAAmB,IAAI,IAAiC;;AAuB9D,SAAgB,cAAc,OAAmE;CAC/F,IAAI,CAAC,OAAO,SAAS,OAAO,KAAA;CAC5B,MAAM,QAAQ,MAAM,OAAO,SAAS,MAAM,QAAQ,CAAC,MAAM,OAAO;CAChE,IAAI,MAAM,WAAW,GACnB,OAAO;EAAE,MAAM,MAAM;EAAS,OAAO,CAAC;GAAE,MAAM,MAAM;GAAK,KAAK,MAAM;GAAS,QAAQ;EAAG,CAAC;CAAE;CAE7F,MAAM,OAAO,KAAK,MAAM,QAAQ,MAAM,OAAO;CAC7C,OAAO;EACL;EACA,OAAO,MAAM,KAAI,SAAQ;GACvB,MAAM,MAAM,KAAK,YAAY,MAAM,MAAM,QAAQ,YAAY,IAAI,MAAM,UAAW,aAAa,MAAM,IAAI;GACzG,OAAO;IAAE;IAAM;IAAK,QAAQ,GAAG,KAAK,MAAM,SAAS,GAAG,EAAE;GAAG;EAC7D,CAAC;CACH;AACF;;;;;;;AAQA,SAAgB,kBACd,WACA,cACA,WACA,OACqB;CACrB,MAAM,WAAW,iBAAiB,IAAI,SAAS;CAC/C,IAAI,UAAU;EAEZ,IAAI,OAAO,SAAS,QAAQ;EAC5B,OAAO;CACT;CACA,MAAM,UAAU,UAAU;CAC1B,MAAM,QAAQ,mBAAmB,SAAS,YAAY;CACtD,M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A,qBACE,kBAAkB,qBAAqB,SAAS,MAAM,eAAe,IAAI,QAAQ,QAAQ;GAC7F;EACF,CAAC;CACH;AACF"}
|
|
@@ -30,6 +30,16 @@ export declare function deriveRemoteRepoDir(sandbox: {
|
|
|
30
30
|
}, repoFullName: string): string | undefined;
|
|
31
31
|
/** Join a parent directory and sanitized repository name. */
|
|
32
32
|
export declare function repoDirUnder(parent: string, repoFullName: string): string;
|
|
33
|
+
/**
|
|
34
|
+
* The directory a repository checks out into, under the workspace root. Must
|
|
35
|
+
* agree with the repo templates' private `repoDirName`
|
|
36
|
+
* (`workspaces/platform-workspace/src/repo-template.ts`): the last segment
|
|
37
|
+
* of the clone URL, `[^A-Za-z0-9._-]` replaced by `-`, leading dots dropped,
|
|
38
|
+
* `repo` when nothing is left. A repository slug never ends in `.git`, so
|
|
39
|
+
* both derive the same name for every slug; `workdir.test.ts` pins the
|
|
40
|
+
* template's own fixtures.
|
|
41
|
+
*/
|
|
42
|
+
export declare function repositoryDirectoryName(repoFullName: string): string;
|
|
33
43
|
/** Resolve a workdir under `root`, refusing any path that escapes the configured root. */
|
|
34
44
|
export declare function resolveContainedLocalWorkdir(root: string, ...segments: string[]): string;
|
|
35
45
|
//# 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,CAMpB;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,CAIzE;
|
|
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,CAMpB;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,CAIzE;AAED;;;;;;;;GAQG;AACH,wBAAgB,uBAAuB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAGpE;AAED,0FAA0F;AAC1F,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,CAKxF"}
|
package/dist/sandbox/workdir.js
CHANGED
|
@@ -38,6 +38,15 @@ function repoDirUnder(parent, repoFullName) {
|
|
|
38
38
|
while (end > 0 && parent[end - 1] === "/") end--;
|
|
39
39
|
return `${parent.slice(0, end)}/${repositoryDirectoryName(repoFullName)}`;
|
|
40
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* The directory a repository checks out into, under the workspace root. Must
|
|
43
|
+
* agree with the repo templates' private `repoDirName`
|
|
44
|
+
* (`workspaces/platform-workspace/src/repo-template.ts`): the last segment
|
|
45
|
+
* of the clone URL, `[^A-Za-z0-9._-]` replaced by `-`, leading dots dropped,
|
|
46
|
+
* `repo` when nothing is left. A repository slug never ends in `.git`, so
|
|
47
|
+
* both derive the same name for every slug; `workdir.test.ts` pins the
|
|
48
|
+
* template's own fixtures.
|
|
49
|
+
*/
|
|
41
50
|
function repositoryDirectoryName(repoFullName) {
|
|
42
51
|
const segments = repoFullName.split("/");
|
|
43
52
|
return sanitizeSegment(segments.length > 1 ? segments.at(-1) || "repo" : "repo");
|
|
@@ -50,6 +59,6 @@ function resolveContainedLocalWorkdir(root, ...segments) {
|
|
|
50
59
|
throw new Error(`Refusing to use local sandbox path outside configured root: ${resolved}`);
|
|
51
60
|
}
|
|
52
61
|
//#endregion
|
|
53
|
-
export { deriveLocalWorkdir, deriveRemoteRepoDir, repoDirUnder, resolveContainedLocalWorkdir, sanitizeSegment };
|
|
62
|
+
export { deriveLocalWorkdir, deriveRemoteRepoDir, repoDirUnder, repositoryDirectoryName, resolveContainedLocalWorkdir, sanitizeSegment };
|
|
54
63
|
|
|
55
64
|
//# 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 return resolveContainedLocalWorkdir(wd, repositoryDirectoryName(repoFullName));\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 let end = parent.length;\n while (end > 0 && parent[end - 1] === '/') end--;\n return `${parent.slice(0, end)}/${repositoryDirectoryName(repoFullName)}`;\n}\n\
|
|
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 return resolveContainedLocalWorkdir(wd, repositoryDirectoryName(repoFullName));\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 let end = parent.length;\n while (end > 0 && parent[end - 1] === '/') end--;\n return `${parent.slice(0, end)}/${repositoryDirectoryName(repoFullName)}`;\n}\n\n/**\n * The directory a repository checks out into, under the workspace root. Must\n * agree with the repo templates' private `repoDirName`\n * (`workspaces/platform-workspace/src/repo-template.ts`): the last segment\n * of the clone URL, `[^A-Za-z0-9._-]` replaced by `-`, leading dots dropped,\n * `repo` when nothing is left. A repository slug never ends in `.git`, so\n * both derive the same name for every slug; `workdir.test.ts` pins the\n * template's own fixtures.\n */\nexport function repositoryDirectoryName(repoFullName: string): string {\n const segments = repoFullName.split('/');\n return sanitizeSegment(segments.length > 1 ? segments.at(-1) || 'repo' : '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,GACxE,OAAO,6BAA6B,IAAI,wBAAwB,YAAY,CAAC;AAGjF;;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,IAAI,MAAM,OAAO;CACjB,OAAO,MAAM,KAAK,OAAO,MAAM,OAAO,KAAK;CAC3C,OAAO,GAAG,OAAO,MAAM,GAAG,GAAG,EAAE,GAAG,wBAAwB,YAAY;AACxE;;;;;;;;;;AAWA,SAAgB,wBAAwB,cAA8B;CACpE,MAAM,WAAW,aAAa,MAAM,GAAG;CACvC,OAAO,gBAAgB,SAAS,SAAS,IAAI,SAAS,GAAG,EAAE,KAAK,SAAS,MAAM;AACjF;;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"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ProjectRepository, ProjectSourceControlConnection, SourceControlRepository, SourceControlSession, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';
|
|
2
|
+
/** One repository of a factory environment, fully resolved: the link, its repository row and its connection. */
|
|
3
|
+
export interface EnvironmentRepository {
|
|
4
|
+
link: ProjectRepository;
|
|
5
|
+
repository: SourceControlRepository;
|
|
6
|
+
connection: ProjectSourceControlConnection;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The `inEnvironment` links of a factory in position order, resolved to their
|
|
10
|
+
* repository and connection rows, for the integration the handle belongs to.
|
|
11
|
+
* A link whose connection or repository row is missing (an uninstalled app,
|
|
12
|
+
* a link left behind by a reinstall) is skipped with one warning, ids only.
|
|
13
|
+
*/
|
|
14
|
+
export declare function resolveEnvironmentRepositories(args: {
|
|
15
|
+
sourceControl: SourceControlStorageHandle;
|
|
16
|
+
orgId: string;
|
|
17
|
+
factoryProjectId: string;
|
|
18
|
+
}): Promise<EnvironmentRepository[]>;
|
|
19
|
+
/**
|
|
20
|
+
* The repositories a session may target: the environment list plus, when the
|
|
21
|
+
* session is filed under a link that is no longer in the environment (a work
|
|
22
|
+
* item's repository toggled out after dispatch), that own link appended last.
|
|
23
|
+
* A session can always target the repository it was filed under.
|
|
24
|
+
*/
|
|
25
|
+
export declare function resolveSessionRepositories(args: {
|
|
26
|
+
sourceControl: SourceControlStorageHandle;
|
|
27
|
+
session: Pick<SourceControlSession, 'orgId' | 'factoryProjectId' | 'projectRepositoryId'>;
|
|
28
|
+
}): Promise<EnvironmentRepository[]>;
|
|
29
|
+
export declare function findEnvironmentRepository(repositories: EnvironmentRepository[], slug: string): EnvironmentRepository | undefined;
|
|
30
|
+
export declare function environmentSlugs(repositories: EnvironmentRepository[]): string[];
|
|
31
|
+
//# sourceMappingURL=environment-repositories.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"environment-repositories.d.ts","sourceRoot":"","sources":["../../src/session/environment-repositories.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EACjB,8BAA8B,EAC9B,uBAAuB,EACvB,oBAAoB,EACpB,0BAA0B,EAC3B,MAAM,2CAA2C,CAAC;AAEnD,gHAAgH;AAChH,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,iBAAiB,CAAC;IACxB,UAAU,EAAE,uBAAuB,CAAC;IACpC,UAAU,EAAE,8BAA8B,CAAC;CAC5C;AAED;;;;;GAKG;AACH,wBAAsB,8BAA8B,CAAC,IAAI,EAAE;IACzD,aAAa,EAAE,0BAA0B,CAAC;IAC1C,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;CAC1B,GAAG,OAAO,CAAC,qBAAqB,EAAE,CAAC,CA2BnC;AAED;;;;;GAKG;AACH,wBAAsB,0BAA0B,CAAC,IAAI,EAAE;IACrD,aAAa,EAAE,0BAA0B,CAAC;IAC1C,OAAO,EAAE,IAAI,CAAC,oBAAoB,EAAE,OAAO,GAAG,kBAAkB,GAAG,qBAAqB,CAAC,CAAC;CAC3F,GAAG,OAAO,CAAC,qBAAqB,EAAE,CAAC,CAcnC;AAED,wBAAgB,yBAAyB,CACvC,YAAY,EAAE,qBAAqB,EAAE,EACrC,IAAI,EAAE,MAAM,GACX,qBAAqB,GAAG,SAAS,CAGnC;AAED,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,qBAAqB,EAAE,GAAG,MAAM,EAAE,CAEhF"}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
//#region src/session/environment-repositories.ts
|
|
2
|
+
/**
|
|
3
|
+
* The `inEnvironment` links of a factory in position order, resolved to their
|
|
4
|
+
* repository and connection rows, for the integration the handle belongs to.
|
|
5
|
+
* A link whose connection or repository row is missing (an uninstalled app,
|
|
6
|
+
* a link left behind by a reinstall) is skipped with one warning, ids only.
|
|
7
|
+
*/
|
|
8
|
+
async function resolveEnvironmentRepositories(args) {
|
|
9
|
+
const { sourceControl, orgId, factoryProjectId } = args;
|
|
10
|
+
const connections = await sourceControl.connections.list({
|
|
11
|
+
orgId,
|
|
12
|
+
factoryProjectId
|
|
13
|
+
});
|
|
14
|
+
const connectionById = new Map(connections.filter((connection) => connection.integrationId === sourceControl.integrationId).map((connection) => [connection.id, connection]));
|
|
15
|
+
const links = (await sourceControl.projectRepositories.listByProject({
|
|
16
|
+
orgId,
|
|
17
|
+
factoryProjectId
|
|
18
|
+
})).filter((link) => link.inEnvironment).sort((a, b) => a.position - b.position || a.createdAt.getTime() - b.createdAt.getTime());
|
|
19
|
+
const resolved = [];
|
|
20
|
+
for (const link of links) {
|
|
21
|
+
const connection = connectionById.get(link.connectionId);
|
|
22
|
+
const repository = connection ? await sourceControl.repositories.get({
|
|
23
|
+
orgId,
|
|
24
|
+
id: link.repositoryId
|
|
25
|
+
}) : null;
|
|
26
|
+
if (!connection || !repository) {
|
|
27
|
+
console.warn("[Mastra Factory] Environment repository link cannot be resolved; skipping it", {
|
|
28
|
+
orgId,
|
|
29
|
+
factoryProjectId,
|
|
30
|
+
projectRepositoryId: link.id,
|
|
31
|
+
reason: connection ? "repository" : "connection"
|
|
32
|
+
});
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
resolved.push({
|
|
36
|
+
link,
|
|
37
|
+
repository,
|
|
38
|
+
connection
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
return resolved;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The repositories a session may target: the environment list plus, when the
|
|
45
|
+
* session is filed under a link that is no longer in the environment (a work
|
|
46
|
+
* item's repository toggled out after dispatch), that own link appended last.
|
|
47
|
+
* A session can always target the repository it was filed under.
|
|
48
|
+
*/
|
|
49
|
+
async function resolveSessionRepositories(args) {
|
|
50
|
+
const { sourceControl, session } = args;
|
|
51
|
+
const orgId = session.orgId;
|
|
52
|
+
const repositories = session.factoryProjectId ? await resolveEnvironmentRepositories({
|
|
53
|
+
sourceControl,
|
|
54
|
+
orgId,
|
|
55
|
+
factoryProjectId: session.factoryProjectId
|
|
56
|
+
}) : [];
|
|
57
|
+
const ownId = session.projectRepositoryId;
|
|
58
|
+
if (!ownId || repositories.some((candidate) => candidate.link.id === ownId)) return repositories;
|
|
59
|
+
const link = await sourceControl.projectRepositories.get({
|
|
60
|
+
orgId,
|
|
61
|
+
id: ownId
|
|
62
|
+
});
|
|
63
|
+
if (!link) return repositories;
|
|
64
|
+
const connection = await sourceControl.connections.get({
|
|
65
|
+
orgId,
|
|
66
|
+
id: link.connectionId
|
|
67
|
+
});
|
|
68
|
+
const repository = connection ? await sourceControl.repositories.get({
|
|
69
|
+
orgId,
|
|
70
|
+
id: link.repositoryId
|
|
71
|
+
}) : null;
|
|
72
|
+
if (!connection || !repository) return repositories;
|
|
73
|
+
return [...repositories, {
|
|
74
|
+
link,
|
|
75
|
+
repository,
|
|
76
|
+
connection
|
|
77
|
+
}];
|
|
78
|
+
}
|
|
79
|
+
function findEnvironmentRepository(repositories, slug) {
|
|
80
|
+
const wanted = slug.trim().toLowerCase();
|
|
81
|
+
return repositories.find((candidate) => candidate.repository.slug.toLowerCase() === wanted);
|
|
82
|
+
}
|
|
83
|
+
function environmentSlugs(repositories) {
|
|
84
|
+
return repositories.map((candidate) => candidate.repository.slug);
|
|
85
|
+
}
|
|
86
|
+
//#endregion
|
|
87
|
+
export { environmentSlugs, findEnvironmentRepository, resolveEnvironmentRepositories, resolveSessionRepositories };
|
|
88
|
+
|
|
89
|
+
//# sourceMappingURL=environment-repositories.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"environment-repositories.js","names":[],"sources":["../../src/session/environment-repositories.ts"],"sourcesContent":["import type {\n ProjectRepository,\n ProjectSourceControlConnection,\n SourceControlRepository,\n SourceControlSession,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\n\n/** One repository of a factory environment, fully resolved: the link, its repository row and its connection. */\nexport interface EnvironmentRepository {\n link: ProjectRepository;\n repository: SourceControlRepository;\n connection: ProjectSourceControlConnection;\n}\n\n/**\n * The `inEnvironment` links of a factory in position order, resolved to their\n * repository and connection rows, for the integration the handle belongs to.\n * A link whose connection or repository row is missing (an uninstalled app,\n * a link left behind by a reinstall) is skipped with one warning, ids only.\n */\nexport async function resolveEnvironmentRepositories(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n}): Promise<EnvironmentRepository[]> {\n const { sourceControl, orgId, factoryProjectId } = args;\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n const connectionById = new Map(\n connections\n .filter(connection => connection.integrationId === sourceControl.integrationId)\n .map(connection => [connection.id, connection] as const),\n );\n const links = (await sourceControl.projectRepositories.listByProject({ orgId, factoryProjectId }))\n .filter(link => link.inEnvironment)\n .sort((a, b) => a.position - b.position || a.createdAt.getTime() - b.createdAt.getTime());\n const resolved: EnvironmentRepository[] = [];\n for (const link of links) {\n const connection = connectionById.get(link.connectionId);\n const repository = connection ? await sourceControl.repositories.get({ orgId, id: link.repositoryId }) : null;\n if (!connection || !repository) {\n console.warn('[Mastra Factory] Environment repository link cannot be resolved; skipping it', {\n orgId,\n factoryProjectId,\n projectRepositoryId: link.id,\n reason: connection ? 'repository' : 'connection',\n });\n continue;\n }\n resolved.push({ link, repository, connection });\n }\n return resolved;\n}\n\n/**\n * The repositories a session may target: the environment list plus, when the\n * session is filed under a link that is no longer in the environment (a work\n * item's repository toggled out after dispatch), that own link appended last.\n * A session can always target the repository it was filed under.\n */\nexport async function resolveSessionRepositories(args: {\n sourceControl: SourceControlStorageHandle;\n session: Pick<SourceControlSession, 'orgId' | 'factoryProjectId' | 'projectRepositoryId'>;\n}): Promise<EnvironmentRepository[]> {\n const { sourceControl, session } = args;\n const orgId = session.orgId;\n const repositories = session.factoryProjectId\n ? await resolveEnvironmentRepositories({ sourceControl, orgId, factoryProjectId: session.factoryProjectId })\n : [];\n const ownId = session.projectRepositoryId;\n if (!ownId || repositories.some(candidate => candidate.link.id === ownId)) return repositories;\n const link = await sourceControl.projectRepositories.get({ orgId, id: ownId });\n if (!link) return repositories;\n const connection = await sourceControl.connections.get({ orgId, id: link.connectionId });\n const repository = connection ? await sourceControl.repositories.get({ orgId, id: link.repositoryId }) : null;\n if (!connection || !repository) return repositories;\n return [...repositories, { link, repository, connection }];\n}\n\nexport function findEnvironmentRepository(\n repositories: EnvironmentRepository[],\n slug: string,\n): EnvironmentRepository | undefined {\n const wanted = slug.trim().toLowerCase();\n return repositories.find(candidate => candidate.repository.slug.toLowerCase() === wanted);\n}\n\nexport function environmentSlugs(repositories: EnvironmentRepository[]): string[] {\n return repositories.map(candidate => candidate.repository.slug);\n}\n"],"mappings":";;;;;;;AAqBA,eAAsB,+BAA+B,MAIhB;CACnC,MAAM,EAAE,eAAe,OAAO,qBAAqB;CACnD,MAAM,cAAc,MAAM,cAAc,YAAY,KAAK;EAAE;EAAO;CAAiB,CAAC;CACpF,MAAM,iBAAiB,IAAI,IACzB,YACG,QAAO,eAAc,WAAW,kBAAkB,cAAc,aAAa,CAAC,CAC9E,KAAI,eAAc,CAAC,WAAW,IAAI,UAAU,CAAU,CAC3D;CACA,MAAM,SAAS,MAAM,cAAc,oBAAoB,cAAc;EAAE;EAAO;CAAiB,CAAC,EAAA,CAC7F,QAAO,SAAQ,KAAK,aAAa,CAAC,CAClC,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,QAAQ,IAAI,EAAE,UAAU,QAAQ,CAAC;CAC1F,MAAM,WAAoC,CAAC;CAC3C,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,aAAa,eAAe,IA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;AAChE"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { ComputeStateSignalArgs, ComputeStateSignalResult, Processor } from '@mastra/core/processors';
|
|
2
|
+
export type EnvironmentRepositorySetupStatus = 'ok' | 'failed' | 'skipped';
|
|
3
|
+
/** One repository of the booted environment as the agent is told about it: never a token or a clone URL. */
|
|
4
|
+
export interface SessionEnvironmentRepositoryState {
|
|
5
|
+
slug: string;
|
|
6
|
+
/** Absolute directory of the checkout under the workspace root. */
|
|
7
|
+
dir: string;
|
|
8
|
+
/** The branch the checkout ended on after boot; `null` when it stays detached. */
|
|
9
|
+
branch: string | null;
|
|
10
|
+
defaultBranch: string;
|
|
11
|
+
position: number;
|
|
12
|
+
/** `ok` ran or was already set up, `failed` exited non-zero, `skipped` has no setup command. */
|
|
13
|
+
setupStatus: EnvironmentRepositorySetupStatus;
|
|
14
|
+
/** The change request this session opened in the repository, once it has. */
|
|
15
|
+
changeRequestUrl?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface SessionEnvironmentState {
|
|
18
|
+
/** The workspace root, the session's working directory; repositories sit beneath it. */
|
|
19
|
+
workingDirectory: string;
|
|
20
|
+
repositories: SessionEnvironmentRepositoryState[];
|
|
21
|
+
/** One free-form line the boot wants the agent to know (never a credential), rendered last. */
|
|
22
|
+
note?: string;
|
|
23
|
+
}
|
|
24
|
+
/** A repository's teardown command and the directory it runs in; kept beside the state, never rendered. */
|
|
25
|
+
export interface SessionEnvironmentTeardown {
|
|
26
|
+
slug: string;
|
|
27
|
+
dir: string;
|
|
28
|
+
command: string;
|
|
29
|
+
}
|
|
30
|
+
export declare function recordSessionEnvironment(sessionId: string, state: SessionEnvironmentState, teardown?: SessionEnvironmentTeardown[]): void;
|
|
31
|
+
/**
|
|
32
|
+
* Record what a source-control tool did in one environment repository (the
|
|
33
|
+
* branch it pushed, the change request it opened) so the next signal snapshot
|
|
34
|
+
* tells the agent. A no-op when the session's environment is not recorded in
|
|
35
|
+
* this process or the slug is not part of it.
|
|
36
|
+
*/
|
|
37
|
+
export declare function updateSessionEnvironmentRepository(sessionId: string, slug: string, patch: {
|
|
38
|
+
branch?: string;
|
|
39
|
+
changeRequestUrl?: string;
|
|
40
|
+
}): void;
|
|
41
|
+
/** Set or clear the environment's note; a no-op when the session's environment is not recorded here. */
|
|
42
|
+
export declare function setSessionEnvironmentNote(sessionId: string, note: string | null): void;
|
|
43
|
+
export declare function clearSessionEnvironment(sessionId: string): void;
|
|
44
|
+
export declare function peekSessionEnvironment(sessionId: string): SessionEnvironmentState | undefined;
|
|
45
|
+
/** Teardown commands of the booted environment, in position order. */
|
|
46
|
+
export declare function peekSessionEnvironmentTeardown(sessionId: string): SessionEnvironmentTeardown[];
|
|
47
|
+
export declare function __clearSessionEnvironmentsForTests(): void;
|
|
48
|
+
/**
|
|
49
|
+
* Tells the agent which repositories its sandbox holds and where: the
|
|
50
|
+
* workspace root is the session's working directory and every environment
|
|
51
|
+
* repository is a directory beneath it. Snapshot mode only; a new snapshot
|
|
52
|
+
* is emitted when the booted set changes (a start after an environment edit).
|
|
53
|
+
*/
|
|
54
|
+
export declare class FactoryEnvironmentStateProcessor implements Processor<'factory-environment'> {
|
|
55
|
+
readonly id = "factory-environment";
|
|
56
|
+
readonly stateId = "factory-environment";
|
|
57
|
+
computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult>;
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=environment-state-processor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"environment-state-processor.d.ts","sourceRoot":"","sources":["../../src/session/environment-state-processor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAK3G,MAAM,MAAM,gCAAgC,GAAG,IAAI,GAAG,QAAQ,GAAG,SAAS,CAAC;AAE3E,4GAA4G;AAC5G,MAAM,WAAW,iCAAiC;IAChD,IAAI,EAA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MAAM,GAAG,0BAA0B,EAAE,CAE9F;AAED,wBAAgB,kCAAkC,IAAI,IAAI,CAEzD;AAmBD;;;;;GAKG;AACH,qBAAa,gCAAiC,YAAW,SAAS,CAAC,qBAAqB,CAAC;IACvF,QAAQ,CAAC,EAAE,yBAAY;IACvB,QAAQ,CAAC,OAAO,yBAAY;IAEtB,kBAAkB,CAAC,IAAI,EAAE,sBAAsB,GAAG,OAAO,CAAC,wBAAwB,CAAC;CAiC1F"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createHash } from "crypto";
|
|
2
|
+
//#region src/session/environment-state-processor.ts
|
|
3
|
+
const STATE_ID = "factory-environment";
|
|
4
|
+
const environments = /* @__PURE__ */ new Map();
|
|
5
|
+
function recordSessionEnvironment(sessionId, state, teardown = []) {
|
|
6
|
+
environments.set(sessionId, {
|
|
7
|
+
state,
|
|
8
|
+
teardown
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Record what a source-control tool did in one environment repository (the
|
|
13
|
+
* branch it pushed, the change request it opened) so the next signal snapshot
|
|
14
|
+
* tells the agent. A no-op when the session's environment is not recorded in
|
|
15
|
+
* this process or the slug is not part of it.
|
|
16
|
+
*/
|
|
17
|
+
function updateSessionEnvironmentRepository(sessionId, slug, patch) {
|
|
18
|
+
const entry = environments.get(sessionId);
|
|
19
|
+
if (!entry) return;
|
|
20
|
+
const wanted = slug.toLowerCase();
|
|
21
|
+
const repositories = entry.state.repositories.map((repo) => {
|
|
22
|
+
if (repo.slug.toLowerCase() !== wanted) return repo;
|
|
23
|
+
return {
|
|
24
|
+
...repo,
|
|
25
|
+
...patch.branch !== void 0 ? { branch: patch.branch } : {},
|
|
26
|
+
...patch.changeRequestUrl !== void 0 ? { changeRequestUrl: patch.changeRequestUrl } : {}
|
|
27
|
+
};
|
|
28
|
+
});
|
|
29
|
+
entry.state = {
|
|
30
|
+
...entry.state,
|
|
31
|
+
repositories
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** Set or clear the environment's note; a no-op when the session's environment is not recorded here. */
|
|
35
|
+
function setSessionEnvironmentNote(sessionId, note) {
|
|
36
|
+
const entry = environments.get(sessionId);
|
|
37
|
+
if (!entry) return;
|
|
38
|
+
const { note: _previous, ...rest } = entry.state;
|
|
39
|
+
entry.state = note ? {
|
|
40
|
+
...rest,
|
|
41
|
+
note
|
|
42
|
+
} : rest;
|
|
43
|
+
}
|
|
44
|
+
function clearSessionEnvironment(sessionId) {
|
|
45
|
+
environments.delete(sessionId);
|
|
46
|
+
}
|
|
47
|
+
function peekSessionEnvironment(sessionId) {
|
|
48
|
+
return environments.get(sessionId)?.state;
|
|
49
|
+
}
|
|
50
|
+
/** Teardown commands of the booted environment, in position order. */
|
|
51
|
+
function peekSessionEnvironmentTeardown(sessionId) {
|
|
52
|
+
return environments.get(sessionId)?.teardown ?? [];
|
|
53
|
+
}
|
|
54
|
+
function __clearSessionEnvironmentsForTests() {
|
|
55
|
+
environments.clear();
|
|
56
|
+
}
|
|
57
|
+
function escapeText(value) {
|
|
58
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
59
|
+
}
|
|
60
|
+
function sessionIdFromContext(requestContext) {
|
|
61
|
+
if (!requestContext || typeof requestContext.get !== "function") return null;
|
|
62
|
+
const controller = requestContext.get("controller");
|
|
63
|
+
return typeof controller?.resourceId === "string" && controller.resourceId ? controller.resourceId : null;
|
|
64
|
+
}
|
|
65
|
+
function environmentCacheKey(state) {
|
|
66
|
+
return `environment:${createHash("sha256").update(JSON.stringify(state)).digest("hex").slice(0, 16)}`;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Tells the agent which repositories its sandbox holds and where: the
|
|
70
|
+
* workspace root is the session's working directory and every environment
|
|
71
|
+
* repository is a directory beneath it. Snapshot mode only; a new snapshot
|
|
72
|
+
* is emitted when the booted set changes (a start after an environment edit).
|
|
73
|
+
*/
|
|
74
|
+
var FactoryEnvironmentStateProcessor = class {
|
|
75
|
+
id = STATE_ID;
|
|
76
|
+
stateId = STATE_ID;
|
|
77
|
+
async computeStateSignal(args) {
|
|
78
|
+
const sessionId = sessionIdFromContext(args.requestContext);
|
|
79
|
+
if (!sessionId) return;
|
|
80
|
+
const state = environments.get(sessionId)?.state;
|
|
81
|
+
if (!state) return;
|
|
82
|
+
const cacheKey = environmentCacheKey(state);
|
|
83
|
+
if (Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey) return;
|
|
84
|
+
const lines = state.repositories.map((repo) => `${repo.position}. ${escapeText(repo.slug)} at ${escapeText(repo.dir)} on ${escapeText(repo.branch ?? "(detached)")} (default ${escapeText(repo.defaultBranch)}, setup ${repo.setupStatus})` + (repo.changeRequestUrl ? `, change request ${escapeText(repo.changeRequestUrl)}` : ""));
|
|
85
|
+
const only = state.repositories.length === 1 ? state.repositories[0] : void 0;
|
|
86
|
+
const contents = (only ? `Factory environment: 1 repository, ${escapeText(only.slug)} at ${escapeText(only.dir)}, your working directory.\n` : `Factory environment: ${state.repositories.length} repositories under ${escapeText(state.workingDirectory)}, your working directory.\n`) + lines.join("\n") + (only ? "" : "\nRun git and project commands inside the repository directory they belong to.") + (state.note ? `\n${escapeText(state.note)}` : "");
|
|
87
|
+
return {
|
|
88
|
+
id: STATE_ID,
|
|
89
|
+
cacheKey,
|
|
90
|
+
mode: "snapshot",
|
|
91
|
+
tagName: "factory-environment",
|
|
92
|
+
contents,
|
|
93
|
+
value: { environment: state },
|
|
94
|
+
attributes: {
|
|
95
|
+
workingDirectory: only?.dir ?? state.workingDirectory,
|
|
96
|
+
repositories: state.repositories.length
|
|
97
|
+
},
|
|
98
|
+
metadata: { value: { environment: state } }
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
//#endregion
|
|
103
|
+
export { FactoryEnvironmentStateProcessor, __clearSessionEnvironmentsForTests, clearSessionEnvironment, peekSessionEnvironment, peekSessionEnvironmentTeardown, recordSessionEnvironment, setSessionEnvironmentNote, updateSessionEnvironmentRepository };
|
|
104
|
+
|
|
105
|
+
//# sourceMappingURL=environment-state-processor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"environment-state-processor.js","names":[],"sources":["../../src/session/environment-state-processor.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport type { ComputeStateSignalArgs, ComputeStateSignalResult, Processor } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nconst STATE_ID = 'factory-environment';\n\nexport type EnvironmentRepositorySetupStatus = 'ok' | 'failed' | 'skipped';\n\n/** One repository of the booted environment as the agent is told about it: never a token or a clone URL. */\nexport interface SessionEnvironmentRepositoryState {\n slug: string;\n /** Absolute directory of the checkout under the workspace root. */\n dir: string;\n /** The branch the checkout ended on after boot; `null` when it stays detached. */\n branch: string | null;\n defaultBranch: string;\n position: number;\n /** `ok` ran or was already set up, `failed` exited non-zero, `skipped` has no setup command. */\n setupStatus: EnvironmentRepositorySetupStatus;\n /** The change request this session opened in the repository, once it has. */\n changeRequestUrl?: string;\n}\n\nexport interface SessionEnvironmentState {\n /** The workspace root, the session's working directory; repositories sit beneath it. */\n workingDirectory: string;\n repositories: SessionEnvironmentRepositoryState[];\n /** One free-form line the boot wants the agent to know (never a credential), rendered last. */\n note?: string;\n}\n\n// The boot records what it materialized, keyed by the factory session id (the\n// agent's resource id); the processor reads it on the next model step. Boot\n// runs on every sandbox start, so a replacement process re-learns the state\n// the first time the session's sandbox starts again.\nconst environments = new Map<string, { state: SessionEnvironmentState; teardown: SessionEnvironmentTeardown[] }>();\n\n/** A repository's teardown command and the directory it runs in; kept beside the state, never rendered. */\nexport interface SessionEnvironmentTeardown {\n slug: string;\n dir: string;\n command: string;\n}\n\nexport function recordSessionEnvironment(\n sessionId: string,\n state: SessionEnvironmentState,\n teardown: SessionEnvironmentTeardown[] = [],\n): void {\n environments.set(sessionId, { state, teardown });\n}\n\n/**\n * Record what a source-control tool did in one environment repository (the\n * branch it pushed, the change request it opened) so the next signal snapshot\n * tells the agent. A no-op when the session's environment is not recorded in\n * this process or the slug is not part of it.\n */\nexport function updateSessionEnvironmentRepository(\n sessionId: string,\n slug: string,\n patch: { branch?: string; changeRequestUrl?: string },\n): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const wanted = slug.toLowerCase();\n const repositories = entry.state.repositories.map(repo => {\n if (repo.slug.toLowerCase() !== wanted) return repo;\n return {\n ...repo,\n ...(patch.branch !== undefined ? { branch: patch.branch } : {}),\n ...(patch.changeRequestUrl !== undefined ? { changeRequestUrl: patch.changeRequestUrl } : {}),\n };\n });\n entry.state = { ...entry.state, repositories };\n}\n\n/** Set or clear the environment's note; a no-op when the session's environment is not recorded here. */\nexport function setSessionEnvironmentNote(sessionId: string, note: string | null): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const { note: _previous, ...rest } = entry.state;\n entry.state = note ? { ...rest, note } : rest;\n}\n\nexport function clearSessionEnvironment(sessionId: string): void {\n environments.delete(sessionId);\n}\n\nexport function peekSessionEnvironment(sessionId: string): SessionEnvironmentState | undefined {\n return environments.get(sessionId)?.state;\n}\n\n/** Teardown commands of the booted environment, in position order. */\nexport function peekSessionEnvironmentTeardown(sessionId: string): SessionEnvironmentTeardown[] {\n return environments.get(sessionId)?.teardown ?? [];\n}\n\nexport function __clearSessionEnvironmentsForTests(): void {\n environments.clear();\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');\n}\n\n// The session id is the controller's resource id. Unlike factory runs, a user\n// session carries no `factoryProjectId` in its controller state, and the\n// environment is recorded for both, so only the resource id is required.\nfunction sessionIdFromContext(requestContext: RequestContext | undefined): string | null {\n if (!requestContext || typeof requestContext.get !== 'function') return null;\n const controller = requestContext.get('controller') as { resourceId?: unknown } | undefined;\n return typeof controller?.resourceId === 'string' && controller.resourceId ? controller.resourceId : null;\n}\n\nfunction environmentCacheKey(state: SessionEnvironmentState): string {\n return `environment:${createHash('sha256').update(JSON.stringify(state)).digest('hex').slice(0, 16)}`;\n}\n\n/**\n * Tells the agent which repositories its sandbox holds and where: the\n * workspace root is the session's working directory and every environment\n * repository is a directory beneath it. Snapshot mode only; a new snapshot\n * is emitted when the booted set changes (a start after an environment edit).\n */\nexport class FactoryEnvironmentStateProcessor implements Processor<'factory-environment'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const sessionId = sessionIdFromContext(args.requestContext);\n if (!sessionId) return;\n const state = environments.get(sessionId)?.state;\n if (!state) return;\n const cacheKey = environmentCacheKey(state);\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey)\n return;\n const lines = state.repositories.map(\n repo =>\n `${repo.position}. ${escapeText(repo.slug)} at ${escapeText(repo.dir)} on ${escapeText(repo.branch ?? '(detached)')} (default ${escapeText(repo.defaultBranch)}, setup ${repo.setupStatus})` +\n (repo.changeRequestUrl ? `, change request ${escapeText(repo.changeRequestUrl)}` : ''),\n );\n const only = state.repositories.length === 1 ? state.repositories[0] : undefined;\n const contents =\n (only\n ? `Factory environment: 1 repository, ${escapeText(only.slug)} at ${escapeText(only.dir)}, your working directory.\\n`\n : `Factory environment: ${state.repositories.length} repositories under ${escapeText(state.workingDirectory)}, your working directory.\\n`) +\n lines.join('\\n') +\n (only ? '' : '\\nRun git and project commands inside the repository directory they belong to.') +\n (state.note ? `\\n${escapeText(state.note)}` : '');\n return {\n id: STATE_ID,\n cacheKey,\n mode: 'snapshot',\n tagName: 'factory-environment',\n contents,\n value: { environment: state },\n attributes: { workingDirectory: only?.dir ?? state.workingDirectory, repositories: state.repositories.length },\n metadata: { value: { environment: state } },\n };\n }\n}\n"],"mappings":";;A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AM,KAAK,IAAI,KACd,OAAO,KAAK,qFACZ,MAAM,OAAO,KAAK,WAAW,MAAM,IAAI,MAAM;EAChD,OAAO;GACL,IAAI;GACJ;GACA,MAAM;GACN,SAAS;GACT;GACA,OAAO,EAAE,aAAa,MAAM;GAC5B,YAAY;IAAE,kBAAkB,MAAM,OAAO,MAAM;IAAkB,cAAc,MAAM,aAAa;GAAO;GAC7G,UAAU,EAAE,OAAO,EAAE,aAAa,MAAM,EAAE;EAC5C;CACF;AACF"}
|
|
@@ -51,8 +51,12 @@ export interface EnsureFactorySourceSessionArgs {
|
|
|
51
51
|
orgId: string;
|
|
52
52
|
factoryProjectId: string;
|
|
53
53
|
branch: string;
|
|
54
|
-
/**
|
|
55
|
-
|
|
54
|
+
/**
|
|
55
|
+
* The repository link the session is filed under: the one a work item
|
|
56
|
+
* targets. Defaults to the factory's position-1 environment link (D1), for
|
|
57
|
+
* callers where nothing names a repository (chat threads, user sessions).
|
|
58
|
+
*/
|
|
59
|
+
projectRepositoryId?: string;
|
|
56
60
|
/**
|
|
57
61
|
* Attribute the run to this user instead of the repo connector. Set when the
|
|
58
62
|
* run has an interactive user — e.g. the person who approved a proposed run.
|
|
@@ -78,10 +82,11 @@ export interface ResolvedFactorySourceRepository {
|
|
|
78
82
|
connectedByUserId: string;
|
|
79
83
|
}
|
|
80
84
|
/**
|
|
81
|
-
* Outcome of {@link
|
|
82
|
-
* failed: callers differ on whether that is an error (an autonomous run
|
|
83
|
-
* proceed) or a routine fallback (a chat integration drops to a
|
|
84
|
-
* session), and the two steps fail for different reasons worth
|
|
85
|
+
* Outcome of {@link resolvePrimaryEnvironmentRepository}. A miss carries which
|
|
86
|
+
* step failed: callers differ on whether that is an error (an autonomous run
|
|
87
|
+
* cannot proceed) or a routine fallback (a chat integration drops to a
|
|
88
|
+
* chat-only session), and the two steps fail for different reasons worth
|
|
89
|
+
* reporting apart.
|
|
85
90
|
*/
|
|
86
91
|
export type FactorySourceRepositoryResult = ({
|
|
87
92
|
found: true;
|
|
@@ -90,49 +95,35 @@ export type FactorySourceRepositoryResult = ({
|
|
|
90
95
|
reason: 'connection' | 'repository';
|
|
91
96
|
};
|
|
92
97
|
/**
|
|
93
|
-
*
|
|
94
|
-
*
|
|
98
|
+
* The repository link a new session is filed under. By default the position-1
|
|
99
|
+
* `inEnvironment` link of the factory (decision D1); a work item that targets
|
|
100
|
+
* a repository names its link through `projectRepositoryId`, which must be an
|
|
101
|
+
* environment link of the same factory. Session start no longer picks a
|
|
102
|
+
* repository to work in, the sandbox holds every environment repository. The
|
|
103
|
+
* PR tools default to this link, and subscriptions, audit and the work item's
|
|
104
|
+
* repository check still read it; moving them to the per-repository
|
|
105
|
+
* `sessionRepositories` rows is a follow-up.
|
|
95
106
|
*
|
|
96
107
|
* The owner is whichever integration owns source control, matched by the
|
|
97
108
|
* handle's own `integrationId` — nothing here is provider-specific.
|
|
98
109
|
*/
|
|
99
|
-
export declare function
|
|
110
|
+
export declare function resolvePrimaryEnvironmentRepository(args: {
|
|
100
111
|
sourceControl: SourceControlStorageHandle;
|
|
101
112
|
orgId: string;
|
|
102
113
|
factoryProjectId: string;
|
|
103
|
-
|
|
104
|
-
} | {
|
|
105
|
-
sourceControl: SourceControlStorageHandle;
|
|
106
|
-
orgId: string;
|
|
107
|
-
factoryProjectId: string;
|
|
108
|
-
firstLinkedRepository: true;
|
|
114
|
+
projectRepositoryId?: string;
|
|
109
115
|
}): Promise<FactorySourceRepositoryResult>;
|
|
110
|
-
/**
|
|
111
|
-
* Walk a Factory user-session id back to the project it belongs to.
|
|
112
|
-
*
|
|
113
|
-
* Repo-backed channel threads are keyed by their Factory session id, which is
|
|
114
|
-
* the only handle a session-start hook gets. This turns that id back into the
|
|
115
|
-
* project whose configuration the session should adopt. Durable by
|
|
116
|
-
* construction — it reads the same rows the session was created from, so it
|
|
117
|
-
* survives restarts without any in-memory mapping.
|
|
118
|
-
*/
|
|
119
|
-
export declare function resolveFactoryProjectForSession(args: {
|
|
120
|
-
sourceControl: SourceControlStorageHandle;
|
|
121
|
-
sessionId: string;
|
|
122
|
-
}): Promise<{
|
|
123
|
-
factoryProjectId: string;
|
|
124
|
-
orgId: string;
|
|
125
|
-
userId: string;
|
|
126
|
-
} | null>;
|
|
127
116
|
/**
|
|
128
117
|
* Create the source-control session a repo-backed factory run needs.
|
|
129
118
|
*
|
|
130
119
|
* `FactoryStartCoordinator.prepare` requires this record to already exist —
|
|
131
120
|
* `resolveSourceSession` throws `Factory session not found` otherwise — so every
|
|
132
121
|
* autonomous entry point has to produce one before it can start a run. This is
|
|
133
|
-
* that step, in one place: the owner's connection on the factory project,
|
|
134
|
-
*
|
|
135
|
-
*
|
|
122
|
+
* that step, in one place: the owner's connection on the factory project, the
|
|
123
|
+
* work item's repository link (else the position-1 environment link, D1) as
|
|
124
|
+
* the session's link, and a session on the requested branch with that
|
|
125
|
+
* repository's pinned or default branch as the base. The sandbox itself boots
|
|
126
|
+
* every environment repository.
|
|
136
127
|
*
|
|
137
128
|
* The run is attributed to `attributeToUserId` when the caller has an
|
|
138
129
|
* interactive user (e.g. the approver of a proposed run), and otherwise falls
|