@mastra/factory 0.11.1 → 0.12.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/factory.d.ts +2 -22
  3. package/dist/factory.d.ts.map +1 -1
  4. package/dist/factory.js +15 -58
  5. package/dist/factory.js.map +1 -1
  6. package/dist/index.d.ts +2 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/integrations/base.d.ts +5 -13
  9. package/dist/integrations/base.d.ts.map +1 -1
  10. package/dist/integrations/github/config.d.ts +4 -4
  11. package/dist/integrations/github/config.d.ts.map +1 -1
  12. package/dist/integrations/github/config.js +3 -3
  13. package/dist/integrations/github/config.js.map +1 -1
  14. package/dist/integrations/github/integration.d.ts.map +1 -1
  15. package/dist/integrations/github/integration.js +2 -4
  16. package/dist/integrations/github/integration.js.map +1 -1
  17. package/dist/integrations/github/reconcile-worker.d.ts +0 -5
  18. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  19. package/dist/integrations/github/reconcile-worker.js +0 -7
  20. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  21. package/dist/integrations/github/routes.d.ts +6 -5
  22. package/dist/integrations/github/routes.d.ts.map +1 -1
  23. package/dist/integrations/github/routes.js +36 -263
  24. package/dist/integrations/github/routes.js.map +1 -1
  25. package/dist/integrations/github/sandbox-release.d.ts +17 -47
  26. package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
  27. package/dist/integrations/github/sandbox-release.js +24 -103
  28. package/dist/integrations/github/sandbox-release.js.map +1 -1
  29. package/dist/integrations/github/sandbox.d.ts +25 -139
  30. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  31. package/dist/integrations/github/sandbox.js +24 -212
  32. package/dist/integrations/github/sandbox.js.map +1 -1
  33. package/dist/integrations/github/webhook.d.ts.map +1 -1
  34. package/dist/integrations/github/webhook.js +1 -2
  35. package/dist/integrations/github/webhook.js.map +1 -1
  36. package/dist/integrations/platform/github/event-worker.d.ts +0 -2
  37. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  38. package/dist/integrations/platform/github/event-worker.js +0 -7
  39. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  40. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  41. package/dist/integrations/platform/github/integration.js +5 -7
  42. package/dist/integrations/platform/github/integration.js.map +1 -1
  43. package/dist/routes/config.d.ts.map +1 -1
  44. package/dist/routes/config.js +3 -1
  45. package/dist/routes/config.js.map +1 -1
  46. package/dist/routes/fs.d.ts +4 -6
  47. package/dist/routes/fs.d.ts.map +1 -1
  48. package/dist/routes/fs.js +28 -34
  49. package/dist/routes/fs.js.map +1 -1
  50. package/dist/routes/skills.d.ts.map +1 -1
  51. package/dist/routes/skills.js +6 -3
  52. package/dist/routes/skills.js.map +1 -1
  53. package/dist/routes/surface.d.ts +4 -9
  54. package/dist/routes/surface.d.ts.map +1 -1
  55. package/dist/routes/surface.js +3 -5
  56. package/dist/routes/surface.js.map +1 -1
  57. package/dist/sandbox/materialization.d.ts +36 -0
  58. package/dist/sandbox/materialization.d.ts.map +1 -0
  59. package/dist/sandbox/materialization.js +18 -0
  60. package/dist/sandbox/materialization.js.map +1 -0
  61. package/dist/sandbox/session-retirement.d.ts +8 -6
  62. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  63. package/dist/sandbox/session-retirement.js +28 -123
  64. package/dist/sandbox/session-retirement.js.map +1 -1
  65. package/dist/sandbox/session-sandbox.d.ts +117 -0
  66. package/dist/sandbox/session-sandbox.d.ts.map +1 -0
  67. package/dist/sandbox/session-sandbox.js +132 -0
  68. package/dist/sandbox/session-sandbox.js.map +1 -0
  69. package/dist/sandbox/workdir.d.ts +30 -0
  70. package/dist/sandbox/workdir.d.ts.map +1 -0
  71. package/dist/sandbox/workdir.js +48 -0
  72. package/dist/sandbox/workdir.js.map +1 -0
  73. package/dist/session/filesystem-capture.d.ts +2 -1
  74. package/dist/session/filesystem-capture.d.ts.map +1 -1
  75. package/dist/session/filesystem-capture.js +45 -4
  76. package/dist/session/filesystem-capture.js.map +1 -1
  77. package/dist/session/first-exec-capture.d.ts +1 -0
  78. package/dist/session/first-exec-capture.d.ts.map +1 -1
  79. package/dist/session/first-exec-capture.js +1 -1
  80. package/dist/session/first-exec-capture.js.map +1 -1
  81. package/dist/storage/domains/integrations/base.d.ts +1 -1
  82. package/dist/storage/domains/integrations/base.js +1 -1
  83. package/dist/storage/domains/integrations/base.js.map +1 -1
  84. package/dist/storage/domains/source-control/base.d.ts +0 -144
  85. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  86. package/dist/storage/domains/source-control/base.js +3 -290
  87. package/dist/storage/domains/source-control/base.js.map +1 -1
  88. package/dist/storage/domains/source-control/inmemory.d.ts +1 -63
  89. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  90. package/dist/storage/domains/source-control/inmemory.js +0 -89
  91. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  92. package/dist/workspace.d.ts +5 -37
  93. package/dist/workspace.d.ts.map +1 -1
  94. package/dist/workspace.js +107 -245
  95. package/dist/workspace.js.map +1 -1
  96. package/package.json +4 -4
  97. package/dist/sandbox/base-checkpoint-triggers.d.ts +0 -77
  98. package/dist/sandbox/base-checkpoint-triggers.d.ts.map +0 -1
  99. package/dist/sandbox/base-checkpoint-triggers.js +0 -137
  100. package/dist/sandbox/base-checkpoint-triggers.js.map +0 -1
  101. package/dist/sandbox/base-checkpoint.d.ts +0 -59
  102. package/dist/sandbox/base-checkpoint.d.ts.map +0 -1
  103. package/dist/sandbox/base-checkpoint.js +0 -145
  104. package/dist/sandbox/base-checkpoint.js.map +0 -1
  105. package/dist/sandbox/fleet.d.ts +0 -258
  106. package/dist/sandbox/fleet.d.ts.map +0 -1
  107. package/dist/sandbox/fleet.js +0 -356
  108. package/dist/sandbox/fleet.js.map +0 -1
  109. package/dist/sandbox/reattach.d.ts +0 -3
  110. package/dist/sandbox/reattach.d.ts.map +0 -1
  111. package/dist/sandbox/reattach.js +0 -16
  112. package/dist/sandbox/reattach.js.map +0 -1
@@ -0,0 +1,132 @@
1
+ import { deriveLocalWorkdir, remoteWorkdirFromHome } from "./workdir.js";
2
+ //#region src/sandbox/session-sandbox.ts
3
+ const sessionSandboxes = /* @__PURE__ */ new Map();
4
+ /**
5
+ * Get the session's memoized sandbox entry, constructing (and memoizing) it on
6
+ * first access. Construction is cheap and side-effect-free by contract; VMs
7
+ * are provisioned on `start()` only. Local sandboxes get their workdir here;
8
+ * remote workdirs are a runtime fact of the VM, resolved on first start.
9
+ */
10
+ function getSessionSandbox(sessionId, repoFullName, construct) {
11
+ const existing = sessionSandboxes.get(sessionId);
12
+ if (existing) return existing;
13
+ const sandbox = construct();
14
+ const local = deriveLocalWorkdir(sandbox, repoFullName);
15
+ const entry = {
16
+ sandbox,
17
+ ...local ? { workdir: local } : {}
18
+ };
19
+ sessionSandboxes.set(sessionId, entry);
20
+ return entry;
21
+ }
22
+ /**
23
+ * Resolve (and memoize on the session entry) the session's repo checkout
24
+ * root. Local sandboxes answer synchronously from their configured
25
+ * `workingDirectory`; remote sandboxes clone into the VM's own default cwd,
26
+ * so the first resolution probes it with one `pwd` — the VM tells us where
27
+ * home is, we never invent a path. Calling this against a stopped sandbox
28
+ * lazily starts it (the probe is a command), so passive readers must peek
29
+ * `entry.workdir` instead.
30
+ */
31
+ async function resolveSessionWorkdir(sessionId, sandbox, repoFullName) {
32
+ const entry = sessionSandboxes.get(sessionId);
33
+ if (entry?.workdir && entry.sandbox === sandbox) return entry.workdir;
34
+ const workdir = deriveLocalWorkdir(sandbox, repoFullName) ?? remoteWorkdirFromHome(await probeHome(sandbox), repoFullName);
35
+ if (entry && entry.sandbox === sandbox) entry.workdir = workdir;
36
+ return workdir;
37
+ }
38
+ /** One `pwd` in the VM's default shell cwd — its home dir, by provider convention. */
39
+ async function probeHome(sandbox) {
40
+ if (!sandbox.executeCommand) throw new Error(`Sandbox '${sandbox.id}' cannot resolve its workdir: no executeCommand implementation`);
41
+ const probe = await sandbox.executeCommand("pwd");
42
+ const home = probe.stdout.trim().split("\n").pop()?.trim() ?? "";
43
+ if (probe.exitCode !== 0 || !home.startsWith("/")) throw new Error(`Sandbox '${sandbox.id}' default cwd probe failed (exit ${probe.exitCode}): ${probe.stderr.trim() || probe.stdout.trim() || "empty output"}`);
44
+ return home;
45
+ }
46
+ /**
47
+ * The session's memoized sandbox (and its workdir) when one was already
48
+ * constructed in this process, else undefined. Never constructs — passive
49
+ * read paths use this so browsing files cannot provision a VM.
50
+ */
51
+ function peekSessionSandbox(sessionId) {
52
+ return sessionSandboxes.get(sessionId);
53
+ }
54
+ /** Drop the memoized instance (on stop/destroy/retirement or construction failure). */
55
+ function evictSessionSandbox(sessionId) {
56
+ sessionSandboxes.delete(sessionId);
57
+ failedSetupCommands.delete(sessionId);
58
+ }
59
+ /** Test-only: reset the process-wide memo between tests. */
60
+ function __clearSessionSandboxesForTests() {
61
+ sessionSandboxes.clear();
62
+ failedSetupCommands.clear();
63
+ }
64
+ /**
65
+ * Setup commands that already failed once for a session. The first failure
66
+ * fails the start loudly — the agent sees the real error in the tool result
67
+ * that triggered it. Recording it lets the next start skip the known-bad
68
+ * command instead of wedging the session behind a permanently failing
69
+ * onStart: clone and checkout still run, and the agent can fix or re-run
70
+ * the setup itself. Keyed by the exact command so an edited setup command
71
+ * runs fresh. In-memory only — a server restart re-runs the (idempotent)
72
+ * setup.
73
+ */
74
+ const failedSetupCommands = /* @__PURE__ */ new Map();
75
+ function recordFailedSetupCommand(sessionId, command) {
76
+ failedSetupCommands.set(sessionId, command);
77
+ }
78
+ function hasFailedSetupCommand(sessionId, command) {
79
+ return failedSetupCommands.get(sessionId) === command;
80
+ }
81
+ /**
82
+ * Completion marker for the session setup. Factory owns this end-to-end:
83
+ * the `onStart` hook and the post-start fallback guard the exact same path,
84
+ * so setup never double-runs regardless of which layer executed it. It is a
85
+ * skip cache, not a correctness mechanism — the setup work is idempotent by
86
+ * construction (materialize probes the disk, checkout/setup re-run safely).
87
+ */
88
+ const SESSION_SETUP_MARKER = ".mastra-factory/bootstrap";
89
+ function markerShellPath(sandbox) {
90
+ return sandbox.provider === "local" ? `./${SESSION_SETUP_MARKER}` : `$HOME/${SESSION_SETUP_MARKER}`;
91
+ }
92
+ async function markerPresent(sandbox, workdir) {
93
+ return (await sandbox.executeCommand(`test -f "${markerShellPath(sandbox)}" && test -d "${workdir}/.git"`)).exitCode === 0;
94
+ }
95
+ async function writeMarker(sandbox) {
96
+ const marker = markerShellPath(sandbox);
97
+ await sandbox.executeCommand(`mkdir -p "$(dirname "${marker}")" && touch "${marker}"`).catch(() => {});
98
+ }
99
+ /**
100
+ * Run the session setup, marker-guarded: skip when the marker exists (unless
101
+ * the VM is known-fresh), otherwise run and write the marker only on
102
+ * success. Setup failures propagate — no marker is written, so the next
103
+ * attempt re-runs.
104
+ */
105
+ async function runGuardedSetup(sandbox, run, { skipMarkerProbe, sessionId, repoFullName }) {
106
+ if (!sandbox.executeCommand) throw new Error(`Sandbox '${sandbox.id}' cannot run the session setup: no executeCommand implementation`);
107
+ const workdir = await resolveSessionWorkdir(sessionId, sandbox, repoFullName);
108
+ if (!skipMarkerProbe && await markerPresent(sandbox, workdir)) return;
109
+ await run(sandbox, workdir);
110
+ await writeMarker(sandbox);
111
+ }
112
+ /**
113
+ * Build the session setup hook, which factory attaches to the constructed
114
+ * sandbox with `setOnStart`. Runs inside the sandbox start
115
+ * lifecycle: a fresh VM (`outcome: 'created'`) runs setup with no probe; a
116
+ * reconnect probes the marker first, which re-runs setup after a failed or
117
+ * crash-interrupted attempt. Throwing fails `start()` loudly — core treats
118
+ * onStart errors as fatal.
119
+ */
120
+ function createSessionSetupHook(run, sessionId, repoFullName) {
121
+ return async ({ sandbox, outcome }) => {
122
+ await runGuardedSetup(sandbox, run, {
123
+ skipMarkerProbe: outcome === "created",
124
+ sessionId,
125
+ repoFullName
126
+ });
127
+ };
128
+ }
129
+ //#endregion
130
+ export { __clearSessionSandboxesForTests, createSessionSetupHook, evictSessionSandbox, getSessionSandbox, hasFailedSetupCommand, peekSessionSandbox, recordFailedSetupCommand, resolveSessionWorkdir };
131
+
132
+ //# sourceMappingURL=session-sandbox.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-sandbox.js","names":[],"sources":["../../src/sandbox/session-sandbox.ts"],"sourcesContent":["import type { MastraSandbox, SandboxStartHook, WorkspaceSandbox } from '@mastra/core/workspace';\nimport type { RepositoryAccess } from '../capabilities/version-control.js';\nimport { deriveLocalWorkdir, remoteWorkdirFromHome } from './workdir.js';\n\n/**\n * Everything factory knows about a session's sandbox needs — the whole\n * contract between factory and the deployer's sandbox callback. Factory owns\n * intent; the provider owns resolving `sessionId` to a runnable VM.\n */\nexport interface FactorySandboxContext {\n /** Stable session id — the sandbox identity. */\n sessionId: string;\n /** owner/name of the repository, when the session is repo-backed. */\n repoFullName?: string;\n /**\n * Configured repo setup command, when present. Part of a repo template's\n * identity: a different setup command produces a different template.\n */\n setupCommand?: string;\n /**\n * Resolves the session repository's clone URL and a fresh short-lived\n * credential for it. Providers use it for authenticated work that runs\n * outside the VM — resolving a private repo's head, or cloning it during\n * a template build. The credential is minted per call (installation\n * tokens expire in ~1h); never an org PAT.\n *\n * `undefined` when the session has no repository, which is how a provider\n * knows to build no repo template. The key is always present so that\n * passing the whole context to a provider helper keeps working when this\n * field changes, instead of silently resolving to \"no repository\".\n */\n getRepositoryAccess: (() => Promise<RepositoryAccess>) | undefined;\n}\n\n/**\n * The deploy's sandbox configuration: construct a session's sandbox from\n * intent. The sandbox identity is the session id; the provider must honor\n * id-keyed getOrCreate on `start()` (reconnect/resume an existing VM for the\n * id, create otherwise). Construction must be cheap and side-effect-free —\n * VMs are provisioned on `start()` only. Local sandboxes should root their\n * `workingDirectory` at a per-session directory (e.g.\n * `join(root, ctx.sessionId)`); the repo checks out as a subdirectory of it.\n *\n * Returns a `MastraSandbox`, not the bare `WorkspaceSandbox` interface:\n * factory relies on the base class for the start lifecycle and the runtime\n * env, so providers extend it rather than reimplementing the contract.\n *\n * Factory attaches its own session setup to the returned sandbox, so the\n * callback never has to wire it up. A callback may still pass its own\n * `onStart`; it runs after factory's setup, against a prepared workspace.\n *\n * @example\n * ```typescript\n * sandbox: ({ sessionId }) => new E2BSandbox({ id: sessionId })\n * ```\n */\nexport type MastraFactorySandboxConfig = (ctx: FactorySandboxContext) => MastraSandbox;\n\n/** The session's setup work, run against a started sandbox. Must be idempotent. */\nexport type SessionSetupRun = (sandbox: WorkspaceSandbox, workdir: string) => Promise<void>;\n\n/**\n * Per-process session-id → sandbox instance memo.\n *\n * The provider contract is id-keyed getOrCreate, but provider find-then-create\n * has a real double-create race across independent instances. Memoizing the\n * instance per session makes the base class's per-instance start coalescing\n * apply process-wide per session — the same single-flight scope the fleet's\n * per-binding coalescing provided. Cross-replica races are accepted (the\n * fleet was also per-replica).\n */\ninterface SessionSandboxEntry {\n sandbox: WorkspaceSandbox;\n /**\n * The session's repo checkout root, recorded for passive readers (fs\n * routes, capture, authz). Local sandboxes derive it at construction;\n * remote sandboxes clone into the VM's own home, so it is undefined until\n * `resolveSessionWorkdir` probes the first started VM — passive readers\n * treat an unresolved workdir as \"nothing materialized\".\n */\n workdir?: string;\n}\n\nconst sessionSandboxes = new Map<string, SessionSandboxEntry>();\n\n/**\n * Get the session's memoized sandbox entry, constructing (and memoizing) it on\n * first access. Construction is cheap and side-effect-free by contract; VMs\n * are provisioned on `start()` only. Local sandboxes get their workdir here;\n * remote workdirs are a runtime fact of the VM, resolved on first start.\n */\nexport function getSessionSandbox(\n sessionId: string,\n repoFullName: string,\n construct: () => WorkspaceSandbox,\n): SessionSandboxEntry {\n const existing = sessionSandboxes.get(sessionId);\n if (existing) return existing;\n const sandbox = construct();\n const local = deriveLocalWorkdir(sandbox, repoFullName);\n const entry: SessionSandboxEntry = { sandbox, ...(local ? { workdir: local } : {}) };\n sessionSandboxes.set(sessionId, entry);\n return entry;\n}\n\n/**\n * Resolve (and memoize on the session entry) the session's repo checkout\n * root. Local sandboxes answer synchronously from their configured\n * `workingDirectory`; remote sandboxes clone into the VM's own default cwd,\n * so the first resolution probes it with one `pwd` — the VM tells us where\n * home is, we never invent a path. Calling this against a stopped sandbox\n * lazily starts it (the probe is a command), so passive readers must peek\n * `entry.workdir` instead.\n */\nexport async function resolveSessionWorkdir(\n sessionId: string,\n sandbox: WorkspaceSandbox,\n repoFullName: string,\n): Promise<string> {\n const entry = sessionSandboxes.get(sessionId);\n if (entry?.workdir && entry.sandbox === sandbox) return entry.workdir;\n const workdir =\n deriveLocalWorkdir(sandbox, repoFullName) ?? remoteWorkdirFromHome(await probeHome(sandbox), repoFullName);\n if (entry && entry.sandbox === sandbox) entry.workdir = workdir;\n return workdir;\n}\n\n/** One `pwd` in the VM's default shell cwd — its home dir, by provider convention. */\nasync function probeHome(sandbox: WorkspaceSandbox): Promise<string> {\n if (!sandbox.executeCommand) {\n throw new Error(`Sandbox '${sandbox.id}' cannot resolve its workdir: no executeCommand implementation`);\n }\n const probe = await sandbox.executeCommand('pwd');\n const home = probe.stdout.trim().split('\\n').pop()?.trim() ?? '';\n if (probe.exitCode !== 0 || !home.startsWith('/')) {\n throw new Error(\n `Sandbox '${sandbox.id}' default cwd probe failed (exit ${probe.exitCode}): ${\n probe.stderr.trim() || probe.stdout.trim() || 'empty output'\n }`,\n );\n }\n return home;\n}\n\n/**\n * The session's memoized sandbox (and its workdir) when one was already\n * constructed in this process, else undefined. Never constructs — passive\n * read paths use this so browsing files cannot provision a VM.\n */\nexport function peekSessionSandbox(sessionId: string): SessionSandboxEntry | undefined {\n return sessionSandboxes.get(sessionId);\n}\n\n/** Drop the memoized instance (on stop/destroy/retirement or construction failure). */\nexport function evictSessionSandbox(sessionId: string): void {\n sessionSandboxes.delete(sessionId);\n failedSetupCommands.delete(sessionId);\n}\n\n/** Test-only: reset the process-wide memo between tests. */\nexport function __clearSessionSandboxesForTests(): void {\n sessionSandboxes.clear();\n failedSetupCommands.clear();\n}\n\n/**\n * Setup commands that already failed once for a session. The first failure\n * fails the start loudly — the agent sees the real error in the tool result\n * that triggered it. Recording it lets the next start skip the known-bad\n * command instead of wedging the session behind a permanently failing\n * onStart: clone and checkout still run, and the agent can fix or re-run\n * the setup itself. Keyed by the exact command so an edited setup command\n * runs fresh. In-memory only — a server restart re-runs the (idempotent)\n * setup.\n */\nconst failedSetupCommands = new Map<string, string>();\n\nexport function recordFailedSetupCommand(sessionId: string, command: string): void {\n failedSetupCommands.set(sessionId, command);\n}\n\nexport function hasFailedSetupCommand(sessionId: string, command: string): boolean {\n return failedSetupCommands.get(sessionId) === command;\n}\n\n/**\n * Completion marker for the session setup. Factory owns this end-to-end:\n * the `onStart` hook and the post-start fallback guard the exact same path,\n * so setup never double-runs regardless of which layer executed it. It is a\n * skip cache, not a correctness mechanism — the setup work is idempotent by\n * construction (materialize probes the disk, checkout/setup re-run safely).\n */\nconst SESSION_SETUP_MARKER = '.mastra-factory/bootstrap';\n\nfunction markerShellPath(sandbox: Pick<WorkspaceSandbox, 'provider'>): string {\n // Local sandboxes exec with cwd = the session working directory; remote\n // VMs are one-per-session so $HOME is private to the session.\n return sandbox.provider === 'local' ? `./${SESSION_SETUP_MARKER}` : `$HOME/${SESSION_SETUP_MARKER}`;\n}\n\nasync function markerPresent(sandbox: WorkspaceSandbox, workdir: string): Promise<boolean> {\n // The marker is a skip cache — it sits beside the checkout, not inside it,\n // so it can outlive a removed checkout (e.g. a wiped local session dir or\n // a recovered VM). Trust it only when the checkout it describes exists.\n const probe = await sandbox.executeCommand!(`test -f \"${markerShellPath(sandbox)}\" && test -d \"${workdir}/.git\"`);\n return probe.exitCode === 0;\n}\n\nasync function writeMarker(sandbox: WorkspaceSandbox): Promise<void> {\n // Best-effort: a missing marker only re-runs the idempotent setup later.\n const marker = markerShellPath(sandbox);\n await sandbox.executeCommand!(`mkdir -p \"$(dirname \"${marker}\")\" && touch \"${marker}\"`).catch(() => {});\n}\n\n/**\n * Run the session setup, marker-guarded: skip when the marker exists (unless\n * the VM is known-fresh), otherwise run and write the marker only on\n * success. Setup failures propagate — no marker is written, so the next\n * attempt re-runs.\n */\nasync function runGuardedSetup(\n sandbox: WorkspaceSandbox,\n run: SessionSetupRun,\n { skipMarkerProbe, sessionId, repoFullName }: { skipMarkerProbe: boolean; sessionId: string; repoFullName: string },\n): Promise<void> {\n if (!sandbox.executeCommand) {\n throw new Error(`Sandbox '${sandbox.id}' cannot run the session setup: no executeCommand implementation`);\n }\n // Resolved from the live instance (the hook runs inside `start()`, so the\n // VM is up) and memoized on the session entry for passive readers.\n const workdir = await resolveSessionWorkdir(sessionId, sandbox, repoFullName);\n if (!skipMarkerProbe && (await markerPresent(sandbox, workdir))) return;\n await run(sandbox, workdir);\n await writeMarker(sandbox);\n}\n\n/**\n * Build the session setup hook, which factory attaches to the constructed\n * sandbox with `setOnStart`. Runs inside the sandbox start\n * lifecycle: a fresh VM (`outcome: 'created'`) runs setup with no probe; a\n * reconnect probes the marker first, which re-runs setup after a failed or\n * crash-interrupted attempt. Throwing fails `start()` loudly — core treats\n * onStart errors as fatal.\n */\nexport function createSessionSetupHook(\n run: SessionSetupRun,\n sessionId: string,\n repoFullName: string,\n): SandboxStartHook {\n return async ({ sandbox, outcome }) => {\n await runGuardedSetup(sandbox, run, { skipMarkerProbe: outcome === 'created', sessionId, repoFullName });\n };\n}\n"],"mappings":";;AAmFA,MAAM,mCAAmB,IAAI,IAAiC;;;;;;;AAQ9D,SAAgB,kBACd,WACA,cACA,WACqB;CACrB,MAAM,WAAW,iBAAiB,IAAI,SAAS;CAC/C,IAAI,UAAU,OAAO;CACrB,MAAM,UAAU,UAAU;CAC1B,MAAM,QAAQ,mBAAmB,SAAS,YAAY;CACtD,MAAM,QAA6B;EAAE;EAAS,GAAI,QAAQ,EAAE,SAAS,MAAM,IAAI,CAAC;CAAG;CACnF,iBAAiB,IAAI,WAAW,KAAK;CACrC,OAAO;AACT;;;;;;;;;;AAWA,eAA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,aAAa,UAAU,KAAK,yBAAyB,SAAS;AAC/E;AAEA,eAAe,cAAc,SAA2B,SAAmC;CAKzF,QAAO,MADa,QAAQ,eAAgB,YAAY,gBAAgB,OAAO,EAAE,gBAAgB,QAAQ,OAAO,EAAA,CACnG,aAAa;AAC5B;AAEA,eAAe,YAAY,SAA0C;CAEnE,MAAM,SAAS,gBAAgB,OAAO;CACtC,MAAM,QAAQ,eAAgB,wBAAwB,OAAO,gBAAgB,OAAO,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC;AACxG;;;;;;;AAQA,eAAe,gBACb,SACA,KACA,EAAE,iBAAiB,WAAW,gBACf;CACf,IAAI,CAAC,QAAQ,gBACX,MAAM,IAAI,MAAM,YAAY,QAAQ,GAAG,iEAAiE;CAI1G,MAAM,UAAU,MAAM,sBAAsB,WAAW,SAAS,YAAY;CAC5E,IAAI,CAAC,mBAAoB,MAAM,cAAc,SAAS,OAAO,GAAI;CACjE,MAAM,IAAI,SAAS,OAAO;CAC1B,MAAM,YAAY,OAAO;AAC3B;;;;;;;;;AAUA,SAAgB,uBACd,KACA,WACA,cACkB;CAClB,OAAO,OAAO,EAAE,SAAS,cAAc;EACrC,MAAM,gBAAgB,SAAS,KAAK;GAAE,iBAAiB,YAAY;GAAW;GAAW;EAAa,CAAC;CACzG;AACF"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Session workdir derivation. Workdirs are never persisted or trusted from
3
+ * storage or client input — the stale-workdir class of production bugs came
4
+ * from reading `session.sandboxWorkdir` written under a different provider.
5
+ *
6
+ * Local sandboxes derive their workdir synchronously from the sandbox's own
7
+ * `workingDirectory` (the per-session directory the deploy's callback chose).
8
+ * Remote sandboxes have no invented path: the repo clones into the VM's own
9
+ * default cwd (its home dir), so the workdir is only knowable once a VM is
10
+ * running — resolved lazily by `resolveSessionWorkdir` via a one-time `pwd`
11
+ * probe and memoized on the session entry.
12
+ */
13
+ /** Keep each path piece a single safe segment (no separators or traversal). */
14
+ export declare function sanitizeSegment(segment: string): string;
15
+ /**
16
+ * Synchronously derivable workdir: local sandboxes expose their host
17
+ * `workingDirectory`; the repo checks out as a contained subdirectory so the
18
+ * setup marker sits beside the clone instead of polluting `git status`
19
+ * inside it. Returns undefined for remote providers, whose workdir is a
20
+ * runtime fact of the VM (`<home>/<repo>`).
21
+ */
22
+ export declare function deriveLocalWorkdir(sandbox: {
23
+ provider: string;
24
+ workingDirectory?: unknown;
25
+ }, repoFullName: string): string | undefined;
26
+ /** `<home>/<repo>` — where a remote VM's default-cwd clone lands. */
27
+ export declare function remoteWorkdirFromHome(home: string, repoFullName: string): string;
28
+ /** Resolve a workdir under `root`, refusing any path that escapes the configured root. */
29
+ export declare function resolveContainedLocalWorkdir(root: string, ...segments: string[]): string;
30
+ //# sourceMappingURL=workdir.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workdir.d.ts","sourceRoot":"","sources":["../../src/sandbox/workdir.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AAEH,+EAA+E;AAC/E,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAGvD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAE,EACzD,YAAY,EAAE,MAAM,GACnB,MAAM,GAAG,SAAS,CAOpB;AAED,qEAAqE;AACrE,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAGhF;AAED,0FAA0F;AAC1F,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,CAKxF"}
@@ -0,0 +1,48 @@
1
+ import * as path$1 from "path";
2
+ //#region src/sandbox/workdir.ts
3
+ /**
4
+ * Session workdir derivation. Workdirs are never persisted or trusted from
5
+ * storage or client input — the stale-workdir class of production bugs came
6
+ * from reading `session.sandboxWorkdir` written under a different provider.
7
+ *
8
+ * Local sandboxes derive their workdir synchronously from the sandbox's own
9
+ * `workingDirectory` (the per-session directory the deploy's callback chose).
10
+ * Remote sandboxes have no invented path: the repo clones into the VM's own
11
+ * default cwd (its home dir), so the workdir is only knowable once a VM is
12
+ * running — resolved lazily by `resolveSessionWorkdir` via a one-time `pwd`
13
+ * probe and memoized on the session entry.
14
+ */
15
+ /** Keep each path piece a single safe segment (no separators or traversal). */
16
+ function sanitizeSegment(segment) {
17
+ return segment.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^\.+/, "") || "repo";
18
+ }
19
+ /**
20
+ * Synchronously derivable workdir: local sandboxes expose their host
21
+ * `workingDirectory`; the repo checks out as a contained subdirectory so the
22
+ * setup marker sits beside the clone instead of polluting `git status`
23
+ * inside it. Returns undefined for remote providers, whose workdir is a
24
+ * runtime fact of the VM (`<home>/<repo>`).
25
+ */
26
+ function deriveLocalWorkdir(sandbox, repoFullName) {
27
+ const wd = sandbox.workingDirectory;
28
+ if (sandbox.provider === "local" && typeof wd === "string" && wd.length > 0) {
29
+ const [, name] = repoFullName.split("/", 2);
30
+ return resolveContainedLocalWorkdir(wd, sanitizeSegment(name || "repo"));
31
+ }
32
+ }
33
+ /** `<home>/<repo>` — where a remote VM's default-cwd clone lands. */
34
+ function remoteWorkdirFromHome(home, repoFullName) {
35
+ const [, name] = repoFullName.split("/", 2);
36
+ return `${home.replace(/\/+$/, "")}/${sanitizeSegment(name || "repo")}`;
37
+ }
38
+ /** Resolve a workdir under `root`, refusing any path that escapes the configured root. */
39
+ function resolveContainedLocalWorkdir(root, ...segments) {
40
+ const resolvedRoot = path$1.resolve(root);
41
+ const resolved = path$1.resolve(resolvedRoot, ...segments);
42
+ if (resolved !== resolvedRoot && resolved.startsWith(`${resolvedRoot}${path$1.sep}`)) return resolved;
43
+ throw new Error(`Refusing to use local sandbox path outside configured root: ${resolved}`);
44
+ }
45
+ //#endregion
46
+ export { deriveLocalWorkdir, remoteWorkdirFromHome, resolveContainedLocalWorkdir, sanitizeSegment };
47
+
48
+ //# sourceMappingURL=workdir.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workdir.js","names":["path"],"sources":["../../src/sandbox/workdir.ts"],"sourcesContent":["import * as path from 'node:path';\n\n/**\n * Session workdir derivation. Workdirs are never persisted or trusted from\n * storage or client input — the stale-workdir class of production bugs came\n * from reading `session.sandboxWorkdir` written under a different provider.\n *\n * Local sandboxes derive their workdir synchronously from the sandbox's own\n * `workingDirectory` (the per-session directory the deploy's callback chose).\n * Remote sandboxes have no invented path: the repo clones into the VM's own\n * default cwd (its home dir), so the workdir is only knowable once a VM is\n * running — resolved lazily by `resolveSessionWorkdir` via a one-time `pwd`\n * probe and memoized on the session entry.\n */\n\n/** Keep each path piece a single safe segment (no separators or traversal). */\nexport function sanitizeSegment(segment: string): string {\n const cleaned = segment.replace(/[^A-Za-z0-9._-]/g, '-').replace(/^\\.+/, '');\n return cleaned || 'repo';\n}\n\n/**\n * Synchronously derivable workdir: local sandboxes expose their host\n * `workingDirectory`; the repo checks out as a contained subdirectory so the\n * setup marker sits beside the clone instead of polluting `git status`\n * inside it. Returns undefined for remote providers, whose workdir is a\n * runtime fact of the VM (`<home>/<repo>`).\n */\nexport function deriveLocalWorkdir(\n sandbox: { provider: string; workingDirectory?: unknown },\n repoFullName: string,\n): string | undefined {\n const wd = sandbox.workingDirectory;\n if (sandbox.provider === 'local' && typeof wd === 'string' && wd.length > 0) {\n const [, name] = repoFullName.split('/', 2);\n return resolveContainedLocalWorkdir(wd, sanitizeSegment(name || 'repo'));\n }\n return undefined;\n}\n\n/** `<home>/<repo>` — where a remote VM's default-cwd clone lands. */\nexport function remoteWorkdirFromHome(home: string, repoFullName: string): string {\n const [, name] = repoFullName.split('/', 2);\n return `${home.replace(/\\/+$/, '')}/${sanitizeSegment(name || 'repo')}`;\n}\n\n/** Resolve a workdir under `root`, refusing any path that escapes the configured root. */\nexport function resolveContainedLocalWorkdir(root: string, ...segments: string[]): string {\n const resolvedRoot = path.resolve(root);\n const resolved = path.resolve(resolvedRoot, ...segments);\n if (resolved !== resolvedRoot && resolved.startsWith(`${resolvedRoot}${path.sep}`)) return resolved;\n throw new Error(`Refusing to use local sandbox path outside configured root: ${resolved}`);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,SAAgB,gBAAgB,SAAyB;CAEvD,OADgB,QAAQ,QAAQ,oBAAoB,GAAG,CAAC,CAAC,QAAQ,QAAQ,EAC5D,KAAK;AACpB;;;;;;;;AASA,SAAgB,mBACd,SACA,cACoB;CACpB,MAAM,KAAK,QAAQ;CACnB,IAAI,QAAQ,aAAa,WAAW,OAAO,OAAO,YAAY,GAAG,SAAS,GAAG;EAC3E,MAAM,GAAG,QAAQ,aAAa,MAAM,KAAK,CAAC;EAC1C,OAAO,6BAA6B,IAAI,gBAAgB,QAAQ,MAAM,CAAC;CACzE;AAEF;;AAGA,SAAgB,sBAAsB,MAAc,cAA8B;CAChF,MAAM,GAAG,QAAQ,aAAa,MAAM,KAAK,CAAC;CAC1C,OAAO,GAAG,KAAK,QAAQ,QAAQ,EAAE,EAAE,GAAG,gBAAgB,QAAQ,MAAM;AACtE;;AAGA,SAAgB,6BAA6B,MAAc,GAAG,UAA4B;CACxF,MAAM,eAAeA,OAAK,QAAQ,IAAI;CACtC,MAAM,WAAWA,OAAK,QAAQ,cAAc,GAAG,QAAQ;CACvD,IAAI,aAAa,gBAAgB,SAAS,WAAW,GAAG,eAAeA,OAAK,KAAK,GAAG,OAAO;CAC3F,MAAM,IAAI,MAAM,+DAA+D,UAAU;AAC3F"}
@@ -1,4 +1,4 @@
1
- import type { SessionBeforeAgentEndListener } from '@mastra/core/agent-controller';
1
+ import type { AgentControllerEvent, SessionBeforeAgentEndListener } from '@mastra/core/agent-controller';
2
2
  import type { WorkspaceSandbox } from '@mastra/core/workspace';
3
3
  import type { FilesystemFile, FilesystemStorage } from '../storage/domains/filesystem/base.js';
4
4
  import type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';
@@ -13,6 +13,7 @@ export interface FilesystemCaptureSession {
13
13
  sandbox?: Pick<WorkspaceSandbox, 'executeCommand'>;
14
14
  } | undefined;
15
15
  onBeforeAgentEnd(listener: SessionBeforeAgentEndListener): () => void;
16
+ subscribe(listener: (event: AgentControllerEvent) => void): () => void;
16
17
  }
17
18
  export interface FilesystemCaptureDependencies {
18
19
  filesystem: Pick<FilesystemStorage, 'replaceFiles'>;
@@ -1 +1 @@
1
- {"version":3,"file":"filesystem-capture.d.ts","sourceRoot":"","sources":["../../src/session/filesystem-capture.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE/D,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAC/F,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAK5F,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,QAAQ,EAAE;QAAE,aAAa,IAAI,MAAM,CAAA;KAAE,CAAC;IAC/C,QAAQ,CAAC,MAAM,EAAE;QAAE,SAAS,IAAI,MAAM,CAAA;KAAE,CAAC;IACzC,YAAY,IAAI;QAAE,OAAO,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,CAAA;KAAE,GAAG,SAAS,CAAC;IACnF,gBAAgB,CAAC,QAAQ,EAAE,6BAA6B,GAAG,MAAM,IAAI,CAAC;CACvE;AAED,MAAM,WAAW,6BAA6B;IAC5C,UAAU,EAAE,IAAI,CAAC,iBAAiB,EAAE,cAAc,CAAC,CAAC;IACpD,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,gBAAgB,CAAC,CAAC;KAC1E,CAAC;CACH;AAED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E;AAED,MAAM,WAAW,6BAA6B;IAC5C,UAAU,EAAE,IAAI,CAAC,iBAAiB,EAAE,cAAc,CAAC,CAAC;IACpD,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,gBAAgB,CAAC,CAAC;KAC1E,CAAC;CACH;AAED,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,MAAM,GAAG,cAAc,EAAE,CAmB5E;AAED,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,wBAAwB,EACjC,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE,6BAA6B,GAC3D,OAAO,CAAC,IAAI,CAAC,CA2Df;AAYD;;;;;GAKG;AACH,wBAAsB,+BAA+B,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAc3G;AAED,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,wBAAwB,EACjC,YAAY,EAAE,6BAA6B,GAC1C,MAAM,IAAI,CAoFZ"}
@@ -1,3 +1,5 @@
1
+ import { peekSessionSandbox } from "../sandbox/session-sandbox.js";
2
+ import { isMeaningfulToolName } from "./first-exec-capture.js";
1
3
  //#region src/session/filesystem-capture.ts
2
4
  const GIT_STATUS_ARGS = [
3
5
  "status",
@@ -28,10 +30,15 @@ async function captureSessionFilesystem(session, { filesystem, sourceControl })
28
30
  const threadId = session.thread.requireId();
29
31
  const sourceSession = await sourceControl.sessions.getBySessionId(resourceId);
30
32
  const sandbox = session.getWorkspace()?.sandbox;
31
- if (!sourceSession?.sandboxWorkdir || !sandbox?.executeCommand) return;
33
+ if (!sourceSession || !sandbox?.executeCommand) return;
34
+ const entry = peekSessionSandbox(sourceSession.id);
35
+ if (!entry) return;
36
+ if (entry.sandbox.status !== "running") return;
37
+ const workdir = entry.workdir;
38
+ if (!workdir) return;
32
39
  const result = await sandbox.executeCommand("git", [
33
40
  "-C",
34
- sourceSession.sandboxWorkdir,
41
+ workdir,
35
42
  ...GIT_STATUS_ARGS
36
43
  ], { timeout: 3e4 });
37
44
  if (result.exitCode !== 0) {
@@ -42,7 +49,7 @@ async function captureSessionFilesystem(session, { filesystem, sourceControl })
42
49
  "-c",
43
50
  ARTIFACTS_LIST_COMMAND,
44
51
  "sh",
45
- sourceSession.sandboxWorkdir
52
+ workdir
46
53
  ], { timeout: 3e4 });
47
54
  if (artifacts.exitCode !== 0) {
48
55
  console.warn("[Factory filesystem capture] Unable to list workspace artifacts.", artifacts.stderr);
@@ -91,7 +98,37 @@ async function waitForPendingFilesystemCapture(resourceId, timeoutMs = 1e4) {
91
98
  }
92
99
  function observeSessionFilesystem(session, dependencies) {
93
100
  let fallbackChain = Promise.resolve();
94
- return session.onBeforeAgentEnd(() => {
101
+ let workspaceTouched = false;
102
+ const toolNames = /* @__PURE__ */ new Map();
103
+ const suspended = /* @__PURE__ */ new Set();
104
+ const unsubscribeEvents = session.subscribe((event) => {
105
+ switch (event.type) {
106
+ case "tool_start":
107
+ toolNames.set(event.toolCallId, event.toolName);
108
+ return;
109
+ case "tool_suspended":
110
+ suspended.add(event.toolCallId);
111
+ return;
112
+ case "tool_suspension_cancelled":
113
+ toolNames.delete(event.toolCallId);
114
+ suspended.delete(event.toolCallId);
115
+ return;
116
+ case "agent_end":
117
+ for (const id of toolNames.keys()) if (!suspended.has(id)) toolNames.delete(id);
118
+ return;
119
+ case "tool_end": {
120
+ const toolName = toolNames.get(event.toolCallId);
121
+ toolNames.delete(event.toolCallId);
122
+ suspended.delete(event.toolCallId);
123
+ if (event.isError || event.denied) return;
124
+ if (isMeaningfulToolName(toolName)) workspaceTouched = true;
125
+ return;
126
+ }
127
+ }
128
+ });
129
+ const unsubscribeEnd = session.onBeforeAgentEnd(() => {
130
+ if (!workspaceTouched) return;
131
+ workspaceTouched = false;
95
132
  let resourceId;
96
133
  try {
97
134
  resourceId = session.identity.getResourceId();
@@ -105,6 +142,10 @@ function observeSessionFilesystem(session, dependencies) {
105
142
  if (pendingCaptures.get(resourceId) === chain) pendingCaptures.delete(resourceId);
106
143
  });
107
144
  });
145
+ return () => {
146
+ unsubscribeEvents();
147
+ unsubscribeEnd();
148
+ };
108
149
  }
109
150
  //#endregion
110
151
  export { captureSessionFilesystem, observeSessionFilesystem, parseFilesystemCaptureFiles, waitForPendingFilesystemCapture };
@@ -1 +1 @@
1
- {"version":3,"file":"filesystem-capture.js","names":[],"sources":["../../src/session/filesystem-capture.ts"],"sourcesContent":["import type { SessionBeforeAgentEndListener } from '@mastra/core/agent-controller';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\n\nimport type { FilesystemFile, FilesystemStorage } from '../storage/domains/filesystem/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\n\nconst GIT_STATUS_ARGS = ['status', '--porcelain=v1', '-z', '--untracked-files=all'];\nconst ARTIFACTS_LIST_COMMAND = 'cd \"$1\" && test -d .artifacts && find .artifacts -type f -print0 || true';\n\nexport interface FilesystemCaptureSession {\n readonly identity: { getResourceId(): string };\n readonly thread: { requireId(): string };\n getWorkspace(): { sandbox?: Pick<WorkspaceSandbox, 'executeCommand'> } | undefined;\n onBeforeAgentEnd(listener: SessionBeforeAgentEndListener): () => void;\n}\n\nexport interface FilesystemCaptureDependencies {\n filesystem: Pick<FilesystemStorage, 'replaceFiles'>;\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'getBySessionId'>;\n };\n}\n\nexport function parseFilesystemCaptureFiles(output: string): FilesystemFile[] {\n const files = new Map<string, FilesystemFile>();\n const records = output.split('\\0');\n\n for (let index = 0; index < records.length; index += 1) {\n const record = records[index];\n if (!record || record.length < 4) continue;\n\n const code = record.slice(0, 2);\n let path = record.slice(3);\n const moved = code.includes('R') || code.includes('C');\n if (moved) index += 1;\n if (path.startsWith('./')) path = path.slice(2);\n if (!path || (!code.includes('U') && code.includes('D') && !moved)) continue;\n\n files.set(path, { path });\n }\n\n return [...files.values()].toSorted((a, b) => a.path.localeCompare(b.path));\n}\n\nexport async function captureSessionFilesystem(\n session: FilesystemCaptureSession,\n { filesystem, sourceControl }: FilesystemCaptureDependencies,\n): Promise<void> {\n try {\n const resourceId = session.identity.getResourceId();\n const threadId = session.thread.requireId();\n const sourceSession = await sourceControl.sessions.getBySessionId(resourceId);\n // Chat-only sessions run without a workspace; there is nothing to capture.\n const sandbox = session.getWorkspace()?.sandbox;\n if (!sourceSession?.sandboxWorkdir || !sandbox?.executeCommand) return;\n\n const result = await sandbox.executeCommand('git', ['-C', sourceSession.sandboxWorkdir, ...GIT_STATUS_ARGS], {\n timeout: 30_000,\n });\n if (result.exitCode !== 0) {\n console.warn('[Factory filesystem capture] Unable to inspect Git status.', result.stderr);\n return;\n }\n\n const artifacts = await sandbox.executeCommand(\n 'sh',\n ['-c', ARTIFACTS_LIST_COMMAND, 'sh', sourceSession.sandboxWorkdir],\n { timeout: 30_000 },\n );\n if (artifacts.exitCode !== 0) {\n console.warn('[Factory filesystem capture] Unable to list workspace artifacts.', artifacts.stderr);\n return;\n }\n\n const files = new Map(parseFilesystemCaptureFiles(result.stdout).map(file => [file.path, file]));\n for (const path of artifacts.stdout.split('\\0')) {\n const normalizedPath = path.replace(/^\\.\\//, '');\n if (normalizedPath) {\n files.set(normalizedPath, { path: normalizedPath });\n }\n }\n\n await filesystem.replaceFiles({\n resourceId,\n threadId,\n files: [...files.values()].toSorted((a, b) => a.path.localeCompare(b.path)),\n });\n } catch (error) {\n console.warn('[Factory filesystem capture] Unable to persist files.', error);\n }\n}\n\n/**\n * In-flight capture chains keyed by session resource id. Serves two purposes:\n * readers of the persisted file listing (the /web/workspace routes) await the\n * capture for the turn that just ended instead of racing it, and captures for\n * the same resource stay sequential (last write wins) even when multiple\n * scoped sessions observe the same resource id. In-process only: the factory\n * server that runs the session controller also serves those routes.\n */\nconst pendingCaptures = new Map<string, Promise<void>>();\n\n/**\n * Resolve once the session's in-flight filesystem capture (if any) has\n * persisted, or after `timeoutMs` so a reader that arrives mid-capture is\n * never blocked by the execs' worst-case 30s timeouts. Never rejects: the\n * capture body is fully try/catch contained.\n */\nexport async function waitForPendingFilesystemCapture(resourceId: string, timeoutMs = 10_000): Promise<void> {\n const pending = pendingCaptures.get(resourceId);\n if (!pending) return;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n pending,\n new Promise<void>(resolve => {\n timer = setTimeout(resolve, timeoutMs);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport function observeSessionFilesystem(\n session: FilesystemCaptureSession,\n dependencies: FilesystemCaptureDependencies,\n): () => void {\n let fallbackChain = Promise.resolve();\n return session.onBeforeAgentEnd(() => {\n // Chain so captures stay sequential (last write wins), but do NOT return\n // the chain: finishAgentRun awaits every listener before emitting\n // agent_end, and the capture's sandbox execs (git status + artifacts\n // find, 30s timeouts each) must not gate turn completion. Readers that\n // need the fresh listing await the pending capture through\n // waitForPendingFilesystemCapture instead. The un-returned chain cannot\n // leak an unhandled rejection: captureSessionFilesystem's entire body\n // runs inside its own try/catch, and disposal of this listener does not\n // cancel an in-flight chain, so a final turn's capture still persists.\n let resourceId: string | undefined;\n try {\n resourceId = session.identity.getResourceId();\n } catch {\n // No resource id means no route can address this session's listing;\n // keep a per-observer chain so captures still run sequentially.\n fallbackChain = fallbackChain.then(() => captureSessionFilesystem(session, dependencies));\n return;\n }\n // Extend the resource-level chain rather than a per-session one: sessions\n // are deduplicated by (resourceId, scope), so multiple scoped sessions can\n // observe the same resource, and their captures must not interleave.\n const chain = (pendingCaptures.get(resourceId) ?? Promise.resolve()).then(() =>\n captureSessionFilesystem(session, dependencies),\n );\n pendingCaptures.set(resourceId, chain);\n void chain.finally(() => {\n if (pendingCaptures.get(resourceId) === chain) {\n pendingCaptures.delete(resourceId);\n }\n });\n });\n}\n"],"mappings":";AAMA,MAAM,kBAAkB;CAAC;CAAU;CAAkB;CAAM;AAAuB;AAClF,MAAM,yBAAyB;AAgB/B,SAAgB,4BAA4B,QAAkC;CAC5E,MAAM,wBAA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E,yBAAyB,SAAS,YAAY,CAChD;EACA,gBAAgB,IAAI,YAAY,KAAK;EACrC,MAAW,cAAc;GACvB,IAAI,gBAAgB,IAAI,UAAU,MAAM,OACtC,gBAAgB,OAAO,UAAU;EAErC,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"filesystem-capture.js","names":[],"sources":["../../src/session/filesystem-capture.ts"],"sourcesContent":["import type { AgentControllerEvent, SessionBeforeAgentEndListener } from '@mastra/core/agent-controller';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport { peekSessionSandbox } from '../sandbox/session-sandbox.js';\n\nimport type { FilesystemFile, FilesystemStorage } from '../storage/domains/filesystem/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { isMeaningfulToolName } from './first-exec-capture.js';\n\nconst GIT_STATUS_ARGS = ['status', '--porcelain=v1', '-z', '--untracked-files=all'];\nconst ARTIFACTS_LIST_COMMAND = 'cd \"$1\" && test -d .artifacts && find .artifacts -type f -print0 || true';\n\nexport interface FilesystemCaptureSession {\n readonly identity: { getResourceId(): string };\n readonly thread: { requireId(): string };\n getWorkspace(): { sandbox?: Pick<WorkspaceSandbox, 'executeCommand'> } | undefined;\n onBeforeAgentEnd(listener: SessionBeforeAgentEndListener): () => void;\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\nexport interface FilesystemCaptureDependencies {\n filesystem: Pick<FilesystemStorage, 'replaceFiles'>;\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'getBySessionId'>;\n };\n}\n\nexport function parseFilesystemCaptureFiles(output: string): FilesystemFile[] {\n const files = new Map<string, FilesystemFile>();\n const records = output.split('\\0');\n\n for (let index = 0; index < records.length; index += 1) {\n const record = records[index];\n if (!record || record.length < 4) continue;\n\n const code = record.slice(0, 2);\n let path = record.slice(3);\n const moved = code.includes('R') || code.includes('C');\n if (moved) index += 1;\n if (path.startsWith('./')) path = path.slice(2);\n if (!path || (!code.includes('U') && code.includes('D') && !moved)) continue;\n\n files.set(path, { path });\n }\n\n return [...files.values()].toSorted((a, b) => a.path.localeCompare(b.path));\n}\n\nexport async function captureSessionFilesystem(\n session: FilesystemCaptureSession,\n { filesystem, sourceControl }: FilesystemCaptureDependencies,\n): Promise<void> {\n try {\n const resourceId = session.identity.getResourceId();\n const threadId = session.thread.requireId();\n const sourceSession = await sourceControl.sessions.getBySessionId(resourceId);\n // Chat-only sessions run without a workspace; there is nothing to capture.\n const sandbox = session.getWorkspace()?.sandbox;\n if (!sourceSession || !sandbox?.executeCommand) return;\n // The live workdir comes from the per-process memo (the deterministic\n // truth) ONLY — never the persisted observability column, which a row\n // written under a previous provider can point at a workdir that no\n // longer exists (the stale-workdir incident class). No memo entry means\n // no live sandbox worth capturing in this replica; capture is\n // best-effort telemetry, so skip.\n const entry = peekSessionSandbox(sourceSession.id);\n if (!entry) return;\n // Telemetry must never provision a VM: executeCommand lazily starts the\n // sandbox via ensureRunning, so a chat turn that never touched the\n // workspace would otherwise boot (and clone into) a fresh VM just to\n // capture an empty git status. Only capture when the turn already has a\n // running sandbox.\n if (entry.sandbox.status !== 'running') return;\n // Running-but-unresolved should not happen (the start hook resolves the\n // workdir), but capture is best-effort — skip rather than guess.\n const workdir = entry.workdir;\n if (!workdir) return;\n\n const result = await sandbox.executeCommand('git', ['-C', workdir, ...GIT_STATUS_ARGS], {\n timeout: 30_000,\n });\n if (result.exitCode !== 0) {\n console.warn('[Factory filesystem capture] Unable to inspect Git status.', result.stderr);\n return;\n }\n\n const artifacts = await sandbox.executeCommand('sh', ['-c', ARTIFACTS_LIST_COMMAND, 'sh', workdir], {\n timeout: 30_000,\n });\n if (artifacts.exitCode !== 0) {\n console.warn('[Factory filesystem capture] Unable to list workspace artifacts.', artifacts.stderr);\n return;\n }\n\n const files = new Map(parseFilesystemCaptureFiles(result.stdout).map(file => [file.path, file]));\n for (const path of artifacts.stdout.split('\\0')) {\n const normalizedPath = path.replace(/^\\.\\//, '');\n if (normalizedPath) {\n files.set(normalizedPath, { path: normalizedPath });\n }\n }\n\n await filesystem.replaceFiles({\n resourceId,\n threadId,\n files: [...files.values()].toSorted((a, b) => a.path.localeCompare(b.path)),\n });\n } catch (error) {\n console.warn('[Factory filesystem capture] Unable to persist files.', error);\n }\n}\n\n/**\n * In-flight capture chains keyed by session resource id. Serves two purposes:\n * readers of the persisted file listing (the /web/workspace routes) await the\n * capture for the turn that just ended instead of racing it, and captures for\n * the same resource stay sequential (last write wins) even when multiple\n * scoped sessions observe the same resource id. In-process only: the factory\n * server that runs the session controller also serves those routes.\n */\nconst pendingCaptures = new Map<string, Promise<void>>();\n\n/**\n * Resolve once the session's in-flight filesystem capture (if any) has\n * persisted, or after `timeoutMs` so a reader that arrives mid-capture is\n * never blocked by the execs' worst-case 30s timeouts. Never rejects: the\n * capture body is fully try/catch contained.\n */\nexport async function waitForPendingFilesystemCapture(resourceId: string, timeoutMs = 10_000): Promise<void> {\n const pending = pendingCaptures.get(resourceId);\n if (!pending) return;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n pending,\n new Promise<void>(resolve => {\n timer = setTimeout(resolve, timeoutMs);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport function observeSessionFilesystem(\n session: FilesystemCaptureSession,\n dependencies: FilesystemCaptureDependencies,\n): () => void {\n let fallbackChain = Promise.resolve();\n // Capture only runs after a turn that actually touched the workspace: a\n // successful workspace tool call both proves the sandbox is awake and is\n // the only way the listing can have changed. Without this gate every chat\n // turn would run two sandbox execs — and since executeCommand resumes an\n // idle VM, a pure-chat turn would keep waking a sandbox it never used.\n // Same bookkeeping as first-exec capture: tool names resolve at tool_end\n // via the tool_start map, and suspended calls survive agent_end so a\n // resumed run's eventual completion still counts for that turn.\n let workspaceTouched = false;\n const toolNames = new Map<string, string>();\n const suspended = new Set<string>();\n const unsubscribeEvents = session.subscribe(event => {\n switch (event.type) {\n case 'tool_start': {\n toolNames.set(event.toolCallId, event.toolName);\n return;\n }\n case 'tool_suspended': {\n suspended.add(event.toolCallId);\n return;\n }\n case 'tool_suspension_cancelled': {\n toolNames.delete(event.toolCallId);\n suspended.delete(event.toolCallId);\n return;\n }\n case 'agent_end': {\n for (const id of toolNames.keys()) {\n if (!suspended.has(id)) toolNames.delete(id);\n }\n return;\n }\n case 'tool_end': {\n const toolName = toolNames.get(event.toolCallId);\n toolNames.delete(event.toolCallId);\n suspended.delete(event.toolCallId);\n if (event.isError || event.denied) return;\n if (isMeaningfulToolName(toolName)) workspaceTouched = true;\n return;\n }\n }\n });\n const unsubscribeEnd = session.onBeforeAgentEnd(() => {\n // onBeforeAgentEnd fires before agent_end is emitted, so every tool_end\n // of the finishing run has already been observed; read then reset.\n if (!workspaceTouched) return;\n workspaceTouched = false;\n // Chain so captures stay sequential (last write wins), but do NOT return\n // the chain: finishAgentRun awaits every listener before emitting\n // agent_end, and the capture's sandbox execs (git status + artifacts\n // find, 30s timeouts each) must not gate turn completion. Readers that\n // need the fresh listing await the pending capture through\n // waitForPendingFilesystemCapture instead. The un-returned chain cannot\n // leak an unhandled rejection: captureSessionFilesystem's entire body\n // runs inside its own try/catch, and disposal of this listener does not\n // cancel an in-flight chain, so a final turn's capture still persists.\n let resourceId: string | undefined;\n try {\n resourceId = session.identity.getResourceId();\n } catch {\n // No resource id means no route can address this session's listing;\n // keep a per-observer chain so captures still run sequentially.\n fallbackChain = fallbackChain.then(() => captureSessionFilesystem(session, dependencies));\n return;\n }\n // Extend the resource-level chain rather than a per-session one: sessions\n // are deduplicated by (resourceId, scope), so multiple scoped sessions can\n // observe the same resource, and their captures must not interleave.\n const chain = (pendingCaptures.get(resourceId) ?? Promise.resolve()).then(() =>\n captureSessionFilesystem(session, dependencies),\n );\n pendingCaptures.set(resourceId, chain);\n void chain.finally(() => {\n if (pendingCaptures.get(resourceId) === chain) {\n pendingCaptures.delete(resourceId);\n }\n });\n });\n return () => {\n unsubscribeEvents();\n unsubscribeEnd();\n };\n}\n"],"mappings":";;;AAQA,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11
  sessions: Pick<SourceControlStorageHandle['sessions'], 'markFirstMeaningfulExec'>;
12
12
  };
13
13
  }
14
+ export declare function isMeaningfulToolName(name: string | undefined): boolean;
14
15
  /**
15
16
  * Record when a session's agent completed its first successful meaningful
16
17
  * tool call (the TTFME anchor — "time to first meaningful exec").
@@ -1 +1 @@
1
- {"version":3,"file":"first-exec-capture.d.ts","sourceRoot":"","sources":["../../src/session/first-exec-capture.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAG1E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAE5F,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,QAAQ,EAAE;QAAE,aAAa,IAAI,MAAM,CAAA;KAAE,CAAC;IAC/C,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACxE;AAED,MAAM,WAAW,4BAA4B;IAC3C,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,yBAAyB,CAAC,CAAC;KACnF,CAAC;CACH;AAmCD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,uBAAuB,EAChC,EAAE,aAAa,EAAE,EAAE,4BAA4B,GAC9C,MAAM,IAAI,CAoDZ"}
1
+ {"version":3,"file":"first-exec-capture.d.ts","sourceRoot":"","sources":["../../src/session/first-exec-capture.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAG1E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAE5F,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,QAAQ,EAAE;QAAE,aAAa,IAAI,MAAM,CAAA;KAAE,CAAC;IAC/C,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACxE;AAED,MAAM,WAAW,4BAA4B;IAC3C,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,yBAAyB,CAAC,CAAC;KACnF,CAAC;CACH;AA6BD,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAItE;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,uBAAuB,EAChC,EAAE,aAAa,EAAE,EAAE,4BAA4B,GAC9C,MAAM,IAAI,CAoDZ"}
@@ -86,6 +86,6 @@ function observeSessionFirstExec(session, { sourceControl }) {
86
86
  return unsubscribe;
87
87
  }
88
88
  //#endregion
89
- export { observeSessionFirstExec };
89
+ export { isMeaningfulToolName, observeSessionFirstExec };
90
90
 
91
91
  //# sourceMappingURL=first-exec-capture.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"first-exec-capture.js","names":[],"sources":["../../src/session/first-exec-capture.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\nimport { WORKSPACE_TOOLS_PREFIX } from '@mastra/core/workspace';\n\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\n\nexport interface FirstExecCaptureSession {\n readonly identity: { getResourceId(): string };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\nexport interface FirstExecCaptureDependencies {\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'markFirstMeaningfulExec'>;\n };\n}\n\n/**\n * Tool names that count as \"meaningful exec\" independent of the workspace\n * prefix. The workspace tools get remapped from `mastra_workspace_*` to\n * mastracode-friendly names (see `mastracode/sdk/src/tool-names.ts`), and\n * this listener runs on the emitted tool name after remap, so both spellings\n * need to match.\n */\nconst MEANINGFUL_TOOL_NAMES: ReadonlySet<string> = new Set([\n // Filesystem (post-remap)\n 'view',\n 'write_file',\n 'string_replace_lsp',\n 'find_files',\n 'delete_file',\n 'file_stat',\n 'mkdir',\n // Search\n 'search_content',\n // Code intelligence\n 'ast_smart_edit',\n 'lsp_inspect',\n // Sandbox\n 'execute_command',\n 'get_process_output',\n 'kill_process',\n]);\n\nfunction isMeaningfulToolName(name: string | undefined): boolean {\n if (!name) return false;\n if (name.startsWith(`${WORKSPACE_TOOLS_PREFIX}_`)) return true;\n return MEANINGFUL_TOOL_NAMES.has(name);\n}\n\n/**\n * Record when a session's agent completed its first successful meaningful\n * tool call (the TTFME anchor — \"time to first meaningful exec\").\n *\n * Meaningful = a workspace tool the agent invoked itself (filesystem,\n * search, code intelligence, sandbox exec, process control). We accept any\n * tool whose name starts with the workspace prefix `mastra_workspace_` or\n * matches the post-remap mastracode tool names. Non-workspace tools (memory,\n * notification inbox, subagent, etc.) and skill-loader / preflight /\n * materializer `sandbox.executeCommand()` calls that never flow through the\n * tool layer are intentionally excluded.\n *\n * Failed tool calls (`isError === true`) don't count. Approval-denied and\n * abort-while-parked tool completions (`denied === true`) also don't count:\n * the run-engine emits `tool_end` with `isError: false` for those paths\n * because the tool didn't fail, but it also never ran, so treating them as\n * \"meaningful exec\" would re-introduce the same contamination this fix is\n * removing on the message side. The listener stays subscribed until a\n * successful qualifying end, then unsubscribes. The storage write is guarded\n * (`first_meaningful_exec_at IS NULL`), so restarts, re-materialized\n * sessions, and sessions without a source-control row are no-ops.\n */\nexport function observeSessionFirstExec(\n session: FirstExecCaptureSession,\n { sourceControl }: FirstExecCaptureDependencies,\n): () => void {\n let seen = false;\n // toolCallId -> toolName. Populated on `tool_start`, consumed on `tool_end`.\n // Suspended entries survive `agent_end` so the resumed run can still resolve\n // its tool name when the eventual `tool_end` arrives.\n const toolNames = new Map<string, string>();\n const suspended = new Set<string>();\n const unsubscribe = session.subscribe(event => {\n if (seen) return;\n switch (event.type) {\n case 'tool_start': {\n toolNames.set(event.toolCallId, event.toolName);\n return;\n }\n case 'tool_suspended': {\n suspended.add(event.toolCallId);\n return;\n }\n case 'tool_suspension_cancelled': {\n toolNames.delete(event.toolCallId);\n suspended.delete(event.toolCallId);\n return;\n }\n case 'agent_end': {\n // Drop any in-flight starts that will never see a matching `tool_end`\n // on this run. Genuinely suspended calls stay so their eventual\n // resume-time `tool_end` can still map back to a tool name. Without\n // this, sessions that repeatedly abort or error before a qualifying\n // completion would accumulate stale entries for the entire lifetime\n // of the subscription.\n for (const id of toolNames.keys()) {\n if (!suspended.has(id)) toolNames.delete(id);\n }\n return;\n }\n case 'tool_end': {\n const toolName = toolNames.get(event.toolCallId);\n toolNames.delete(event.toolCallId);\n suspended.delete(event.toolCallId);\n if (event.isError) return;\n if (event.denied) return;\n if (!isMeaningfulToolName(toolName)) return;\n seen = true;\n unsubscribe();\n void sourceControl.sessions\n .markFirstMeaningfulExec({ sessionId: session.identity.getResourceId() })\n .catch(error => console.warn('[Factory first-exec capture] Unable to persist first exec time.', error));\n return;\n }\n }\n });\n return unsubscribe;\n}\n"],"mappings":";;;;;;;;;AAuBA,MAAM,wCAA6C,IAAI,IAAI;CAEzD;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CAEA;CACA;CAEA;CACA;CACA;AACF,CAAC;AAED,SAAS,qBAAqB,MAAmC;CAC/D,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,KAAK,WAAW,GAAG,uBAAuB,EAAE,GAAG,OAAO;CAC1D,OAAO,sBAAsB,IAAI,IAAI;AACvC;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,wBACd,SACA,EAAE,iBACU;CACZ,IAAI,OAAO;CAIX,MAAM,4BAAY,IAAI,IAAoB;CAC1C,MAAM,4BAAY,IAAI,IAAY;CAClC,MAAM,cAAc,QAAQ,WAAU,UAAS;EAC7C,IAAI,MAAM;EACV,QAAQ,MAAM,MAAd;GACE,KAAK;IACH,UAAU,IAAI,MAAM,YAAY,MAAM,QAAQ;IAC9C;GAEF,KAAK;IACH,UAAU,IAAI,MAAM,UAAU;IAC9B;GAEF,KAAK;IACH,UAAU,OAAO,MAAM,UAAU;IACjC,UAAU,OAAO,MAAM,UAAU;IACjC;GAEF,KAAK;IAOH,KAAK,MAAM,MAAM,UAAU,KAAK,GAC9B,IAAI,CAAC,UAAU,IAAI,EAAE,GAAG,UAAU,OAAO,EAAE;IAE7C;GAEF,KAAK,YAAY;IACf,MAAM,WAAW,UAAU,IAAI,MAAM,UAAU;IAC/C,UAAU,OAAO,MAAM,UAAU;IACjC,UAAU,OAAO,MAAM,UAAU;IACjC,IAAI,MAAM,SAAS;IACnB,IAAI,MAAM,QAAQ;IAClB,IAAI,CAAC,qBAAqB,QAAQ,GAAG;IACrC,OAAO;IACP,YAAY;IACZ,cAAmB,SAChB,wBAAwB,EAAE,WAAW,QAAQ,SAAS,cAAc,EAAE,CAAC,CAAC,CACxE,OAAM,UAAS,QAAQ,KAAK,mEAAmE,KAAK,CAAC;IACxG;GACF;EACF;CACF,CAAC;CACD,OAAO;AACT"}
1
+ {"version":3,"file":"first-exec-capture.js","names":[],"sources":["../../src/session/first-exec-capture.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\nimport { WORKSPACE_TOOLS_PREFIX } from '@mastra/core/workspace';\n\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\n\nexport interface FirstExecCaptureSession {\n readonly identity: { getResourceId(): string };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\nexport interface FirstExecCaptureDependencies {\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'markFirstMeaningfulExec'>;\n };\n}\n\n/**\n * Tool names that count as \"meaningful exec\" independent of the workspace\n * prefix. The workspace tools get remapped from `mastra_workspace_*` to\n * mastracode-friendly names (see `mastracode/sdk/src/tool-names.ts`), and\n * this listener runs on the emitted tool name after remap, so both spellings\n * need to match.\n */\nconst MEANINGFUL_TOOL_NAMES: ReadonlySet<string> = new Set([\n // Filesystem (post-remap)\n 'view',\n 'write_file',\n 'string_replace_lsp',\n 'find_files',\n 'delete_file',\n 'file_stat',\n 'mkdir',\n // Search\n 'search_content',\n // Code intelligence\n 'ast_smart_edit',\n 'lsp_inspect',\n // Sandbox\n 'execute_command',\n 'get_process_output',\n 'kill_process',\n]);\n\nexport function isMeaningfulToolName(name: string | undefined): boolean {\n if (!name) return false;\n if (name.startsWith(`${WORKSPACE_TOOLS_PREFIX}_`)) return true;\n return MEANINGFUL_TOOL_NAMES.has(name);\n}\n\n/**\n * Record when a session's agent completed its first successful meaningful\n * tool call (the TTFME anchor — \"time to first meaningful exec\").\n *\n * Meaningful = a workspace tool the agent invoked itself (filesystem,\n * search, code intelligence, sandbox exec, process control). We accept any\n * tool whose name starts with the workspace prefix `mastra_workspace_` or\n * matches the post-remap mastracode tool names. Non-workspace tools (memory,\n * notification inbox, subagent, etc.) and skill-loader / preflight /\n * materializer `sandbox.executeCommand()` calls that never flow through the\n * tool layer are intentionally excluded.\n *\n * Failed tool calls (`isError === true`) don't count. Approval-denied and\n * abort-while-parked tool completions (`denied === true`) also don't count:\n * the run-engine emits `tool_end` with `isError: false` for those paths\n * because the tool didn't fail, but it also never ran, so treating them as\n * \"meaningful exec\" would re-introduce the same contamination this fix is\n * removing on the message side. The listener stays subscribed until a\n * successful qualifying end, then unsubscribes. The storage write is guarded\n * (`first_meaningful_exec_at IS NULL`), so restarts, re-materialized\n * sessions, and sessions without a source-control row are no-ops.\n */\nexport function observeSessionFirstExec(\n session: FirstExecCaptureSession,\n { sourceControl }: FirstExecCaptureDependencies,\n): () => void {\n let seen = false;\n // toolCallId -> toolName. Populated on `tool_start`, consumed on `tool_end`.\n // Suspended entries survive `agent_end` so the resumed run can still resolve\n // its tool name when the eventual `tool_end` arrives.\n const toolNames = new Map<string, string>();\n const suspended = new Set<string>();\n const unsubscribe = session.subscribe(event => {\n if (seen) return;\n switch (event.type) {\n case 'tool_start': {\n toolNames.set(event.toolCallId, event.toolName);\n return;\n }\n case 'tool_suspended': {\n suspended.add(event.toolCallId);\n return;\n }\n case 'tool_suspension_cancelled': {\n toolNames.delete(event.toolCallId);\n suspended.delete(event.toolCallId);\n return;\n }\n case 'agent_end': {\n // Drop any in-flight starts that will never see a matching `tool_end`\n // on this run. Genuinely suspended calls stay so their eventual\n // resume-time `tool_end` can still map back to a tool name. Without\n // this, sessions that repeatedly abort or error before a qualifying\n // completion would accumulate stale entries for the entire lifetime\n // of the subscription.\n for (const id of toolNames.keys()) {\n if (!suspended.has(id)) toolNames.delete(id);\n }\n return;\n }\n case 'tool_end': {\n const toolName = toolNames.get(event.toolCallId);\n toolNames.delete(event.toolCallId);\n suspended.delete(event.toolCallId);\n if (event.isError) return;\n if (event.denied) return;\n if (!isMeaningfulToolName(toolName)) return;\n seen = true;\n unsubscribe();\n void sourceControl.sessions\n .markFirstMeaningfulExec({ sessionId: session.identity.getResourceId() })\n .catch(error => console.warn('[Factory first-exec capture] Unable to persist first exec time.', error));\n return;\n }\n }\n });\n return unsubscribe;\n}\n"],"mappings":";;;;;;;;;AAuBA,MAAM,wCAA6C,IAAI,IAAI;CAEzD;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CAEA;CACA;CAEA;CACA;CACA;AACF,CAAC;AAED,SAAgB,qBAAqB,MAAmC;CACtE,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,KAAK,WAAW,GAAG,uBAAuB,EAAE,GAAG,OAAO;CAC1D,OAAO,sBAAsB,IAAI,IAAI;AACvC;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,wBACd,SACA,EAAE,iBACU;CACZ,IAAI,OAAO;CAIX,MAAM,4BAAY,IAAI,IAAoB;CAC1C,MAAM,4BAAY,IAAI,IAAY;CAClC,MAAM,cAAc,QAAQ,WAAU,UAAS;EAC7C,IAAI,MAAM;EACV,QAAQ,MAAM,MAAd;GACE,KAAK;IACH,UAAU,IAAI,MAAM,YAAY,MAAM,QAAQ;IAC9C;GAEF,KAAK;IACH,UAAU,IAAI,MAAM,UAAU;IAC9B;GAEF,KAAK;IACH,UAAU,OAAO,MAAM,UAAU;IACjC,UAAU,OAAO,MAAM,UAAU;IACjC;GAEF,KAAK;IAOH,KAAK,MAAM,MAAM,UAAU,KAAK,GAC9B,IAAI,CAAC,UAAU,IAAI,EAAE,GAAG,UAAU,OAAO,EAAE;IAE7C;GAEF,KAAK,YAAY;IACf,MAAM,WAAW,UAAU,IAAI,MAAM,UAAU;IAC/C,UAAU,OAAO,MAAM,UAAU;IACjC,UAAU,OAAO,MAAM,UAAU;IACjC,IAAI,MAAM,SAAS;IACnB,IAAI,MAAM,QAAQ;IAClB,IAAI,CAAC,qBAAqB,QAAQ,GAAG;IACrC,OAAO;IACP,YAAY;IACZ,cAAmB,SAChB,wBAAwB,EAAE,WAAW,QAAQ,SAAS,cAAc,EAAE,CAAC,CAAC,CACxE,OAAM,UAAS,QAAQ,KAAK,mEAAmE,KAAK,CAAC;IACxG;GACF;EACF;CACF,CAAC;CACD,OAAO;AACT"}
@@ -11,7 +11,7 @@
11
11
  * returned by {@link IntegrationStorage.forIntegration}.
12
12
  *
13
13
  * Source-control integrations additionally use the shared, provider-scoped
14
- * source-control domain for installations, projects, worktrees, and sandboxes.
14
+ * source-control domain for installations, projects, and sessions.
15
15
  *
16
16
  * Payloads (`data` / `config`) are JSON documents typed per-integration via
17
17
  * the handle's generics. JSON round-trips exactly what JSON can represent:
@@ -14,7 +14,7 @@ import { FactoryStorageDomain, UniqueViolationError } from "@mastra/core/storage
14
14
  * returned by {@link IntegrationStorage.forIntegration}.
15
15
  *
16
16
  * Source-control integrations additionally use the shared, provider-scoped
17
- * source-control domain for installations, projects, worktrees, and sandboxes.
17
+ * source-control domain for installations, projects, and sessions.
18
18
  *
19
19
  * Payloads (`data` / `config`) are JSON documents typed per-integration via
20
20
  * the handle's generics. JSON round-trips exactly what JSON can represent:
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":["#migrateValue","#db"],"sources":["../../../../src/storage/domains/integrations/base.ts"],"sourcesContent":["/**\n * Generic integration storage — the default persistence surface for\n * `FactoryIntegration`s.\n *\n * Most integrations persist the same three shapes: an org-owned OAuth\n * **connection**, **subscriptions** binding external objects to\n * sessions/threads, and per-`(org, user)` **settings**. This built-in domain\n * stores all three in shared collections keyed by `integration_id`, so an\n * integration author writes zero schema, zero DDL, and zero queries — and\n * org scoping is enforced by construction through the pre-scoped handle\n * returned by {@link IntegrationStorage.forIntegration}.\n *\n * Source-control integrations additionally use the shared, provider-scoped\n * source-control domain for installations, projects, worktrees, and sandboxes.\n *\n * Payloads (`data` / `config`) are JSON documents typed per-integration via\n * the handle's generics. JSON round-trips exactly what JSON can represent:\n * store timestamps inside payloads as epoch millis or ISO strings, not\n * `Date`s.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\nimport { createPlaintextFactorySecretEncryption } from '../../../secret-encryption.js';\nimport type { FactorySecretEncryption } from '../../../secret-encryption.js';\n\nexport const INTEGRATION_CONNECTIONS_SCHEMA: CollectionSchema = {\n name: 'integration_connections',\n columns: {\n id: { type: 'uuid-pk' },\n integration_id: { type: 'text' },\n org_id: { type: 'text' },\n /** Who connected it (audit only — never scopes reads). */\n user_id: { type: 'text', nullable: true },\n data: { type: 'json' },\n metadata: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'integration_connections_integration_org_unique', columns: ['integration_id', 'org_id'] }],\n};\n\nexport const INTEGRATION_SUBSCRIPTIONS_SCHEMA: CollectionSchema = {\n name: 'integration_subscriptions',\n columns: {\n id: { type: 'uuid-pk' },\n integration_id: { type: 'text' },\n org_id: { type: 'text' },\n /** Canonical external-object key the integration derives (e.g. `pr:{installation}:{repo}:{number}`). */\n target_key: { type: 'text' },\n session_id: { type: 'text', nullable: true },\n resource_id: { type: 'text', nullable: true },\n thread_id: { type: 'text', nullable: true },\n session_scope: { type: 'text', nullable: true },\n status: { type: 'text' },\n data: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [\n { name: 'integration_subscriptions_target_idx', columns: ['integration_id', 'target_key'] },\n { name: 'integration_subscriptions_org_idx', columns: ['integration_id', 'org_id'] },\n ],\n};\n\nexport const INTEGRATION_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'integration_settings',\n columns: {\n id: { type: 'uuid-pk' },\n integration_id: { type: 'text' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'integration_settings_integration_org_user_unique', columns: ['integration_id', 'org_id', 'user_id'] },\n ],\n};\n\n/** An integration's org-owned connection (typically the OAuth grant). */\nexport interface IntegrationConnection<TData> {\n id: string;\n orgId: string;\n /** Who connected it (audit only). */\n userId: string | null;\n data: TData;\n metadata: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** A subscription binding an external object to a session/thread. */\nexport interface IntegrationSubscription<TData> {\n id: string;\n orgId: string;\n targetKey: string;\n sessionId: string | null;\n resourceId: string | null;\n threadId: string | null;\n sessionScope: string | null;\n status: string;\n data: TData;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport type CreateIntegrationSubscriptionInput<TData> = {\n orgId: string;\n targetKey: string;\n sessionId?: string | null;\n resourceId?: string | null;\n threadId?: string | null;\n sessionScope?: string | null;\n /** Defaults to `'active'`. */\n status?: string;\n} & ({} extends TData ? { data?: TData } : { data: TData });\n\n/**\n * Typed query surface pre-scoped to one `integration_id`. Every read and\n * write is automatically filtered/stamped with the integration id, so an\n * integration cannot reach another integration's rows.\n */\nexport interface IntegrationStorageHandle<\n TConnection = Record<string, unknown>,\n TSettings = Record<string, unknown>,\n TSubscription = Record<string, unknown>,\n> {\n readonly integrationId: string;\n connections: {\n /** The org's connection, or `null` when not connected. */\n get(orgId: string): Promise<IntegrationConnection<TConnection> | null>;\n /** Insert or replace the org's connection (one per org; `created_at` preserved on update). */\n upsert(\n orgId: string,\n input: { userId?: string | null; data: TConnection; metadata?: Record<string, unknown> },\n ): Promise<void>;\n /**\n * Atomic read-modify-write of the connection's `data` payload (token\n * rotation etc.). Returns the updated connection, or `null` when the org\n * has no connection.\n */\n update(orgId: string, fn: (data: TConnection) => TConnection): Promise<IntegrationConnection<TConnection> | null>;\n /** Remove the org's connection. Returns whether a row was deleted. */\n delete(orgId: string): Promise<boolean>;\n };\n subscriptions: {\n create(input: CreateIntegrationSubscriptionInput<TSubscription>): Promise<IntegrationSubscription<TSubscription>>;\n /** All subscriptions for an external object (webhook fan-out), optionally filtered by status. */\n listByTarget(targetKey: string, opts?: { status?: string }): Promise<IntegrationSubscription<TSubscription>[]>;\n listBySession(sessionId: string): Promise<IntegrationSubscription<TSubscription>[]>;\n listByThread(resourceId: string, threadId: string): Promise<IntegrationSubscription<TSubscription>[]>;\n updateStatus(id: string, status: string): Promise<void>;\n delete(id: string): Promise<boolean>;\n /** Targeted cleanup, always org-scoped. Returns the number of rows deleted. */\n deleteWhere(where: { orgId: string; targetKey?: string; sessionId?: string }): Promise<number>;\n };\n settings: {\n /** The `(org, user)` config, or `null` when never saved. */\n get(orgId: string, userId: string): Promise<TSettings | null>;\n /** Upsert the `(org, user)` config (`created_at` preserved on update). */\n save(orgId: string, userId: string, config: TSettings): Promise<void>;\n };\n}\n\ninterface ConnectionRow extends Record<string, unknown> {\n id: string;\n integration_id: string;\n org_id: string;\n user_id: string | null;\n data: unknown;\n metadata: Record<string, unknown>;\n created_at: Date;\n updated_at: Date;\n}\n\ninterface SubscriptionRow extends Record<string, unknown> {\n id: string;\n integration_id: string;\n org_id: string;\n target_key: string;\n session_id: string | null;\n resource_id: string | null;\n thread_id: string | null;\n session_scope: string | null;\n status: string;\n data: unknown;\n created_at: Date;\n updated_at: Date;\n}\n\n/**\n * The built-in generic integration domain, written once against the\n * `FactoryStorageOps` surface — works on any `FactoryStorage` backend.\n */\nexport class IntegrationStorage extends FactoryStorageDomain {\n constructor(\n private readonly encryption: FactorySecretEncryption = createPlaintextFactorySecretEncryption(),\n ) {\n super('integrations');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n INTEGRATION_CONNECTIONS_SCHEMA,\n INTEGRATION_SUBSCRIPTIONS_SCHEMA,\n INTEGRATION_SETTINGS_SCHEMA,\n ]);\n const [connections, settings] = await Promise.all([\n this.ops.findMany<ConnectionRow>('integration_connections', {}),\n this.ops.findMany<{ id: string; config: unknown }>('integration_settings', {}),\n ]);\n await Promise.all([\n ...connections.map(row => this.#migrateValue('integration_connections', row.id, 'data')),\n ...settings.map(row => this.#migrateValue('integration_settings', row.id, 'config')),\n ]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('integration_subscriptions', {});\n await this.ops.deleteMany('integration_settings', {});\n await this.ops.deleteMany('integration_connections', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async #migrateValue(collection: string, id: string, column: 'data' | 'config'): Promise<void> {\n await this.#db.updateAtomic<Record<string, unknown>>(collection, { id }, async row => {\n const decrypted = await this.encryption.decrypt(row[column]);\n return decrypted.needsReencryption ? { [column]: await this.encryption.encrypt(decrypted.value) } : null;\n });\n }\n\n /** A typed handle pre-scoped to `integrationId`. */\n forIntegration<\n TConnection = Record<string, unknown>,\n TSettings = Record<string, unknown>,\n TSubscription = Record<string, unknown>,\n >(integrationId: string): IntegrationStorageHandle<TConnection, TSettings, TSubscription> {\n if (!integrationId) throw new Error('[IntegrationStorage] integrationId is required.');\n const db = () => this.#db;\n const scoped = { integration_id: integrationId };\n\n const mapConnection = async (row: ConnectionRow): Promise<IntegrationConnection<TConnection>> => ({\n id: row.id,\n orgId: row.org_id,\n userId: row.user_id,\n data: (await this.encryption.decrypt<TConnection>(row.data)).value,\n metadata: row.metadata ?? {},\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n });\n\n const mapSubscription = (row: SubscriptionRow): IntegrationSubscription<TSubscription> => ({\n id: row.id,\n orgId: row.org_id,\n targetKey: row.target_key,\n sessionId: row.session_id,\n resourceId: row.resource_id,\n threadId: row.thread_id,\n sessionScope: row.session_scope,\n status: row.status,\n data: row.data as TSubscription,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n });\n\n return {\n integrationId,\n connections: {\n get: async orgId => {\n const row = await db().findOne<ConnectionRow>('integration_connections', { ...scoped, org_id: orgId });\n return row ? mapConnection(row) : null;\n },\n upsert: async (orgId, input) => {\n const where = { ...scoped, org_id: orgId };\n const encrypted = await this.encryption.encrypt(input.data);\n const update = async () =>\n db().updateMany('integration_connections', where, {\n user_id: input.userId ?? null,\n data: encrypted,\n metadata: input.metadata ?? {},\n updated_at: new Date(),\n });\n\n let lastError: unknown;\n for (let attempt = 0; attempt < 2; attempt++) {\n if ((await update()) > 0) return;\n\n const now = new Date();\n try {\n await db().insertOne<ConnectionRow>('integration_connections', {\n ...where,\n user_id: input.userId ?? null,\n data: encrypted,\n metadata: input.metadata ?? {},\n created_at: now,\n updated_at: now,\n });\n return;\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n lastError = error;\n }\n }\n throw lastError;\n },\n update: async (orgId, fn) => {\n const row = await db().updateAtomic<ConnectionRow>(\n 'integration_connections',\n { ...scoped, org_id: orgId },\n async current => {\n const data = (await this.encryption.decrypt<TConnection>(current.data)).value;\n return { data: await this.encryption.encrypt(fn(data)), updated_at: new Date() };\n },\n );\n return row ? mapConnection(row) : null;\n },\n delete: async orgId => {\n const deleted = await db().deleteMany('integration_connections', { ...scoped, org_id: orgId });\n return deleted > 0;\n },\n },\n subscriptions: {\n create: async input => {\n const now = new Date();\n const row = await db().insertOne<SubscriptionRow>('integration_subscriptions', {\n ...scoped,\n org_id: input.orgId,\n target_key: input.targetKey,\n session_id: input.sessionId ?? null,\n resource_id: input.resourceId ?? null,\n thread_id: input.threadId ?? null,\n session_scope: input.sessionScope ?? null,\n status: input.status ?? 'active',\n data: input.data ?? {},\n created_at: now,\n updated_at: now,\n });\n return mapSubscription(row);\n },\n listByTarget: async (targetKey, opts) => {\n const rows = await db().findMany<SubscriptionRow>(\n 'integration_subscriptions',\n { ...scoped, target_key: targetKey, ...(opts?.status !== undefined ? { status: opts.status } : {}) },\n { orderBy: [['created_at', 'asc']] },\n );\n return rows.map(mapSubscription);\n },\n listBySession: async sessionId => {\n const rows = await db().findMany<SubscriptionRow>(\n 'integration_subscriptions',\n { ...scoped, session_id: sessionId },\n { orderBy: [['created_at', 'asc']] },\n );\n return rows.map(mapSubscription);\n },\n listByThread: async (resourceId, threadId) => {\n const rows = await db().findMany<SubscriptionRow>(\n 'integration_subscriptions',\n { ...scoped, resource_id: resourceId, thread_id: threadId },\n { orderBy: [['created_at', 'asc']] },\n );\n return rows.map(mapSubscription);\n },\n updateStatus: async (id, status) => {\n await db().updateMany('integration_subscriptions', { ...scoped, id }, { status, updated_at: new Date() });\n },\n delete: async id => {\n const deleted = await db().deleteMany('integration_subscriptions', { ...scoped, id });\n return deleted > 0;\n },\n deleteWhere: async where => {\n return db().deleteMany('integration_subscriptions', {\n ...scoped,\n org_id: where.orgId,\n ...(where.targetKey !== undefined ? { target_key: where.targetKey } : {}),\n ...(where.sessionId !== undefined ? { session_id: where.sessionId } : {}),\n });\n },\n },\n settings: {\n get: async (orgId, userId) => {\n const row = await db().findOne<{ config: unknown }>('integration_settings', {\n ...scoped,\n org_id: orgId,\n user_id: userId,\n });\n return row ? (await this.encryption.decrypt<TSettings>(row.config)).value : null;\n },\n save: async (orgId, userId, config) => {\n const where = { ...scoped, org_id: orgId, user_id: userId };\n const encrypted = await this.encryption.encrypt(config);\n const update = async () =>\n db().updateMany('integration_settings', where, {\n config: encrypted,\n updated_at: new Date(),\n });\n\n let lastError: unknown;\n for (let attempt = 0; attempt < 2; attempt++) {\n if ((await update()) > 0) return;\n\n const now = new Date();\n try {\n await db().insertOne('integration_settings', {\n ...where,\n config: encrypted,\n created_at: now,\n updated_at: now,\n });\n return;\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n lastError = error;\n }\n }\n throw lastError;\n },\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,iCAAmD;CAC9D,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,gBAAgB,EAAE,MAAM,OAAO;EAC/B,QAAQ,EAAE,MAAM,OAAO;;EAEvB,SAAS;GAAE,MAAM;GAAQ,UAAU;EAAK;EACxC,MAAM,EAAE,MAAM,OAAO;EACrB,UAAU,EAAE,MAAM,OAAO;EACzB,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CAAC;EAAE,MAAM;EAAkD,SAAS,CAAC,kBAAkB,QAAQ;CAAE,CAAC;AACnH;AAEA,MAAa,mCAAqD;CAChE,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,gBAAgB,EAAE,MAAM,OAAO;EAC/B,QAAQ,EAAE,MAAM,OAAO;;EAEvB,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC3C,aAAa;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC5C,WAAW;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC1C,eAAe;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC9C,QAAQ,EAAE,MAAM,OAAO;EACvB,MAAM,EAAE,MAAM,OAAO;EACrB,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,SAAS,CACP;EAAE,MAAM;EAAwC,SAAS,CAAC,kBAAkB,YAAY;CAAE,GAC1F;EAAE,MAAM;EAAqC,SAAS,CAAC,kBAAkB,QAAQ;CAAE,CACrF;AACF;AAEA,MAAa,8BAAgD;CAC3D,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,gB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AM,MAAM,GAAG,CAAC,CAAC,QAA6B,wBAAwB;MAC1E,GAAG;MACH,QAAQ;MACR,SAAS;KACX,CAAC;KACD,OAAO,OAAO,MAAM,KAAK,WAAW,QAAmB,IAAI,MAAM,EAAA,CAAG,QAAQ;IAC9E;IACA,MAAM,OAAO,OAAO,QAAQ,WAAW;KACrC,MAAM,QAAQ;MAAE,GAAG;MAAQ,QAAQ;MAAO,SAAS;KAAO;KAC1D,MAAM,YAAY,MAAM,KAAK,WAAW,QAAQ,MAAM;KACtD,MAAM,SAAS,YACb,GAAG,CAAC,CAAC,WAAW,wBAAwB,OAAO;MAC7C,QAAQ;MACR,4BAAY,IAAI,KAAK;KACvB,CAAC;KAEH,IAAI;KACJ,KAAK,IAAI,UAAU,GAAG,UAAU,GAAG,WAAW;MAC5C,IAAK,MAAM,OAAO,IAAK,GAAG;MAE1B,MAAM,sBAAM,IAAI,KAAK;MACrB,IAAI;OACF,MAAM,GAAG,CAAC,CAAC,UAAU,wBAAwB;QAC3C,GAAG;QACH,QAAQ;QACR,YAAY;QACZ,YAAY;OACd,CAAC;OACD;MACF,SAAS,OAAO;OACd,IAAI,EAAE,iBAAiB,uBAAuB,MAAM;OACpD,YAAY;MACd;KACF;KACA,MAAM;IACR;GACF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"base.js","names":["#migrateValue","#db"],"sources":["../../../../src/storage/domains/integrations/base.ts"],"sourcesContent":["/**\n * Generic integration storage — the default persistence surface for\n * `FactoryIntegration`s.\n *\n * Most integrations persist the same three shapes: an org-owned OAuth\n * **connection**, **subscriptions** binding external objects to\n * sessions/threads, and per-`(org, user)` **settings**. This built-in domain\n * stores all three in shared collections keyed by `integration_id`, so an\n * integration author writes zero schema, zero DDL, and zero queries — and\n * org scoping is enforced by construction through the pre-scoped handle\n * returned by {@link IntegrationStorage.forIntegration}.\n *\n * Source-control integrations additionally use the shared, provider-scoped\n * source-control domain for installations, projects, and sessions.\n *\n * Payloads (`data` / `config`) are JSON documents typed per-integration via\n * the handle's generics. JSON round-trips exactly what JSON can represent:\n * store timestamps inside payloads as epoch millis or ISO strings, not\n * `Date`s.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\nimport { createPlaintextFactorySecretEncryption } from '../../../secret-encryption.js';\nimport type { FactorySecretEncryption } from '../../../secret-encryption.js';\n\nexport const INTEGRATION_CONNECTIONS_SCHEMA: CollectionSchema = {\n name: 'integration_connections',\n columns: {\n id: { type: 'uuid-pk' },\n integration_id: { type: 'text' },\n org_id: { type: 'text' },\n /** Who connected it (audit only — never scopes reads). */\n user_id: { type: 'text', nullable: true },\n data: { type: 'json' },\n metadata: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'integration_connections_integration_org_unique', columns: ['integration_id', 'org_id'] }],\n};\n\nexport const INTEGRATION_SUBSCRIPTIONS_SCHEMA: CollectionSchema = {\n name: 'integration_subscriptions',\n columns: {\n id: { type: 'uuid-pk' },\n integration_id: { type: 'text' },\n org_id: { type: 'text' },\n /** Canonical external-object key the integration derives (e.g. `pr:{installation}:{repo}:{number}`). */\n target_key: { type: 'text' },\n session_id: { type: 'text', nullable: true },\n resource_id: { type: 'text', nullable: true },\n thread_id: { type: 'text', nullable: true },\n session_scope: { type: 'text', nullable: true },\n status: { type: 'text' },\n data: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [\n { name: 'integration_subscriptions_target_idx', columns: ['integration_id', 'target_key'] },\n { name: 'integration_subscriptions_org_idx', columns: ['integration_id', 'org_id'] },\n ],\n};\n\nexport const INTEGRATION_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'integration_settings',\n columns: {\n id: { type: 'uuid-pk' },\n integration_id: { type: 'text' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'integration_settings_integration_org_user_unique', columns: ['integration_id', 'org_id', 'user_id'] },\n ],\n};\n\n/** An integration's org-owned connection (typically the OAuth grant). */\nexport interface IntegrationConnection<TData> {\n id: string;\n orgId: string;\n /** Who connected it (audit only). */\n userId: string | null;\n data: TData;\n metadata: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** A subscription binding an external object to a session/thread. */\nexport interface IntegrationSubscription<TData> {\n id: string;\n orgId: string;\n targetKey: string;\n sessionId: string | null;\n resourceId: string | null;\n threadId: string | null;\n sessionScope: string | null;\n status: string;\n data: TData;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport type CreateIntegrationSubscriptionInput<TData> = {\n orgId: string;\n targetKey: string;\n sessionId?: string | null;\n resourceId?: string | null;\n threadId?: string | null;\n sessionScope?: string | null;\n /** Defaults to `'active'`. */\n status?: string;\n} & ({} extends TData ? { data?: TData } : { data: TData });\n\n/**\n * Typed query surface pre-scoped to one `integration_id`. Every read and\n * write is automatically filtered/stamped with the integration id, so an\n * integration cannot reach another integration's rows.\n */\nexport interface IntegrationStorageHandle<\n TConnection = Record<string, unknown>,\n TSettings = Record<string, unknown>,\n TSubscription = Record<string, unknown>,\n> {\n readonly integrationId: string;\n connections: {\n /** The org's connection, or `null` when not connected. */\n get(orgId: string): Promise<IntegrationConnection<TConnection> | null>;\n /** Insert or replace the org's connection (one per org; `created_at` preserved on update). */\n upsert(\n orgId: string,\n input: { userId?: string | null; data: TConnection; metadata?: Record<string, unknown> },\n ): Promise<void>;\n /**\n * Atomic read-modify-write of the connection's `data` payload (token\n * rotation etc.). Returns the updated connection, or `null` when the org\n * has no connection.\n */\n update(orgId: string, fn: (data: TConnection) => TConnection): Promise<IntegrationConnection<TConnection> | null>;\n /** Remove the org's connection. Returns whether a row was deleted. */\n delete(orgId: string): Promise<boolean>;\n };\n subscriptions: {\n create(input: CreateIntegrationSubscriptionInput<TSubscription>): Promise<IntegrationSubscription<TSubscription>>;\n /** All subscriptions for an external object (webhook fan-out), optionally filtered by status. */\n listByTarget(targetKey: string, opts?: { status?: string }): Promise<IntegrationSubscription<TSubscription>[]>;\n listBySession(sessionId: string): Promise<IntegrationSubscription<TSubscription>[]>;\n listByThread(resourceId: string, threadId: string): Promise<IntegrationSubscription<TSubscription>[]>;\n updateStatus(id: string, status: string): Promise<void>;\n delete(id: string): Promise<boolean>;\n /** Targeted cleanup, always org-scoped. Returns the number of rows deleted. */\n deleteWhere(where: { orgId: string; targetKey?: string; sessionId?: string }): Promise<number>;\n };\n settings: {\n /** The `(org, user)` config, or `null` when never saved. */\n get(orgId: string, userId: string): Promise<TSettings | null>;\n /** Upsert the `(org, user)` config (`created_at` preserved on update). */\n save(orgId: string, userId: string, config: TSettings): Promise<void>;\n };\n}\n\ninterface ConnectionRow extends Record<string, unknown> {\n id: string;\n integration_id: string;\n org_id: string;\n user_id: string | null;\n data: unknown;\n metadata: Record<string, unknown>;\n created_at: Date;\n updated_at: Date;\n}\n\ninterface SubscriptionRow extends Record<string, unknown> {\n id: string;\n integration_id: string;\n org_id: string;\n target_key: string;\n session_id: string | null;\n resource_id: string | null;\n thread_id: string | null;\n session_scope: string | null;\n status: string;\n data: unknown;\n created_at: Date;\n updated_at: Date;\n}\n\n/**\n * The built-in generic integration domain, written once against the\n * `FactoryStorageOps` surface — works on any `FactoryStorage` backend.\n */\nexport class IntegrationStorage extends FactoryStorageDomain {\n constructor(\n private readonly encryption: FactorySecretEncryption = createPlaintextFactorySecretEncryption(),\n ) {\n super('integrations');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n INTEGRATION_CONNECTIONS_SCHEMA,\n INTEGRATION_SUBSCRIPTIONS_SCHEMA,\n INTEGRATION_SETTINGS_SCHEMA,\n ]);\n const [connections, settings] = await Promise.all([\n this.ops.findMany<ConnectionRow>('integration_connections', {}),\n this.ops.findMany<{ id: string; config: unknown }>('integration_settings', {}),\n ]);\n await Promise.all([\n ...connections.map(row => this.#migrateValue('integration_connections', row.id, 'data')),\n ...settings.map(row => this.#migrateValue('integration_settings', row.id, 'config')),\n ]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('integration_subscriptions', {});\n await this.ops.deleteMany('integration_settings', {});\n await this.ops.deleteMany('integration_connections', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async #migrateValue(collection: string, id: string, column: 'data' | 'config'): Promise<void> {\n await this.#db.updateAtomic<Record<string, unknown>>(collection, { id }, async row => {\n const decrypted = await this.encryption.decrypt(row[column]);\n return decrypted.needsReencryption ? { [column]: await this.encryption.encrypt(decrypted.value) } : null;\n });\n }\n\n /** A typed handle pre-scoped to `integrationId`. */\n forIntegration<\n TConnection = Record<string, unknown>,\n TSettings = Record<string, unknown>,\n TSubscription = Record<string, unknown>,\n >(integrationId: string): IntegrationStorageHandle<TConnection, TSettings, TSubscription> {\n if (!integrationId) throw new Error('[IntegrationStorage] integrationId is required.');\n const db = () => this.#db;\n const scoped = { integration_id: integrationId };\n\n const mapConnection = async (row: ConnectionRow): Promise<IntegrationConnection<TConnection>> => ({\n id: row.id,\n orgId: row.org_id,\n userId: row.user_id,\n data: (await this.encryption.decrypt<TConnection>(row.data)).value,\n metadata: row.metadata ?? {},\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n });\n\n const mapSubscription = (row: SubscriptionRow): IntegrationSubscription<TSubscription> => ({\n id: row.id,\n orgId: row.org_id,\n targetKey: row.target_key,\n sessionId: row.session_id,\n resourceId: row.resource_id,\n threadId: row.thread_id,\n sessionScope: row.session_scope,\n status: row.status,\n data: row.data as TSubscription,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n });\n\n return {\n integrationId,\n connections: {\n get: async orgId => {\n const row = await db().findOne<ConnectionRow>('integration_connections', { ...scoped, org_id: orgId });\n return row ? mapConnection(row) : null;\n },\n upsert: async (orgId, input) => {\n const where = { ...scoped, org_id: orgId };\n const encrypted = await this.encryption.encrypt(input.data);\n const update = async () =>\n db().updateMany('integration_connections', where, {\n user_id: input.userId ?? null,\n data: encrypted,\n metadata: input.metadata ?? {},\n updated_at: new Date(),\n });\n\n let lastError: unknown;\n for (let attempt = 0; attempt < 2; attempt++) {\n if ((await update()) > 0) return;\n\n const now = new Date();\n try {\n await db().insertOne<ConnectionRow>('integration_connections', {\n ...where,\n user_id: input.userId ?? null,\n data: encrypted,\n metadata: input.metadata ?? {},\n created_at: now,\n updated_at: now,\n });\n return;\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n lastError = error;\n }\n }\n throw lastError;\n },\n update: async (orgId, fn) => {\n const row = await db().updateAtomic<ConnectionRow>(\n 'integration_connections',\n { ...scoped, org_id: orgId },\n async current => {\n const data = (await this.encryption.decrypt<TConnection>(current.data)).value;\n return { data: await this.encryption.encrypt(fn(data)), updated_at: new Date() };\n },\n );\n return row ? mapConnection(row) : null;\n },\n delete: async orgId => {\n const deleted = await db().deleteMany('integration_connections', { ...scoped, org_id: orgId });\n return deleted > 0;\n },\n },\n subscriptions: {\n create: async input => {\n const now = new Date();\n const row = await db().insertOne<SubscriptionRow>('integration_subscriptions', {\n ...scoped,\n org_id: input.orgId,\n target_key: input.targetKey,\n session_id: input.sessionId ?? null,\n resource_id: input.resourceId ?? null,\n thread_id: input.threadId ?? null,\n session_scope: input.sessionScope ?? null,\n status: input.status ?? 'active',\n data: input.data ?? {},\n created_at: now,\n updated_at: now,\n });\n return mapSubscription(row);\n },\n listByTarget: async (targetKey, opts) => {\n const rows = await db().findMany<SubscriptionRow>(\n 'integration_subscriptions',\n { ...scoped, target_key: targetKey, ...(opts?.status !== undefined ? { status: opts.status } : {}) },\n { orderBy: [['created_at', 'asc']] },\n );\n return rows.map(mapSubscription);\n },\n listBySession: async sessionId => {\n const rows = await db().findMany<SubscriptionRow>(\n 'integration_subscriptions',\n { ...scoped, session_id: sessionId },\n { orderBy: [['created_at', 'asc']] },\n );\n return rows.map(mapSubscription);\n },\n listByThread: async (resourceId, threadId) => {\n const rows = await db().findMany<SubscriptionRow>(\n 'integration_subscriptions',\n { ...scoped, resource_id: resourceId, thread_id: threadId },\n { orderBy: [['created_at', 'asc']] },\n );\n return rows.map(mapSubscription);\n },\n updateStatus: async (id, status) => {\n await db().updateMany('integration_subscriptions', { ...scoped, id }, { status, updated_at: new Date() });\n },\n delete: async id => {\n const deleted = await db().deleteMany('integration_subscriptions', { ...scoped, id });\n return deleted > 0;\n },\n deleteWhere: async where => {\n return db().deleteMany('integration_subscriptions', {\n ...scoped,\n org_id: where.orgId,\n ...(where.targetKey !== undefined ? { target_key: where.targetKey } : {}),\n ...(where.sessionId !== undefined ? { session_id: where.sessionId } : {}),\n });\n },\n },\n settings: {\n get: async (orgId, userId) => {\n const row = await db().findOne<{ config: unknown }>('integration_settings', {\n ...scoped,\n org_id: orgId,\n user_id: userId,\n });\n return row ? (await this.encryption.decrypt<TSettings>(row.config)).value : null;\n },\n save: async (orgId, userId, config) => {\n const where = { ...scoped, org_id: orgId, user_id: userId };\n const encrypted = await this.encryption.encrypt(config);\n const update = async () =>\n db().updateMany('integration_settings', where, {\n config: encrypted,\n updated_at: new Date(),\n });\n\n let lastError: unknown;\n for (let attempt = 0; attempt < 2; attempt++) {\n if ((await update()) > 0) return;\n\n const now = new Date();\n try {\n await db().insertOne('integration_settings', {\n ...where,\n config: encrypted,\n created_at: now,\n updated_at: now,\n });\n return;\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n lastError = error;\n }\n }\n throw lastError;\n },\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,iCAAmD;CAC9D,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,gBAAgB,EAAE,MAAM,OAAO;EAC/B,QAAQ,EAAE,MAAM,OAAO;;EAEvB,SAAS;GAAE,MAAM;GAAQ,UAAU;EAAK;EACxC,MAAM,EAAE,MAAM,OAAO;EACrB,UAAU,EAAE,MA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