@mastra/factory 0.24.0-alpha.9 → 0.24.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 (296) hide show
  1. package/README.md +4 -4
  2. package/dist/environment/build-runner.js +2 -1
  3. package/dist/environment/build-runner.js.map +1 -1
  4. package/dist/environment/build-workflow.js +1 -1
  5. package/dist/environment/build-workflow.js.map +1 -1
  6. package/dist/environment/build.js +16 -14
  7. package/dist/environment/build.js.map +1 -1
  8. package/dist/factory.d.ts.map +1 -1
  9. package/dist/factory.js +111 -19
  10. package/dist/factory.js.map +1 -1
  11. package/dist/integrations/base.d.ts +1 -1
  12. package/dist/integrations/base.d.ts.map +1 -1
  13. package/dist/integrations/github/app-identity.js.map +1 -1
  14. package/dist/integrations/github/integration.js +1 -1
  15. package/dist/integrations/github/integration.js.map +1 -1
  16. package/dist/integrations/github/reconcile-worker.js +1 -1
  17. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  18. package/dist/integrations/github/routes.d.ts +1 -1
  19. package/dist/integrations/github/routes.d.ts.map +1 -1
  20. package/dist/integrations/github/routes.js +24 -13
  21. package/dist/integrations/github/routes.js.map +1 -1
  22. package/dist/integrations/github/rules.d.ts.map +1 -1
  23. package/dist/integrations/github/rules.js +53 -9
  24. package/dist/integrations/github/rules.js.map +1 -1
  25. package/dist/integrations/github/sandbox.js +2 -2
  26. package/dist/integrations/github/sandbox.js.map +1 -1
  27. package/dist/integrations/github/session-subscriptions.d.ts.map +1 -1
  28. package/dist/integrations/github/session-subscriptions.js +1 -2
  29. package/dist/integrations/github/session-subscriptions.js.map +1 -1
  30. package/dist/integrations/github/subscriptions.d.ts +7 -4
  31. package/dist/integrations/github/subscriptions.d.ts.map +1 -1
  32. package/dist/integrations/github/subscriptions.js +5 -5
  33. package/dist/integrations/github/subscriptions.js.map +1 -1
  34. package/dist/integrations/gitlab/api.js.map +1 -1
  35. package/dist/integrations/gitlab/integration.js.map +1 -1
  36. package/dist/integrations/gitlab/reconciliation-config.js +2 -1
  37. package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
  38. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  39. package/dist/integrations/gitlab/routes.js +10 -6
  40. package/dist/integrations/gitlab/routes.js.map +1 -1
  41. package/dist/integrations/gitlab/rules.js.map +1 -1
  42. package/dist/integrations/gitlab/session-subscriptions.d.ts.map +1 -1
  43. package/dist/integrations/gitlab/session-subscriptions.js +1 -2
  44. package/dist/integrations/gitlab/session-subscriptions.js.map +1 -1
  45. package/dist/integrations/gitlab/subscriptions.d.ts +7 -4
  46. package/dist/integrations/gitlab/subscriptions.d.ts.map +1 -1
  47. package/dist/integrations/gitlab/subscriptions.js +5 -5
  48. package/dist/integrations/gitlab/subscriptions.js.map +1 -1
  49. package/dist/integrations/incidentio/api.js.map +1 -1
  50. package/dist/integrations/incidentio/integration.js.map +1 -1
  51. package/dist/integrations/incidentio/rules.js.map +1 -1
  52. package/dist/integrations/issue-reconcile-worker.js +1 -1
  53. package/dist/integrations/issue-reconcile-worker.js.map +1 -1
  54. package/dist/integrations/issue-reconciler.js +1 -1
  55. package/dist/integrations/issue-reconciler.js.map +1 -1
  56. package/dist/integrations/jira/api.js.map +1 -1
  57. package/dist/integrations/jira/integration.js.map +1 -1
  58. package/dist/integrations/jira/rules.js.map +1 -1
  59. package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
  60. package/dist/integrations/linear/agent-tools.js.map +1 -1
  61. package/dist/integrations/linear/integration.js.map +1 -1
  62. package/dist/integrations/linear/rules.js.map +1 -1
  63. package/dist/integrations/platform/api-client.js.map +1 -1
  64. package/dist/integrations/platform/github/event-worker.js +1 -1
  65. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  66. package/dist/integrations/platform/github/integration.js +2 -2
  67. package/dist/integrations/platform/github/integration.js.map +1 -1
  68. package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
  69. package/dist/integrations/platform/gitlab/integration.js.map +1 -1
  70. package/dist/integrations/platform/incidentio/integration.js +2 -1
  71. package/dist/integrations/platform/incidentio/integration.js.map +1 -1
  72. package/dist/integrations/platform/jira/integration.js.map +1 -1
  73. package/dist/integrations/platform/linear/event-worker.js +1 -1
  74. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  75. package/dist/integrations/platform/linear/integration.js.map +1 -1
  76. package/dist/integrations/slack/connect-route.js +1 -1
  77. package/dist/integrations/slack/connect-route.js.map +1 -1
  78. package/dist/integrations/slack/feed-publisher.js +1 -1
  79. package/dist/integrations/slack/feed-publisher.js.map +1 -1
  80. package/dist/integrations/slack/integration.js +1 -1
  81. package/dist/integrations/slack/integration.js.map +1 -1
  82. package/dist/integrations/slack/slack.d.ts +16 -5
  83. package/dist/integrations/slack/slack.d.ts.map +1 -1
  84. package/dist/integrations/slack/slack.js +87 -34
  85. package/dist/integrations/slack/slack.js.map +1 -1
  86. package/dist/integrations/subscription-session.d.ts +0 -1
  87. package/dist/integrations/subscription-session.d.ts.map +1 -1
  88. package/dist/integrations/subscription-session.js +1 -4
  89. package/dist/integrations/subscription-session.js.map +1 -1
  90. package/dist/integrations/workos/integration.js.map +1 -1
  91. package/dist/mcp/routes.d.ts.map +1 -1
  92. package/dist/mcp/routes.js +1 -1
  93. package/dist/mcp/routes.js.map +1 -1
  94. package/dist/packages/_internals/workspace/dist/index.js +18 -1
  95. package/dist/packages/_internals/workspace/dist/index.js.map +1 -1
  96. package/dist/routes/attention-activity.js.map +1 -1
  97. package/dist/routes/attention-parked.js.map +1 -1
  98. package/dist/routes/attention-providers.js.map +1 -1
  99. package/dist/routes/automation-runs.js.map +1 -1
  100. package/dist/routes/config.d.ts +6 -7
  101. package/dist/routes/config.d.ts.map +1 -1
  102. package/dist/routes/config.js +20 -19
  103. package/dist/routes/config.js.map +1 -1
  104. package/dist/routes/contracts.js +1 -1
  105. package/dist/routes/contracts.js.map +1 -1
  106. package/dist/routes/custom-provider-source.js.map +1 -1
  107. package/dist/routes/fs.d.ts +31 -23
  108. package/dist/routes/fs.d.ts.map +1 -1
  109. package/dist/routes/fs.js +218 -64
  110. package/dist/routes/fs.js.map +1 -1
  111. package/dist/routes/intake.js +2 -1
  112. package/dist/routes/intake.js.map +1 -1
  113. package/dist/routes/knowledge.js +1 -1
  114. package/dist/routes/knowledge.js.map +1 -1
  115. package/dist/routes/oauth.js +3 -2
  116. package/dist/routes/oauth.js.map +1 -1
  117. package/dist/routes/projects.d.ts +1 -1
  118. package/dist/routes/projects.d.ts.map +1 -1
  119. package/dist/routes/projects.js +33 -31
  120. package/dist/routes/projects.js.map +1 -1
  121. package/dist/routes/provider-credentials.d.ts.map +1 -1
  122. package/dist/routes/provider-credentials.js +6 -1
  123. package/dist/routes/provider-credentials.js.map +1 -1
  124. package/dist/routes/session-access.d.ts +55 -0
  125. package/dist/routes/session-access.d.ts.map +1 -0
  126. package/dist/routes/session-access.js +165 -0
  127. package/dist/routes/session-access.js.map +1 -0
  128. package/dist/routes/skills.d.ts +2 -4
  129. package/dist/routes/skills.d.ts.map +1 -1
  130. package/dist/routes/skills.js +19 -65
  131. package/dist/routes/skills.js.map +1 -1
  132. package/dist/routes/source-control-sessions.d.ts +6 -1
  133. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  134. package/dist/routes/source-control-sessions.js +95 -12
  135. package/dist/routes/source-control-sessions.js.map +1 -1
  136. package/dist/routes/surface.d.ts +5 -0
  137. package/dist/routes/surface.d.ts.map +1 -1
  138. package/dist/routes/surface.js +10 -4
  139. package/dist/routes/surface.js.map +1 -1
  140. package/dist/routes/tenant-credentials.js.map +1 -1
  141. package/dist/routes/work-items.js.map +1 -1
  142. package/dist/rules/binding-context.js +11 -9
  143. package/dist/rules/binding-context.js.map +1 -1
  144. package/dist/rules/dispatcher.d.ts +1 -1
  145. package/dist/rules/dispatcher.d.ts.map +1 -1
  146. package/dist/rules/dispatcher.js +10 -10
  147. package/dist/rules/dispatcher.js.map +1 -1
  148. package/dist/rules/start-coordinator.d.ts +4 -0
  149. package/dist/rules/start-coordinator.d.ts.map +1 -1
  150. package/dist/rules/start-coordinator.js +36 -4
  151. package/dist/rules/start-coordinator.js.map +1 -1
  152. package/dist/rules/tools.js +2 -2
  153. package/dist/rules/tools.js.map +1 -1
  154. package/dist/rules/transition-service.js.map +1 -1
  155. package/dist/sandbox/callback-factory-sandbox.js.map +1 -1
  156. package/dist/sandbox/local-factory-sandbox.js.map +1 -1
  157. package/dist/sandbox/session-retirement.js.map +1 -1
  158. package/dist/secret-encryption.d.ts.map +1 -1
  159. package/dist/secret-encryption.js +65 -25
  160. package/dist/secret-encryption.js.map +1 -1
  161. package/dist/session/channel-reply-processor.d.ts +7 -6
  162. package/dist/session/channel-reply-processor.d.ts.map +1 -1
  163. package/dist/session/channel-reply-processor.js +9 -9
  164. package/dist/session/channel-reply-processor.js.map +1 -1
  165. package/dist/session/channel-session-link-processor.js +1 -0
  166. package/dist/session/channel-session-link-processor.js.map +1 -1
  167. package/dist/session/credential-policy.d.ts.map +1 -1
  168. package/dist/session/credential-policy.js +7 -6
  169. package/dist/session/credential-policy.js.map +1 -1
  170. package/dist/session/default-model-hydration.d.ts +1 -0
  171. package/dist/session/default-model-hydration.d.ts.map +1 -1
  172. package/dist/session/default-model-hydration.js +3 -2
  173. package/dist/session/default-model-hydration.js.map +1 -1
  174. package/dist/session/environment-state-processor.js +1 -1
  175. package/dist/session/environment-state-processor.js.map +1 -1
  176. package/dist/session/filesystem-capture.d.ts +3 -3
  177. package/dist/session/filesystem-capture.d.ts.map +1 -1
  178. package/dist/session/filesystem-capture.js +16 -17
  179. package/dist/session/filesystem-capture.js.map +1 -1
  180. package/dist/session/first-exec-capture.d.ts +1 -1
  181. package/dist/session/first-exec-capture.d.ts.map +1 -1
  182. package/dist/session/first-exec-capture.js +1 -1
  183. package/dist/session/first-exec-capture.js.map +1 -1
  184. package/dist/session/first-message-capture.d.ts +1 -1
  185. package/dist/session/first-message-capture.d.ts.map +1 -1
  186. package/dist/session/first-message-capture.js +1 -1
  187. package/dist/session/first-message-capture.js.map +1 -1
  188. package/dist/session/live-sessions.d.ts +1 -1
  189. package/dist/session/live-sessions.js +1 -1
  190. package/dist/session/live-sessions.js.map +1 -1
  191. package/dist/session/memory-settings-hydration.d.ts +1 -1
  192. package/dist/session/memory-settings-hydration.d.ts.map +1 -1
  193. package/dist/session/memory-settings-hydration.js +2 -1
  194. package/dist/session/memory-settings-hydration.js.map +1 -1
  195. package/dist/session/resource-migration.d.ts +105 -0
  196. package/dist/session/resource-migration.d.ts.map +1 -0
  197. package/dist/session/resource-migration.js +195 -0
  198. package/dist/session/resource-migration.js.map +1 -0
  199. package/dist/session/session-threads.d.ts +58 -0
  200. package/dist/session/session-threads.d.ts.map +1 -0
  201. package/dist/session/session-threads.js +90 -0
  202. package/dist/session/session-threads.js.map +1 -0
  203. package/dist/session/source-control-tools.js +8 -8
  204. package/dist/session/source-control-tools.js.map +1 -1
  205. package/dist/session/thinking-default.d.ts.map +1 -1
  206. package/dist/session/thinking-default.js +3 -4
  207. package/dist/session/thinking-default.js.map +1 -1
  208. package/dist/session/thread-session-stamp.d.ts +21 -0
  209. package/dist/session/thread-session-stamp.d.ts.map +1 -0
  210. package/dist/session/thread-session-stamp.js +20 -0
  211. package/dist/session/thread-session-stamp.js.map +1 -0
  212. package/dist/session/thread-title-mirror.d.ts +1 -1
  213. package/dist/session/thread-title-mirror.d.ts.map +1 -1
  214. package/dist/session/thread-title-mirror.js +1 -1
  215. package/dist/session/thread-title-mirror.js.map +1 -1
  216. package/dist/skills/service.d.ts +6 -8
  217. package/dist/skills/service.d.ts.map +1 -1
  218. package/dist/skills/service.js +3 -3
  219. package/dist/skills/service.js.map +1 -1
  220. package/dist/spa-static.js.map +1 -1
  221. package/dist/state-signing.js +1 -1
  222. package/dist/state-signing.js.map +1 -1
  223. package/dist/storage/domains/audit/agent-audit.d.ts.map +1 -1
  224. package/dist/storage/domains/audit/agent-audit.js +2 -2
  225. package/dist/storage/domains/audit/agent-audit.js.map +1 -1
  226. package/dist/storage/domains/audit/base.js.map +1 -1
  227. package/dist/storage/domains/audit/domain.js.map +1 -1
  228. package/dist/storage/domains/channel-identity/base.js.map +1 -1
  229. package/dist/storage/domains/comments/base.js.map +1 -1
  230. package/dist/storage/domains/comments/domain.js.map +1 -1
  231. package/dist/storage/domains/comments/feed-context.js.map +1 -1
  232. package/dist/storage/domains/credentials/base.js.map +1 -1
  233. package/dist/storage/domains/custom-providers/base.js.map +1 -1
  234. package/dist/storage/domains/intake/base.js.map +1 -1
  235. package/dist/storage/domains/integrations/base.d.ts +8 -0
  236. package/dist/storage/domains/integrations/base.d.ts.map +1 -1
  237. package/dist/storage/domains/integrations/base.js +7 -0
  238. package/dist/storage/domains/integrations/base.js.map +1 -1
  239. package/dist/storage/domains/memory-settings/base.js.map +1 -1
  240. package/dist/storage/domains/model-defaults/base.js.map +1 -1
  241. package/dist/storage/domains/projects/base.js.map +1 -1
  242. package/dist/storage/domains/queue-health/base.js.map +1 -1
  243. package/dist/storage/domains/source-control/base.d.ts +19 -0
  244. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  245. package/dist/storage/domains/source-control/base.js +42 -0
  246. package/dist/storage/domains/source-control/base.js.map +1 -1
  247. package/dist/storage/domains/source-control/inmemory.d.ts +5 -1
  248. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  249. package/dist/storage/domains/source-control/inmemory.js +7 -0
  250. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  251. package/dist/storage/domains/work-items/base.d.ts +14 -0
  252. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  253. package/dist/storage/domains/work-items/base.js +25 -1
  254. package/dist/storage/domains/work-items/base.js.map +1 -1
  255. package/dist/storage/domains/work-items/board-version.js.map +1 -1
  256. package/dist/storage/domains/work-items/metrics.js.map +1 -1
  257. package/dist/tools/approval-tools.js +1 -1
  258. package/dist/tools/approval-tools.js.map +1 -1
  259. package/dist/tools/deliver.d.ts +8 -5
  260. package/dist/tools/deliver.d.ts.map +1 -1
  261. package/dist/tools/deliver.js +22 -8
  262. package/dist/tools/deliver.js.map +1 -1
  263. package/dist/tools/messaging-tools.d.ts +1 -1
  264. package/dist/tools/messaging-tools.d.ts.map +1 -1
  265. package/dist/tools/messaging-tools.js +203 -72
  266. package/dist/tools/messaging-tools.js.map +1 -1
  267. package/dist/tools/permissions.d.ts +1 -1
  268. package/dist/tools/permissions.d.ts.map +1 -1
  269. package/dist/tools/permissions.js +1 -1
  270. package/dist/tools/permissions.js.map +1 -1
  271. package/dist/tools/reports.d.ts.map +1 -1
  272. package/dist/tools/reports.js +10 -3
  273. package/dist/tools/reports.js.map +1 -1
  274. package/dist/tools/run-watch.d.ts +2 -0
  275. package/dist/tools/run-watch.d.ts.map +1 -1
  276. package/dist/tools/run-watch.js +42 -2
  277. package/dist/tools/run-watch.js.map +1 -1
  278. package/dist/tools/scope.d.ts +2 -1
  279. package/dist/tools/scope.d.ts.map +1 -1
  280. package/dist/tools/scope.js +3 -2
  281. package/dist/tools/scope.js.map +1 -1
  282. package/dist/tools/session-tools.d.ts +1 -1
  283. package/dist/tools/session-tools.d.ts.map +1 -1
  284. package/dist/tools/session-tools.js +33 -16
  285. package/dist/tools/session-tools.js.map +1 -1
  286. package/dist/tools/sessions-state-processor.js +2 -2
  287. package/dist/tools/sessions-state-processor.js.map +1 -1
  288. package/dist/tools/side-sessions.d.ts +1 -1
  289. package/dist/tools/side-sessions.d.ts.map +1 -1
  290. package/dist/tools/side-sessions.js +1 -1
  291. package/dist/tools/side-sessions.js.map +1 -1
  292. package/dist/workspace.d.ts +5 -2
  293. package/dist/workspace.d.ts.map +1 -1
  294. package/dist/workspace.js +28 -15
  295. package/dist/workspace.js.map +1 -1
  296. package/package.json +13 -13
@@ -1 +1 @@
1
- {"version":3,"file":"environment-state-processor.js","names":[],"sources":["../../src/session/environment-state-processor.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport type { ComputeStateSignalArgs, ComputeStateSignalResult, Processor } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nconst STATE_ID = 'factory-environment';\n\nexport type EnvironmentRepositorySetupStatus = 'ok' | 'failed' | 'skipped';\n\n/** One repository of the booted environment as the agent is told about it: never a token or a clone URL. */\nexport interface SessionEnvironmentRepositoryState {\n slug: string;\n /** Absolute directory of the checkout under the workspace root. */\n dir: string;\n /** The branch the checkout ended on after boot; `null` when it stays detached. */\n branch: string | null;\n defaultBranch: string;\n position: number;\n /** `ok` ran or was already set up, `failed` exited non-zero, `skipped` has no setup command. */\n setupStatus: EnvironmentRepositorySetupStatus;\n /** The change request this session opened in the repository, once it has. */\n changeRequestUrl?: string;\n}\n\nexport interface SessionEnvironmentState {\n /** The workspace root, the session's working directory; repositories sit beneath it. */\n workingDirectory: string;\n repositories: SessionEnvironmentRepositoryState[];\n /** One free-form line the boot wants the agent to know (never a credential), rendered last. */\n note?: string;\n}\n\n// The boot records what it materialized, keyed by the factory session id (the\n// agent's resource id); the processor reads it on the next model step. Boot\n// runs on every sandbox start, so a replacement process re-learns the state\n// the first time the session's sandbox starts again.\nconst environments = new Map<string, { state: SessionEnvironmentState; teardown: SessionEnvironmentTeardown[] }>();\n\n/** A repository's teardown command and the directory it runs in; kept beside the state, never rendered. */\nexport interface SessionEnvironmentTeardown {\n slug: string;\n dir: string;\n command: string;\n}\n\nexport function recordSessionEnvironment(\n sessionId: string,\n state: SessionEnvironmentState,\n teardown: SessionEnvironmentTeardown[] = [],\n): void {\n environments.set(sessionId, { state, teardown });\n}\n\n/**\n * Record what a source-control tool did in one environment repository (the\n * branch it pushed, the change request it opened) so the next signal snapshot\n * tells the agent. A no-op when the session's environment is not recorded in\n * this process or the slug is not part of it.\n */\nexport function updateSessionEnvironmentRepository(\n sessionId: string,\n slug: string,\n patch: { branch?: string; changeRequestUrl?: string },\n): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const wanted = slug.toLowerCase();\n const repositories = entry.state.repositories.map(repo => {\n if (repo.slug.toLowerCase() !== wanted) return repo;\n return {\n ...repo,\n ...(patch.branch !== undefined ? { branch: patch.branch } : {}),\n ...(patch.changeRequestUrl !== undefined ? { changeRequestUrl: patch.changeRequestUrl } : {}),\n };\n });\n entry.state = { ...entry.state, repositories };\n}\n\n/** Set or clear the environment's note; a no-op when the session's environment is not recorded here. */\nexport function setSessionEnvironmentNote(sessionId: string, note: string | null): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const { note: _previous, ...rest } = entry.state;\n entry.state = note ? { ...rest, note } : rest;\n}\n\nexport function clearSessionEnvironment(sessionId: string): void {\n environments.delete(sessionId);\n}\n\nexport function peekSessionEnvironment(sessionId: string): SessionEnvironmentState | undefined {\n return environments.get(sessionId)?.state;\n}\n\n/** Teardown commands of the booted environment, in position order. */\nexport function peekSessionEnvironmentTeardown(sessionId: string): SessionEnvironmentTeardown[] {\n return environments.get(sessionId)?.teardown ?? [];\n}\n\nexport function __clearSessionEnvironmentsForTests(): void {\n environments.clear();\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');\n}\n\n// The session id is the controller's resource id. Unlike factory runs, a user\n// session carries no `factoryProjectId` in its controller state, and the\n// environment is recorded for both, so only the resource id is required.\nfunction sessionIdFromContext(requestContext: RequestContext | undefined): string | null {\n if (!requestContext || typeof requestContext.get !== 'function') return null;\n const controller = requestContext.get('controller') as { resourceId?: unknown } | undefined;\n return typeof controller?.resourceId === 'string' && controller.resourceId ? controller.resourceId : null;\n}\n\nfunction environmentCacheKey(state: SessionEnvironmentState): string {\n return `environment:${createHash('sha256').update(JSON.stringify(state)).digest('hex').slice(0, 16)}`;\n}\n\n/**\n * Tells the agent which repositories its sandbox holds and where: the\n * workspace root is the session's working directory and every environment\n * repository is a directory beneath it. Snapshot mode only; a new snapshot\n * is emitted when the booted set changes (a start after an environment edit).\n */\nexport class FactoryEnvironmentStateProcessor implements Processor<'factory-environment'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const sessionId = sessionIdFromContext(args.requestContext);\n if (!sessionId) return;\n const state = environments.get(sessionId)?.state;\n if (!state) return;\n const cacheKey = environmentCacheKey(state);\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey)\n return;\n const lines = state.repositories.map(\n repo =>\n `${repo.position}. ${escapeText(repo.slug)} at ${escapeText(repo.dir)} on ${escapeText(repo.branch ?? '(detached)')} (default ${escapeText(repo.defaultBranch)}, setup ${repo.setupStatus})` +\n (repo.changeRequestUrl ? `, change request ${escapeText(repo.changeRequestUrl)}` : ''),\n );\n const only = state.repositories.length === 1 ? state.repositories[0] : undefined;\n const contents =\n (only\n ? `Factory environment: 1 repository, ${escapeText(only.slug)} at ${escapeText(only.dir)}, your working directory.\\n`\n : `Factory environment: ${state.repositories.length} repositories under ${escapeText(state.workingDirectory)}, your working directory.\\n`) +\n lines.join('\\n') +\n (only ? '' : '\\nRun git and project commands inside the repository directory they belong to.') +\n (state.note ? `\\n${escapeText(state.note)}` : '');\n return {\n id: STATE_ID,\n cacheKey,\n mode: 'snapshot',\n tagName: 'factory-environment',\n contents,\n value: { environment: state },\n attributes: { workingDirectory: only?.dir ?? state.workingDirectory, repositories: state.repositories.length },\n metadata: { value: { environment: state } },\n };\n }\n}\n"],"mappings":";;AAIA,MAAM,WAAW;AA+BjB,MAAM,+BAAe,IAAI,IAAwF;AASjH,SAAgB,yBACd,WACA,OACA,WAAyC,CAAC,GACpC;CACN,aAAa,IAAI,WAAW;EAAE;EAAO;CAAS,CAAC;AACjD;;;;;;;AAQA,SAAgB,mCACd,WACA,MACA,OACM;CACN,MAAM,QAAQ,aAAa,IAAI,SAAS;CACxC,IAAI,CAAC,OAAO;CACZ,MAAM,SAAS,KAAK,YAAY;CAChC,MAAM,eAAe,MAAM,MAAM,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+ {"version":3,"file":"environment-state-processor.js","names":[],"sources":["../../src/session/environment-state-processor.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport type { ComputeStateSignalArgs, ComputeStateSignalResult, Processor } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nconst STATE_ID = 'factory-environment';\n\nexport type EnvironmentRepositorySetupStatus = 'ok' | 'failed' | 'skipped';\n\n/** One repository of the booted environment as the agent is told about it: never a token or a clone URL. */\nexport interface SessionEnvironmentRepositoryState {\n slug: string;\n /** Absolute directory of the checkout under the workspace root. */\n dir: string;\n /** The branch the checkout ended on after boot; `null` when it stays detached. */\n branch: string | null;\n defaultBranch: string;\n position: number;\n /** `ok` ran or was already set up, `failed` exited non-zero, `skipped` has no setup command. */\n setupStatus: EnvironmentRepositorySetupStatus;\n /** The change request this session opened in the repository, once it has. */\n changeRequestUrl?: string;\n}\n\nexport interface SessionEnvironmentState {\n /** The workspace root, the session's working directory; repositories sit beneath it. */\n workingDirectory: string;\n repositories: SessionEnvironmentRepositoryState[];\n /** One free-form line the boot wants the agent to know (never a credential), rendered last. */\n note?: string;\n}\n\n// The boot records what it materialized, keyed by the factory session id (the\n// agent's resource id); the processor reads it on the next model step. Boot\n// runs on every sandbox start, so a replacement process re-learns the state\n// the first time the session's sandbox starts again.\nconst environments = new Map<string, { state: SessionEnvironmentState; teardown: SessionEnvironmentTeardown[] }>();\n\n/** A repository's teardown command and the directory it runs in; kept beside the state, never rendered. */\nexport interface SessionEnvironmentTeardown {\n slug: string;\n dir: string;\n command: string;\n}\n\nexport function recordSessionEnvironment(\n sessionId: string,\n state: SessionEnvironmentState,\n teardown: SessionEnvironmentTeardown[] = [],\n): void {\n environments.set(sessionId, { state, teardown });\n}\n\n/**\n * Record what a source-control tool did in one environment repository (the\n * branch it pushed, the change request it opened) so the next signal snapshot\n * tells the agent. A no-op when the session's environment is not recorded in\n * this process or the slug is not part of it.\n */\nexport function updateSessionEnvironmentRepository(\n sessionId: string,\n slug: string,\n patch: { branch?: string; changeRequestUrl?: string },\n): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const wanted = slug.toLowerCase();\n const repositories = entry.state.repositories.map(repo => {\n if (repo.slug.toLowerCase() !== wanted) return repo;\n return {\n ...repo,\n ...(patch.branch !== undefined ? { branch: patch.branch } : {}),\n ...(patch.changeRequestUrl !== undefined ? { changeRequestUrl: patch.changeRequestUrl } : {}),\n };\n });\n entry.state = { ...entry.state, repositories };\n}\n\n/** Set or clear the environment's note; a no-op when the session's environment is not recorded here. */\nexport function setSessionEnvironmentNote(sessionId: string, note: string | null): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const { note: _previous, ...rest } = entry.state;\n entry.state = note ? { ...rest, note } : rest;\n}\n\nexport function clearSessionEnvironment(sessionId: string): void {\n environments.delete(sessionId);\n}\n\nexport function peekSessionEnvironment(sessionId: string): SessionEnvironmentState | undefined {\n return environments.get(sessionId)?.state;\n}\n\n/** Teardown commands of the booted environment, in position order. */\nexport function peekSessionEnvironmentTeardown(sessionId: string): SessionEnvironmentTeardown[] {\n return environments.get(sessionId)?.teardown ?? [];\n}\n\nexport function __clearSessionEnvironmentsForTests(): void {\n environments.clear();\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');\n}\n\n// Unlike factory runs, a user session carries no `factoryProjectId` in its\n// controller state, and the environment is recorded for both, so only the\n// session id is required.\nfunction sessionIdFromContext(requestContext: RequestContext | undefined): string | null {\n if (!requestContext || typeof requestContext.get !== 'function') return null;\n const controller = requestContext.get('controller') as { sessionId?: unknown } | undefined;\n return typeof controller?.sessionId === 'string' && controller.sessionId ? controller.sessionId : null;\n}\n\nfunction environmentCacheKey(state: SessionEnvironmentState): string {\n return `environment:${createHash('sha256').update(JSON.stringify(state)).digest('hex').slice(0, 16)}`;\n}\n\n/**\n * Tells the agent which repositories its sandbox holds and where: the\n * workspace root is the session's working directory and every environment\n * repository is a directory beneath it. Snapshot mode only; a new snapshot\n * is emitted when the booted set changes (a start after an environment edit).\n */\nexport class FactoryEnvironmentStateProcessor implements Processor<'factory-environment'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const sessionId = sessionIdFromContext(args.requestContext);\n if (!sessionId) return;\n const state = environments.get(sessionId)?.state;\n if (!state) return;\n const cacheKey = environmentCacheKey(state);\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey)\n return;\n const lines = state.repositories.map(\n repo =>\n `${repo.position}. ${escapeText(repo.slug)} at ${escapeText(repo.dir)} on ${escapeText(repo.branch ?? '(detached)')} (default ${escapeText(repo.defaultBranch)}, setup ${repo.setupStatus})` +\n (repo.changeRequestUrl ? `, change request ${escapeText(repo.changeRequestUrl)}` : ''),\n );\n const only = state.repositories.length === 1 ? state.repositories[0] : undefined;\n const contents =\n (only\n ? `Factory environment: 1 repository, ${escapeText(only.slug)} at ${escapeText(only.dir)}, your working directory.\\n`\n : `Factory environment: ${state.repositories.length} repositories under ${escapeText(state.workingDirectory)}, your working directory.\\n`) +\n lines.join('\\n') +\n (only ? '' : '\\nRun git and project commands inside the repository directory they belong to.') +\n (state.note ? `\\n${escapeText(state.note)}` : '');\n return {\n id: STATE_ID,\n cacheKey,\n mode: 'snapshot',\n tagName: 'factory-environment',\n contents,\n value: { environment: state },\n attributes: { workingDirectory: only?.dir ?? state.workingDirectory, repositories: state.repositories.length },\n metadata: { value: { environment: state } },\n };\n }\n}\n"],"mappings":";;AAIA,MAAM,WAAW;AA+BjB,MAAM,+BAAe,IAAI,IAAwF;AASjH,SAAgB,yBACd,WACA,OACA,WAAyC,CAAC,GACpC;CACN,aAAa,IAAI,WAAW;EAAE;EAAO;CAAS,CAAC;AACjD;;;;;;;AAQA,SAAgB,mCACd,WAC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AE,kBAAkB,MAAM,OAAO,MAAM;IAAkB,cAAc,MAAM,aAAa;GAAO;GAC7G,UAAU,EAAE,OAAO,EAAE,aAAa,MAAM,EAAE;EAC5C;CACF;AACF"}
@@ -17,7 +17,7 @@ export declare const ROOT_FILES_LIST_COMMAND: string;
17
17
  export declare function touchStamp(date: Date): string;
18
18
  export interface FilesystemCaptureSession {
19
19
  readonly identity: {
20
- getResourceId(): string;
20
+ getId(): string;
21
21
  };
22
22
  readonly thread: {
23
23
  requireId(): string;
@@ -36,7 +36,7 @@ export interface FilesystemCaptureDependencies {
36
36
  }
37
37
  export declare function parseFilesystemCaptureFiles(output: string): FilesystemFile[];
38
38
  export declare function captureSessionFilesystem(session: FilesystemCaptureSession, { filesystem, sourceControl }: FilesystemCaptureDependencies, ids?: {
39
- resourceId: string;
39
+ sessionId: string;
40
40
  threadId: string;
41
41
  }): Promise<void>;
42
42
  /**
@@ -45,6 +45,6 @@ export declare function captureSessionFilesystem(session: FilesystemCaptureSessi
45
45
  * never blocked by the execs' worst-case 30s timeouts. Never rejects: the
46
46
  * capture body is fully try/catch contained.
47
47
  */
48
- export declare function waitForPendingFilesystemCapture(resourceId: string, timeoutMs?: number): Promise<void>;
48
+ export declare function waitForPendingFilesystemCapture(sessionId: string, timeoutMs?: number): Promise<void>;
49
49
  export declare function observeSessionFilesystem(session: FilesystemCaptureSession, dependencies: FilesystemCaptureDependencies): () => void;
50
50
  //# sourceMappingURL=filesystem-capture.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"filesystem-capture.d.ts","sourceRoot":"","sources":["../../src/session/filesystem-capture.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AACzG,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAI/D,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAC/F,OAAO,KAA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C,UAAU,CAAC,EAAE,gBAAgB,CAAC,CAAC;KAC1E,CAAC;CACH;AAED,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,MAAM,GAAG,cAAc,EAAE,CAS5E;AAED,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,wBAAwB,EACjC,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE,6BAA6B,EAC5D,GAAG,CAAC,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAC5C,OAAO,CAAC,IAAI,CAAC,CAoHf;AAWD;;;;;GAKG;AACH,wBAAsB,+BAA+B,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAsB1G;AAED,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,wBAAwB,EACjC,YAAY,EAAE,6BAA6B,GAC1C,MAAM,IAAI,CAwFZ"}
@@ -48,9 +48,9 @@ function parseFilesystemCaptureFiles(output) {
48
48
  }
49
49
  async function captureSessionFilesystem(session, { filesystem, sourceControl }, ids) {
50
50
  try {
51
- const resourceId = ids?.resourceId ?? session.identity.getResourceId();
51
+ const sessionId = ids?.sessionId ?? session.identity.getId();
52
52
  const threadId = ids?.threadId ?? session.thread.requireId();
53
- const sourceSession = await sourceControl.sessions.getBySessionId(resourceId);
53
+ const sourceSession = await sourceControl.sessions.getBySessionId(sessionId);
54
54
  const sandbox = session.getWorkspace()?.sandbox;
55
55
  if (!sourceSession || !sandbox?.executeCommand) return;
56
56
  const entry = peekSessionSandbox(sourceSession.id);
@@ -120,7 +120,7 @@ async function captureSessionFilesystem(session, { filesystem, sourceControl },
120
120
  }
121
121
  }
122
122
  await filesystem.replaceFiles({
123
- resourceId,
123
+ resourceId: sessionId,
124
124
  threadId,
125
125
  files: [...files.values()].toSorted((a, b) => a.path.localeCompare(b.path))
126
126
  });
@@ -129,11 +129,10 @@ async function captureSessionFilesystem(session, { filesystem, sourceControl },
129
129
  }
130
130
  }
131
131
  /**
132
- * In-flight capture chains keyed by session resource id. Serves two purposes:
133
- * readers of the persisted file listing (the /web/workspace routes) await the
134
- * capture for the turn that just ended instead of racing it, and captures for
135
- * the same resource stay sequential (last write wins) even when multiple
136
- * scoped sessions observe the same resource id. In-process only: the factory
132
+ * In-flight capture chains keyed by session id. Serves two purposes: readers
133
+ * of the persisted file listing (the /web/workspace routes) await the capture
134
+ * for the turn that just ended instead of racing it, and captures for the same
135
+ * session stay sequential (last write wins). In-process only: the factory
137
136
  * server that runs the session controller also serves those routes.
138
137
  */
139
138
  const pendingCaptures = /* @__PURE__ */ new Map();
@@ -143,8 +142,8 @@ const pendingCaptures = /* @__PURE__ */ new Map();
143
142
  * never blocked by the execs' worst-case 30s timeouts. Never rejects: the
144
143
  * capture body is fully try/catch contained.
145
144
  */
146
- async function waitForPendingFilesystemCapture(resourceId, timeoutMs = 1e4) {
147
- let pending = pendingCaptures.get(resourceId);
145
+ async function waitForPendingFilesystemCapture(sessionId, timeoutMs = 1e4) {
146
+ let pending = pendingCaptures.get(sessionId);
148
147
  if (!pending) return;
149
148
  let timer;
150
149
  let timedOut = false;
@@ -157,7 +156,7 @@ async function waitForPendingFilesystemCapture(resourceId, timeoutMs = 1e4) {
157
156
  try {
158
157
  while (pending && !timedOut) {
159
158
  await Promise.race([pending, deadline]);
160
- const next = pendingCaptures.get(resourceId);
159
+ const next = pendingCaptures.get(sessionId);
161
160
  pending = next === pending ? void 0 : next;
162
161
  }
163
162
  } finally {
@@ -197,9 +196,9 @@ function observeSessionFilesystem(session, dependencies) {
197
196
  const unsubscribeEnd = session.onBeforeAgentEnd(() => {
198
197
  if (!workspaceTouched) return;
199
198
  workspaceTouched = false;
200
- let resourceId;
199
+ let sessionId;
201
200
  try {
202
- resourceId = session.identity.getResourceId();
201
+ sessionId = session.identity.getId();
203
202
  } catch {
204
203
  fallbackChain = fallbackChain.then(() => captureSessionFilesystem(session, dependencies));
205
204
  return;
@@ -211,13 +210,13 @@ function observeSessionFilesystem(session, dependencies) {
211
210
  return;
212
211
  }
213
212
  const ids = {
214
- resourceId,
213
+ sessionId,
215
214
  threadId
216
215
  };
217
- const chain = (pendingCaptures.get(resourceId) ?? Promise.resolve()).then(() => captureSessionFilesystem(session, dependencies, ids));
218
- pendingCaptures.set(resourceId, chain);
216
+ const chain = (pendingCaptures.get(sessionId) ?? Promise.resolve()).then(() => captureSessionFilesystem(session, dependencies, ids));
217
+ pendingCaptures.set(sessionId, chain);
219
218
  chain.finally(() => {
220
- if (pendingCaptures.get(resourceId) === chain) pendingCaptures.delete(resourceId);
219
+ if (pendingCaptures.get(sessionId) === chain) pendingCaptures.delete(sessionId);
221
220
  });
222
221
  });
223
222
  return () => {
@@ -1 +1 @@
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, sessionLayout } from '../sandbox/session-sandbox.js';\nimport type { SessionLayoutRepository } 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 { peekSessionEnvironment } from './environment-state-processor.js';\nimport { isMeaningfulToolName } from './first-exec-capture.js';\n\n/** Exit code of `GIT_CHANGED_FILES_SCRIPT` when the checkout is not there: the repository is skipped, not failed. */\nconst CHECKOUT_MISSING_EXIT_CODE = 3;\nconst GIT_CHANGED_FILES_SCRIPT = `\nset -e\nworkdir=$1\nbase_branch=$2\ntest -d \"$workdir\" || exit ${CHECKOUT_MISSING_EXIT_CODE}\nbase=HEAD\nif merge_base=$(git -C \"$workdir\" merge-base HEAD \"origin/$base_branch\" 2>/dev/null); then\n base=$merge_base\nfi\ngit -C \"$workdir\" diff --name-only -z --find-renames --diff-filter=ACMRTUXB \"$base\"\ngit -C \"$workdir\" ls-files --others --exclude-standard -z\n`;\nconst ARTIFACTS_LIST_COMMAND = 'cd \"$1\" && test -d .artifacts && find .artifacts -type f -print0 || true';\n/**\n * Regular files directly under the workspace root written since the session\n * was created ($2 is a UTC `touch -t` stamp, `YYYYMMDDhhmm.SS`), such as the\n * agent's notes. Files the template shipped with predate the session and stay\n * out; the checkouts are covered by git. Dotfiles are never listed: a listed\n * path becomes readable through the thread's file route, and the root is where\n * setup leaves `.env`, `.pgpass`, `.netrc` and other credential files.\n * `touch -t` plus `-newer` works on GNU and BSD find alike; `-newermt\n * \"@epoch\"` is GNU only.\n */\nexport const ROOT_FILES_LIST_COMMAND = [\n 'cd \"$1\" && ref=$(mktemp) && TZ=UTC touch -t \"$2\" \"$ref\"',\n '&& find . -mindepth 1 -maxdepth 1 -type f ! -name \\'.*\\' -newer \"$ref\" -print0',\n '; status=$?; rm -f \"$ref\"; exit $status',\n].join(' ');\n\n/** `touch -t` stamp of a moment, in UTC. */\nexport function touchStamp(date: Date): string {\n const two = (value: number) => String(value).padStart(2, '0');\n return (\n `${date.getUTCFullYear()}${two(date.getUTCMonth() + 1)}${two(date.getUTCDate())}` +\n `${two(date.getUTCHours())}${two(date.getUTCMinutes())}.${two(date.getUTCSeconds())}`\n );\n}\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 for (const record of output.split('\\0')) {\n if (!record) continue;\n const path = record.replace(/^\\.\\//, '');\n if (path) 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 ids?: { resourceId: string; threadId: string },\n): Promise<void> {\n try {\n // Scheduled captures pass ids read at schedule time: a session deleted\n // before the queued capture runs has already cleared its thread.\n const resourceId = ids?.resourceId ?? session.identity.getResourceId();\n const threadId = ids?.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 layout = sessionLayout(entry);\n if (!layout) return;\n\n // One git pass per checkout, in parallel so three repositories stay well\n // inside the 10 s readers wait for a pending capture. The session's own\n // repository compares against the session base branch; the others sit on\n // their default branch and compare against that. A repository whose\n // checkout is missing (exit 3) is skipped: it has nothing to list and\n // must not block the others. Any other failure is treated as transient\n // and leaves the previous listing in place.\n const multiRepo = layout.repos.length > 1;\n const environment = multiRepo ? peekSessionEnvironment(sourceSession.sessionId) : undefined;\n const ownRepo = entry.ownRepo.toLowerCase();\n // The boot records the state at its end, after every setup command; until\n // then a secondary checkout compares against its own `origin/HEAD`.\n const baseBranchFor = (repo: SessionLayoutRepository): string => {\n if (repo.slug.toLowerCase() === ownRepo) return sourceSession.baseBranch;\n const state = environment?.repositories.find(\n candidate => candidate.slug.toLowerCase() === repo.slug.toLowerCase(),\n );\n return state?.defaultBranch ?? 'HEAD';\n };\n const targets = layout.repos.map(repo => ({ repo, baseBranch: baseBranchFor(repo) }));\n const executeCommand = sandbox.executeCommand.bind(sandbox);\n const results = await Promise.all(\n targets.map(({ repo, baseBranch }) =>\n executeCommand('sh', ['-c', GIT_CHANGED_FILES_SCRIPT, 'mastracode-changed-files', repo.dir, baseBranch], {\n timeout: 30_000,\n }),\n ),\n );\n const files = new Map<string, FilesystemFile>();\n let captured = 0;\n for (const [index, result] of results.entries()) {\n if (result.exitCode === CHECKOUT_MISSING_EXIT_CODE) continue;\n if (result.exitCode !== 0) {\n console.warn('[Factory filesystem capture] Unable to inspect Git changes.', result.stderr);\n return;\n }\n captured += 1;\n const prefix = targets[index]!.repo.prefix;\n for (const file of parseFilesystemCaptureFiles(result.stdout)) {\n files.set(`${prefix}${file.path}`, { path: `${prefix}${file.path}` });\n }\n }\n if (captured === 0) return;\n\n const artifacts = await executeCommand('sh', ['-c', ARTIFACTS_LIST_COMMAND, 'sh', layout.root], {\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 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 // With several checkouts the root is a plain directory nothing else lists.\n // A failed listing is logged and the git and artifact results still land.\n if (multiRepo) {\n const since = touchStamp(sourceSession.createdAt);\n const rootFiles = await executeCommand('sh', ['-c', ROOT_FILES_LIST_COMMAND, 'sh', layout.root, since], {\n timeout: 30_000,\n });\n if (rootFiles.exitCode !== 0) {\n console.warn('[Factory filesystem capture] Unable to list workspace root files.', rootFiles.stderr);\n } else {\n for (const path of rootFiles.stdout.split('\\0')) {\n const normalizedPath = path.replace(/^\\.\\//, '');\n if (normalizedPath && !normalizedPath.startsWith('.')) {\n files.set(normalizedPath, { path: normalizedPath });\n }\n }\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 let pending = pendingCaptures.get(resourceId);\n if (!pending) return;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n const deadline = new Promise<void>(resolve => {\n timer = setTimeout(() => {\n timedOut = true;\n resolve();\n }, timeoutMs);\n });\n try {\n // A turn that ends while we wait chains a successor capture; keep waiting\n // until the latest chain settles so the final snapshot is not lost.\n while (pending && !timedOut) {\n await Promise.race([pending, deadline]);\n const next = pendingCaptures.get(resourceId);\n pending = next === pending ? undefined : next;\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 let threadId: string;\n try {\n threadId = session.thread.requireId();\n } catch {\n return;\n }\n const ids = { resourceId, threadId };\n const chain = (pendingCaptures.get(resourceId) ?? Promise.resolve()).then(() =>\n captureSessionFilesystem(session, dependencies, ids),\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":";;;;;AAWA,MAAM,6BAA6B;AACnC,MAAM,2BAA2B;;;;6BAIJ,2BAA2B;;;;;;;;AAQxD,MAAM,yBAAyB;;;;;;;;;;;AAW/B,MAAa,0BAA0B;CACrC;CACA;CACA;AACF,CAAC,CAAC,KAAK,GAAG;;AAGV,SAAgB,WAAW,MAAoB;CAC7C,MAAM,OAAO,UAAkB,OAAO,KAAK,CAAC,CAAC,SAAS,GAAG,GAAG;CAC5D,OACE,GAAG,KAAK,eAAe,IAAI,IAAI,KAAK,YAAY,IAAI,CAAC,IAAI,IAAI,KAAK,WAAW,CAAC,IAC3E,IAAI,KAAK,YAAY,CAAC,IAAI,IAAI,KAAK,cAAc,CAAC,EAAE,GAAG,IAAI,KAAK,cAAc,CAAC;AAEtF;AAiBA,SAAgB,4BAA4B,QAAkC;CAC5E,MAAM,wBAAQ,IAAI,IAA4B;CAC9C,KAAK,MAAM,UAAU,OAAO,MAAM,IAAI,GAAG;EACvC,IAAI,CAAC,QAAQ;EACb,MAAM,OAAO,OAAO,QAAQ,SAAS,EAAE;EACvC,IAAI,MAAM,MAAM,IAAI,MAAM,EAAE,KAAK,CAAC;CACpC;CAEA,OAAO,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC,CAAC,UAAU,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;AAC5E;AAEA,eAAsB,yBACpB,SACA,EAAE,YAAY,iBACd,KACe;CACf,IAAI;E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IACvD;GACF;EACF;CACF,CAAC;CACD,MAAM,iBAAiB,QAAQ,uBAAuB;EAGpD,IAAI,CAAC,kBAAkB;EACvB,mBAAmB;EAUnB,IAAI;EACJ,IAAI;GACF,aAAa,QAAQ,SAAS,cAAc;EAC9C,QAAQ;GAGN,gBAAgB,cAAc,WAAW,yBAAyB,SAAS,YAAY,CAAC;GACxF;EACF;EAIA,IAAI;EACJ,IAAI;GACF,WAAW,QAAQ,OAAO,UAAU;EACtC,QAAQ;GACN;EACF;EACA,MAAM,MAAM;GAAE;GAAY;EAAS;EACnC,MAAM,SAAS,gBAAgB,IAAI,UAAU,KAAK,QAAQ,QAAQ,EAAA,CAAG,WACnE,yBAAyB,SAAS,cAAc,GAAG,CACrD;EACA,gBAAgB,IAAI,YAAY,KAAK;EACrC,MAAW,cAAc;GACvB,IAAI,gBAAgB,IAAI,UAAU,MAAM,OACtC,gBAAgB,OAAO,UAAU;EAErC,CAAC;CACH,CAAC;CACD,aAAa;EACX,kBAAkB;EAClB,eAAe;CACjB;AACF"}
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, sessionLayout } from '../sandbox/session-sandbox.js';\nimport type { SessionLayoutRepository } 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 { peekSessionEnvironment } from './environment-state-processor.js';\nimport { isMeaningfulToolName } from './first-exec-capture.js';\n\n/** Exit code of `GIT_CHANGED_FILES_SCRIPT` when the checkout is not there: the repository is skipped, not failed. */\nconst CHECKOUT_MISSING_EXIT_CODE = 3;\nconst GIT_CHANGED_FILES_SCRIPT = `\nset -e\nworkdir=$1\nbase_branch=$2\ntest -d \"$workdir\" || exit ${CHECKOUT_MISSING_EXIT_CODE}\nbase=HEAD\nif merge_base=$(git -C \"$workdir\" merge-base HEAD \"origin/$base_branch\" 2>/dev/null); then\n base=$merge_base\nfi\ngit -C \"$workdir\" diff --name-only -z --find-renames --diff-filter=ACMRTUXB \"$base\"\ngit -C \"$workdir\" ls-files --others --exclude-standard -z\n`;\nconst ARTIFACTS_LIST_COMMAND = 'cd \"$1\" && test -d .artifacts && find .artifacts -type f -print0 || true';\n/**\n * Regular files directly under the workspace root written since the session\n * was created ($2 is a UTC `touch -t` stamp, `YYYYMMDDhhmm.SS`), such as the\n * agent's notes. Files the template shipped with predate the session and stay\n * out; the checkouts are covered by git. Dotfiles are never listed: a listed\n * path becomes readable through the thread's file route, and the root is where\n * setup leaves `.env`, `.pgpass`, `.netrc` and other credential files.\n * `touch -t` plus `-newer` works on GNU and BSD find alike; `-newermt\n * \"@epoch\"` is GNU only.\n */\nexport const ROOT_FILES_LIST_COMMAND = [\n 'cd \"$1\" && ref=$(mktemp) && TZ=UTC touch -t \"$2\" \"$ref\"',\n '&& find . -mindepth 1 -maxdepth 1 -type f ! -name \\'.*\\' -newer \"$ref\" -print0',\n '; status=$?; rm -f \"$ref\"; exit $status',\n].join(' ');\n\n/** `touch -t` stamp of a moment, in UTC. */\nexport function touchStamp(date: Date): string {\n const two = (value: number) => String(value).padStart(2, '0');\n return (\n `${date.getUTCFullYear()}${two(date.getUTCMonth() + 1)}${two(date.getUTCDate())}` +\n `${two(date.getUTCHours())}${two(date.getUTCMinutes())}.${two(date.getUTCSeconds())}`\n );\n}\n\nexport interface FilesystemCaptureSession {\n readonly identity: { getId(): 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 for (const record of output.split('\\0')) {\n if (!record) continue;\n const path = record.replace(/^\\.\\//, '');\n if (path) 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 ids?: { sessionId: string; threadId: string },\n): Promise<void> {\n try {\n // Scheduled captures pass ids read at schedule time: a session deleted\n // before the queued capture runs has already cleared its thread.\n const sessionId = ids?.sessionId ?? session.identity.getId();\n const threadId = ids?.threadId ?? session.thread.requireId();\n const sourceSession = await sourceControl.sessions.getBySessionId(sessionId);\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 layout = sessionLayout(entry);\n if (!layout) return;\n\n // One git pass per checkout, in parallel so three repositories stay well\n // inside the 10 s readers wait for a pending capture. The session's own\n // repository compares against the session base branch; the others sit on\n // their default branch and compare against that. A repository whose\n // checkout is missing (exit 3) is skipped: it has nothing to list and\n // must not block the others. Any other failure is treated as transient\n // and leaves the previous listing in place.\n const multiRepo = layout.repos.length > 1;\n const environment = multiRepo ? peekSessionEnvironment(sourceSession.sessionId) : undefined;\n const ownRepo = entry.ownRepo.toLowerCase();\n // The boot records the state at its end, after every setup command; until\n // then a secondary checkout compares against its own `origin/HEAD`.\n const baseBranchFor = (repo: SessionLayoutRepository): string => {\n if (repo.slug.toLowerCase() === ownRepo) return sourceSession.baseBranch;\n const state = environment?.repositories.find(\n candidate => candidate.slug.toLowerCase() === repo.slug.toLowerCase(),\n );\n return state?.defaultBranch ?? 'HEAD';\n };\n const targets = layout.repos.map(repo => ({ repo, baseBranch: baseBranchFor(repo) }));\n const executeCommand = sandbox.executeCommand.bind(sandbox);\n const results = await Promise.all(\n targets.map(({ repo, baseBranch }) =>\n executeCommand('sh', ['-c', GIT_CHANGED_FILES_SCRIPT, 'mastracode-changed-files', repo.dir, baseBranch], {\n timeout: 30_000,\n }),\n ),\n );\n const files = new Map<string, FilesystemFile>();\n let captured = 0;\n for (const [index, result] of results.entries()) {\n if (result.exitCode === CHECKOUT_MISSING_EXIT_CODE) continue;\n if (result.exitCode !== 0) {\n console.warn('[Factory filesystem capture] Unable to inspect Git changes.', result.stderr);\n return;\n }\n captured += 1;\n const prefix = targets[index]!.repo.prefix;\n for (const file of parseFilesystemCaptureFiles(result.stdout)) {\n files.set(`${prefix}${file.path}`, { path: `${prefix}${file.path}` });\n }\n }\n if (captured === 0) return;\n\n const artifacts = await executeCommand('sh', ['-c', ARTIFACTS_LIST_COMMAND, 'sh', layout.root], {\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 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 // With several checkouts the root is a plain directory nothing else lists.\n // A failed listing is logged and the git and artifact results still land.\n if (multiRepo) {\n const since = touchStamp(sourceSession.createdAt);\n const rootFiles = await executeCommand('sh', ['-c', ROOT_FILES_LIST_COMMAND, 'sh', layout.root, since], {\n timeout: 30_000,\n });\n if (rootFiles.exitCode !== 0) {\n console.warn('[Factory filesystem capture] Unable to list workspace root files.', rootFiles.stderr);\n } else {\n for (const path of rootFiles.stdout.split('\\0')) {\n const normalizedPath = path.replace(/^\\.\\//, '');\n if (normalizedPath && !normalizedPath.startsWith('.')) {\n files.set(normalizedPath, { path: normalizedPath });\n }\n }\n }\n }\n\n // The listing describes the session's workspace, not its memory resource,\n // which the session shares with others: rows are keyed by the session id.\n await filesystem.replaceFiles({\n resourceId: sessionId,\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 id. Serves two purposes: readers\n * of the persisted file listing (the /web/workspace routes) await the capture\n * for the turn that just ended instead of racing it, and captures for the same\n * session stay sequential (last write wins). 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(sessionId: string, timeoutMs = 10_000): Promise<void> {\n let pending = pendingCaptures.get(sessionId);\n if (!pending) return;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n const deadline = new Promise<void>(resolve => {\n timer = setTimeout(() => {\n timedOut = true;\n resolve();\n }, timeoutMs);\n });\n try {\n // A turn that ends while we wait chains a successor capture; keep waiting\n // until the latest chain settles so the final snapshot is not lost.\n while (pending && !timedOut) {\n await Promise.race([pending, deadline]);\n const next = pendingCaptures.get(sessionId);\n pending = next === pending ? undefined : next;\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 sessionId: string;\n try {\n sessionId = session.identity.getId();\n } catch {\n // No identity means no route can address this session's listing; keep\n // a per-observer chain so captures still run sequentially.\n fallbackChain = fallbackChain.then(() => captureSessionFilesystem(session, dependencies));\n return;\n }\n let threadId: string;\n try {\n threadId = session.thread.requireId();\n } catch {\n return;\n }\n const ids = { sessionId, threadId };\n const chain = (pendingCaptures.get(sessionId) ?? Promise.resolve()).then(() =>\n captureSessionFilesystem(session, dependencies, ids),\n );\n pendingCaptures.set(sessionId, chain);\n void chain.finally(() => {\n if (pendingCaptures.get(sessionId) === chain) {\n pendingCaptures.delete(sessionId);\n }\n });\n });\n return () => {\n unsubscribeEvents();\n unsubscribeEnd();\n };\n}\n"],"mappings":";;;;;AAWA,MAAM,6BAA6B;AACnC,MAAM,2BAA2B;;;;6BAIJ,2BAA2B;;;;;;;;AAQxD,MAAM,yBAAyB;;;;;;;;;;;AAW/B,MAAa,0BAA0B;CACrC;CACA;CACA;AACF,CAAC,CAAC,KAAK,GAAG;;AAGV,SAAgB,WAAW,MAAoB;CAC7C,MAAM,OAAO,UAAkB,OAAO,KAAK,CAAC,CAAC,SAAS,GAAG,GAAG;CAC5D,OACE,GAAG,KAAK,eAAe,IAAI,IAAI,KAAK,YAAY,IAAI,CAAC,IAAI,IAAI,KAAK,WAAW,CAAC,IAC3E,IAAI,KAAK,YAAY,CAAC,IAAI,IAAI,KAAK,cAAc,CAAC,EAAE,GAAG,IAAI,KAAK,cAAc,CAAC;AAEtF;AAiBA,SAAgB,4BAA4B,QAAkC;CAC5E,MAAM,wBAAQ,IAAI,IAA4B;CAC9C,KAAK,MAAM,UAAU,OAAO,MAAM,IAAI,GAAG;EACvC,IAAI,CAAC,QAAQ;EACb,MAAM,OAAO,OAAO,QAAQ,SAAS,EAAE;EACvC,IAAI,MAAM,MAAM,IAAI,MAAM,EAAE,KAAK,CAAC;CACpC;CAEA,OAAO,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC,CAAC,UAAU,GAAG,MAAM,EA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jC,UAAU,OAAO,MAAM,UAAU;IACjC,IAAI,MAAM,WAAW,MAAM,QAAQ;IACnC,IAAI,qBAAqB,QAAQ,GAAG,mBAAmB;IACvD;GACF;EACF;CACF,CAAC;CACD,MAAM,iBAAiB,QAAQ,uBAAuB;EAGpD,IAAI,CAAC,kBAAkB;EACvB,mBAAmB;EAUnB,IAAI;EACJ,IAAI;GACF,YAAY,QAAQ,SAAS,MAAM;EACrC,QAAQ;GAGN,gBAAgB,cAAc,WAAW,yBAAyB,SAAS,YAAY,CAAC;GACxF;EACF;EACA,IAAI;EACJ,IAAI;GACF,WAAW,QAAQ,OAAO,UAAU;EACtC,QAAQ;GACN;EACF;EACA,MAAM,MAAM;GAAE;GAAW;EAAS;EAClC,MAAM,SAAS,gBAAgB,IAAI,SAAS,KAAK,QAAQ,QAAQ,EAAA,CAAG,WAClE,yBAAyB,SAAS,cAAc,GAAG,CACrD;EACA,gBAAgB,IAAI,WAAW,KAAK;EACpC,MAAW,cAAc;GACvB,IAAI,gBAAgB,IAAI,SAAS,MAAM,OACrC,gBAAgB,OAAO,SAAS;EAEpC,CAAC;CACH,CAAC;CACD,aAAa;EACX,kBAAkB;EAClB,eAAe;CACjB;AACF"}
@@ -2,7 +2,7 @@ import type { AgentControllerEvent } from '@mastra/core/agent-controller';
2
2
  import type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';
3
3
  export interface FirstExecCaptureSession {
4
4
  readonly identity: {
5
- getResourceId(): string;
5
+ getId(): string;
6
6
  };
7
7
  subscribe(listener: (event: AgentControllerEvent) => void): () => void;
8
8
  }
@@ -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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AAO,EAAE,uBAAuB,EAChC,EAAE,aAAa,EAAE,EAAE,4BAA4B,GAC9C,MAAM,IAAI,CAoDZ"}
@@ -78,7 +78,7 @@ function observeSessionFirstExec(session, { sourceControl }) {
78
78
  if (!isMeaningfulToolName(toolName)) return;
79
79
  seen = true;
80
80
  unsubscribe();
81
- sourceControl.sessions.markFirstMeaningfulExec({ sessionId: session.identity.getResourceId() }).catch((error) => console.warn("[Factory first-exec capture] Unable to persist first exec time.", error));
81
+ sourceControl.sessions.markFirstMeaningfulExec({ sessionId: session.identity.getId() }).catch((error) => console.warn("[Factory first-exec capture] Unable to persist first exec time.", error));
82
82
  return;
83
83
  }
84
84
  }
@@ -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\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"}
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: { getId(): 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.getId() })\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,MAAM,EAAE,CAAC,CAAC,CAChE,OAAM,UAAS,QAAQ,KAAK,mEAAmE,KAAK,CAAC;IACxG;GACF;EACF;CACF,CAAC;CACD,OAAO;AACT"}
@@ -2,7 +2,7 @@ import type { AgentControllerEvent } from '@mastra/core/agent-controller';
2
2
  import type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';
3
3
  export interface FirstMessageCaptureSession {
4
4
  readonly identity: {
5
- getResourceId(): string;
5
+ getId(): string;
6
6
  };
7
7
  subscribe(listener: (event: AgentControllerEvent) => void): () => void;
8
8
  }
@@ -1 +1 @@
1
- {"version":3,"file":"first-message-capture.d.ts","sourceRoot":"","sources":["../../src/session/first-message-capture.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAE5F,MAAM,WAAW,0BAA0B;IACzC,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,+BAA+B;IAC9C,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,kBAAkB,CAAC,CAAC;KAC5E,CAAC;CACH;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,0BAA0B,CACxC,OAAO,EAAE,0BAA0B,EACnC,EAAE,aAAa,EAAE,EAAE,+BAA+B,GACjD,MAAM,IAAI,CAaZ"}
1
+ {"version":3,"file":"first-message-capture.d.ts","sourceRoot":"","sources":["../../src/session/first-message-capture.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAE5F,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,QAAQ,EAAE;QAAE,KAAK,IAAI,MAAM,CAAA;KAAE,CAAC;IACvC,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACxE;AAED,MAAM,WAAW,+BAA+B;IAC9C,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,kBAAkB,CAAC,CAAC;KAC5E,CAAC;CACH;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,0BAA0B,CACxC,OAAO,EAAE,0BAA0B,EACnC,EAAE,aAAa,EAAE,EAAE,+BAA+B,GACjD,MAAM,IAAI,CAaZ"}
@@ -25,7 +25,7 @@ function observeSessionFirstMessage(session, { sourceControl }) {
25
25
  if (role !== "user" && role !== "assistant") return;
26
26
  seen = true;
27
27
  unsubscribe();
28
- sourceControl.sessions.markFirstMessage({ sessionId: session.identity.getResourceId() }).catch((error) => console.warn("[Factory first-message capture] Unable to persist first message time.", error));
28
+ sourceControl.sessions.markFirstMessage({ sessionId: session.identity.getId() }).catch((error) => console.warn("[Factory first-message capture] Unable to persist first message time.", error));
29
29
  });
30
30
  return unsubscribe;
31
31
  }
@@ -1 +1 @@
1
- {"version":3,"file":"first-message-capture.js","names":[],"sources":["../../src/session/first-message-capture.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\n\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\n\nexport interface FirstMessageCaptureSession {\n readonly identity: { getResourceId(): string };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\nexport interface FirstMessageCaptureDependencies {\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'markFirstMessage'>;\n };\n}\n\n/**\n * Record when a session's agent first produced an actual conversational\n * message (the TTFI anchor — \"time to first interaction\").\n *\n * We stamp on the first `message_start` whose role is `user` or `assistant`.\n * The coordinator writes `role='signal'` rows into the thread (skill loads,\n * phase markers, memory reminders) before the model is ever invoked; those\n * signals used to trigger a stamp via `agent_start`, giving every session —\n * including zero-message model-init failures — a false TTFI of a few seconds.\n * Gating on real conversational roles keeps the TTFI column honest: sessions\n * that never produced a user or assistant message stay NULL and drop out of\n * TTFI percentiles instead of contaminating them.\n *\n * The listener unsubscribes after the first qualifying message; the storage\n * write is guarded (`first_message_at IS NULL`), so restarts, re-materialized\n * sessions, and sessions without a source-control row (chat-only channels)\n * are no-ops.\n */\nexport function observeSessionFirstMessage(\n session: FirstMessageCaptureSession,\n { sourceControl }: FirstMessageCaptureDependencies,\n): () => void {\n let seen = false;\n const unsubscribe = session.subscribe(event => {\n if (seen || event.type !== 'message_start') return;\n const role = event.message.role;\n if (role !== 'user' && role !== 'assistant') return;\n seen = true;\n unsubscribe();\n void sourceControl.sessions\n .markFirstMessage({ sessionId: session.identity.getResourceId() })\n .catch(error => console.warn('[Factory first-message capture] Unable to persist first message time.', error));\n });\n return unsubscribe;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,2BACd,SACA,EAAE,iBACU;CACZ,IAAI,OAAO;CACX,MAAM,cAAc,QAAQ,WAAU,UAAS;EAC7C,IAAI,QAAQ,MAAM,SAAS,iBAAiB;EAC5C,MAAM,OAAO,MAAM,QAAQ;EAC3B,IAAI,SAAS,UAAU,SAAS,aAAa;EAC7C,OAAO;EACP,YAAY;EACZ,cAAmB,SAChB,iBAAiB,EAAE,WAAW,QAAQ,SAAS,cAAc,EAAE,CAAC,CAAC,CACjE,OAAM,UAAS,QAAQ,KAAK,yEAAyE,KAAK,CAAC;CAChH,CAAC;CACD,OAAO;AACT"}
1
+ {"version":3,"file":"first-message-capture.js","names":[],"sources":["../../src/session/first-message-capture.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\n\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\n\nexport interface FirstMessageCaptureSession {\n readonly identity: { getId(): string };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\nexport interface FirstMessageCaptureDependencies {\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'markFirstMessage'>;\n };\n}\n\n/**\n * Record when a session's agent first produced an actual conversational\n * message (the TTFI anchor — \"time to first interaction\").\n *\n * We stamp on the first `message_start` whose role is `user` or `assistant`.\n * The coordinator writes `role='signal'` rows into the thread (skill loads,\n * phase markers, memory reminders) before the model is ever invoked; those\n * signals used to trigger a stamp via `agent_start`, giving every session —\n * including zero-message model-init failures — a false TTFI of a few seconds.\n * Gating on real conversational roles keeps the TTFI column honest: sessions\n * that never produced a user or assistant message stay NULL and drop out of\n * TTFI percentiles instead of contaminating them.\n *\n * The listener unsubscribes after the first qualifying message; the storage\n * write is guarded (`first_message_at IS NULL`), so restarts, re-materialized\n * sessions, and sessions without a source-control row (chat-only channels)\n * are no-ops.\n */\nexport function observeSessionFirstMessage(\n session: FirstMessageCaptureSession,\n { sourceControl }: FirstMessageCaptureDependencies,\n): () => void {\n let seen = false;\n const unsubscribe = session.subscribe(event => {\n if (seen || event.type !== 'message_start') return;\n const role = event.message.role;\n if (role !== 'user' && role !== 'assistant') return;\n seen = true;\n unsubscribe();\n void sourceControl.sessions\n .markFirstMessage({ sessionId: session.identity.getId() })\n .catch(error => console.warn('[Factory first-message capture] Unable to persist first message time.', error));\n });\n return unsubscribe;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,2BACd,SACA,EAAE,iBACU;CACZ,IAAI,OAAO;CACX,MAAM,cAAc,QAAQ,WAAU,UAAS;EAC7C,IAAI,QAAQ,MAAM,SAAS,iBAAiB;EAC5C,MAAM,OAAO,MAAM,QAAQ;EAC3B,IAAI,SAAS,UAAU,SAAS,aAAa;EAC7C,OAAO;EACP,YAAY;EACZ,cAAmB,SAChB,iBAAiB,EAAE,WAAW,QAAQ,SAAS,MAAM,EAAE,CAAC,CAAC,CACzD,OAAM,UAAS,QAAQ,KAAK,yEAAyE,KAAK,CAAC;CAChH,CAAC;CACD,OAAO;AACT"}
@@ -35,7 +35,7 @@ export interface ParkedRun {
35
35
  * The sessions this process has materialized, by session id.
36
36
  *
37
37
  * Membership comes from the controller's notifications rather than
38
- * `getSessionByResource`, which hands back the pending creation — awaiting it
38
+ * `getSession`, which hands back the pending creation — awaiting it
39
39
  * from a request blocks for as long as the session takes to materialize its
40
40
  * sandbox, minutes on a cold clone. Notifications only fire once a session
41
41
  * exists, so a read never waits.
@@ -3,7 +3,7 @@
3
3
  * The sessions this process has materialized, by session id.
4
4
  *
5
5
  * Membership comes from the controller's notifications rather than
6
- * `getSessionByResource`, which hands back the pending creation — awaiting it
6
+ * `getSession`, which hands back the pending creation — awaiting it
7
7
  * from a request blocks for as long as the session takes to materialize its
8
8
  * sandbox, minutes on a cold clone. Notifications only fire once a session
9
9
  * exists, so a read never waits.
@@ -1 +1 @@
1
- {"version":3,"file":"live-sessions.js","names":["#byId","#parkedListeners","#track","#lastParkStamp","#nextParkStamp"],"sources":["../../src/session/live-sessions.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\n\n/** The slice of a live session this registry needs: its id, its run, its parked tools, and who it works for. */\nexport interface LiveSession {\n readonly identity: { getId(): string };\n readonly run: { isRunning(): boolean };\n readonly state: { get(): Readonly<{ factoryOrgId?: string; factoryProjectId?: string }> };\n readonly displayState: { get(): { pendingSuspensions: ReadonlyMap<string, { toolName: string }> } };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\ninterface SessionNotifier {\n onSessionCreated(listener: (session: LiveSession) => void): () => void;\n onSessionDeleted(listener: (session: LiveSession) => void): () => void;\n}\n\n/** The tool a session has waited on longest, and since when (epoch ms). */\nexport interface ParkedRun {\n toolName: string;\n suspendedAt: number;\n}\n\ninterface TrackedSession {\n session: LiveSession;\n seenAt: number;\n suspendedAt: Map<string, number>;\n unsubscribe: () => void;\n}\n\n/**\n * The sessions this process has materialized, by session id.\n *\n * Membership comes from the controller's notifications rather than\n * `getSessionByResource`, which hands back the pending creation — awaiting it\n * from a request blocks for as long as the session takes to materialize its\n * sandbox, minutes on a cold clone. Notifications only fire once a session\n * exists, so a read never waits.\n *\n * Whether a session is *running* or *parked* is read from the session itself,\n * never tracked here: no missed run event can leave the answer stuck. Only the\n * moment each suspension arrived is kept, since the session does not date them.\n */\nexport class LiveSessions {\n readonly #byId = new Map<string, TrackedSession>();\n readonly #parkedListeners = new Set<(session: LiveSession) => void>();\n /** A park stamp doubles as the receipt key, so two suspensions in one millisecond must not share one. */\n #lastParkStamp = 0;\n\n constructor(controller: SessionNotifier) {\n controller.onSessionCreated(session => this.#track(session));\n controller.onSessionDeleted(session => {\n const id = session.identity.getId();\n const wasParked = this.parked(id) !== undefined;\n this.#byId.get(id)?.unsubscribe();\n this.#byId.delete(id);\n if (wasParked) for (const listener of this.#parkedListeners) listener(session);\n });\n }\n\n #nextParkStamp(): number {\n this.#lastParkStamp = Math.max(Date.now(), this.#lastParkStamp + 1);\n return this.#lastParkStamp;\n }\n\n #track(session: LiveSession): void {\n const suspendedAt = new Map<string, number>();\n const unsubscribe = session.subscribe(event => {\n if (event.type === 'tool_suspended') suspendedAt.set(event.toolCallId, this.#nextParkStamp());\n else if (event.type === 'tool_suspension_cancelled') suspendedAt.delete(event.toolCallId);\n else if (event.type === 'agent_end' && event.reason !== 'suspended') suspendedAt.clear();\n else return;\n for (const listener of this.#parkedListeners) listener(session);\n });\n this.#byId.set(session.identity.getId(), { session, seenAt: Date.now(), suspendedAt, unsubscribe });\n }\n\n /** Whether the session has an agent run in flight right now. */\n isRunning(sessionId: string): boolean {\n return this.#byId.get(sessionId)?.session.run.isRunning() ?? false;\n }\n\n /** The tool the session is parked on, oldest first, or nothing when no answer is owed. */\n parked(sessionId: string): ParkedRun | undefined {\n const tracked = this.#byId.get(sessionId);\n if (!tracked) return undefined;\n let oldest: ParkedRun | undefined;\n for (const [toolCallId, { toolName }] of tracked.session.displayState.get().pendingSuspensions) {\n const suspendedAt = tracked.suspendedAt.get(toolCallId) ?? tracked.seenAt;\n if (!oldest || suspendedAt < oldest.suspendedAt) oldest = { toolName, suspendedAt };\n }\n return oldest;\n }\n\n /** Every parked session of a project, so the inbox reads no card when nothing waits. */\n parkedIn(factoryProjectId: string): Array<{ sessionId: string; run: ParkedRun }> {\n const parked: Array<{ sessionId: string; run: ParkedRun }> = [];\n for (const [sessionId, tracked] of this.#byId) {\n if (tracked.session.state.get().factoryProjectId !== factoryProjectId) continue;\n const run = this.parked(sessionId);\n if (run) parked.push({ sessionId, run });\n }\n return parked;\n }\n\n /** Fires when a session parks, is answered, or finishes a turn: whoever shows parked runs re-reads. */\n onParkedChanged(listener: (session: LiveSession) => void): () => void {\n this.#parkedListeners.add(listener);\n return () => this.#parkedListeners.delete(listener);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA0CA,IAAa,eAAb,MAA0B;CACxB,wBAAiB,IAAI,IAA4B;CACjD,mCAA4B,IAAI,IAAoC;;CAEpE,iBAAiB;CAEjB,YAAY,YAA6B;EACvC,WAAW,kBAAiB,YAAW,KAAKE,OAAO,OAAO,CAAC;EAC3D,WAAW,kBAAiB,YAAW;GACrC,MAAM,KAAK,QAAQ,SAAS,MAAM;GAClC,MAAM,YAAY,KAAK,OAAO,EAAE,MAAM,KAAA;GACtC,KAAKF,MAAM,IAAI,EAAE,CAAC,EAAE,YAAY;GAChC,KAAKA,MAAM,OAAO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,QAAQ,MAAM,IAAI,CAAC,CAAC,qBAAqB,kBAAkB;GACvE,MAAM,MAAM,KAAK,OAAO,SAAS;GACjC,IAAI,KAAK,OAAO,KAAK;IAAE;IAAW;GAAI,CAAC;EACzC;EACA,OAAO;CACT;;CAGA,gBAAgB,UAAsD;EACpE,KAAKC,iBAAiB,IAAI,QAAQ;EAClC,aAAa,KAAKA,iBAAiB,OAAO,QAAQ;CACpD;AACF"}
1
+ {"version":3,"file":"live-sessions.js","names":[],"sources":["../../src/session/live-sessions.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\n\n/** The slice of a live session this registry needs: its id, its run, its parked tools, and who it works for. */\nexport interface LiveSession {\n readonly identity: { getId(): string };\n readonly run: { isRunning(): boolean };\n readonly state: { get(): Readonly<{ factoryOrgId?: string; factoryProjectId?: string }> };\n readonly displayState: { get(): { pendingSuspensions: ReadonlyMap<string, { toolName: string }> } };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\ninterface SessionNotifier {\n onSessionCreated(listener: (session: LiveSession) => void): () => void;\n onSessionDeleted(listener: (session: LiveSession) => void): () => void;\n}\n\n/** The tool a session has waited on longest, and since when (epoch ms). */\nexport interface ParkedRun {\n toolName: string;\n suspendedAt: number;\n}\n\ninterface TrackedSession {\n session: LiveSession;\n seenAt: number;\n suspendedAt: Map<string, number>;\n unsubscribe: () => void;\n}\n\n/**\n * The sessions this process has materialized, by session id.\n *\n * Membership comes from the controller's notifications rather than\n * `getSession`, which hands back the pending creation — awaiting it\n * from a request blocks for as long as the session takes to materialize its\n * sandbox, minutes on a cold clone. Notifications only fire once a session\n * exists, so a read never waits.\n *\n * Whether a session is *running* or *parked* is read from the session itself,\n * never tracked here: no missed run event can leave the answer stuck. Only the\n * moment each suspension arrived is kept, since the session does not date them.\n */\nexport class LiveSessions {\n readonly #byId = new Map<string, TrackedSession>();\n readonly #parkedListeners = new Set<(session: LiveSession) => void>();\n /** A park stamp doubles as the receipt key, so two suspensions in one millisecond must not share one. */\n #lastParkStamp = 0;\n\n constructor(controller: SessionNotifier) {\n controller.onSessionCreated(session => this.#track(session));\n controller.onSessionDeleted(session => {\n const id = session.identity.getId();\n const wasParked = this.parked(id) !== undefined;\n this.#byId.get(id)?.unsubscribe();\n this.#byId.delete(id);\n if (wasParked) for (const listener of this.#parkedListeners) listener(session);\n });\n }\n\n #nextParkStamp(): number {\n this.#lastParkStamp = Math.max(Date.now(), this.#lastParkStamp + 1);\n return this.#lastParkStamp;\n }\n\n #track(session: LiveSession): void {\n const suspendedAt = new Map<string, number>();\n const unsubscribe = session.subscribe(event => {\n if (event.type === 'tool_suspended') suspendedAt.set(event.toolCallId, this.#nextParkStamp());\n else if (event.type === 'tool_suspension_cancelled') suspendedAt.delete(event.toolCallId);\n else if (event.type === 'agent_end' && event.reason !== 'suspended') suspendedAt.clear();\n else return;\n for (const listener of this.#parkedListeners) listener(session);\n });\n this.#byId.set(session.identity.getId(), { session, seenAt: Date.now(), suspendedAt, unsubscribe });\n }\n\n /** Whether the session has an agent run in flight right now. */\n isRunning(sessionId: string): boolean {\n return this.#byId.get(sessionId)?.session.run.isRunning() ?? false;\n }\n\n /** The tool the session is parked on, oldest first, or nothing when no answer is owed. */\n parked(sessionId: string): ParkedRun | undefined {\n const tracked = this.#byId.get(sessionId);\n if (!tracked) return undefined;\n let oldest: ParkedRun | undefined;\n for (const [toolCallId, { toolName }] of tracked.session.displayState.get().pendingSuspensions) {\n const suspendedAt = tracked.suspendedAt.get(toolCallId) ?? tracked.seenAt;\n if (!oldest || suspendedAt < oldest.suspendedAt) oldest = { toolName, suspendedAt };\n }\n return oldest;\n }\n\n /** Every parked session of a project, so the inbox reads no card when nothing waits. */\n parkedIn(factoryProjectId: string): Array<{ sessionId: string; run: ParkedRun }> {\n const parked: Array<{ sessionId: string; run: ParkedRun }> = [];\n for (const [sessionId, tracked] of this.#byId) {\n if (tracked.session.state.get().factoryProjectId !== factoryProjectId) continue;\n const run = this.parked(sessionId);\n if (run) parked.push({ sessionId, run });\n }\n return parked;\n }\n\n /** Fires when a session parks, is answered, or finishes a turn: whoever shows parked runs re-reads. */\n onParkedChanged(listener: (session: LiveSession) => void): () => void {\n this.#parkedListeners.add(listener);\n return () => this.#parkedListeners.delete(listener);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA0CA,IAAa,eAAb,MAA0B;CACxB,wBAAiB,IAAI,IAA4B;CACjD,mCAA4B,IAAI,IAAoC;;CAEpE,iBAAiB;CAEjB,YAAY,YAA6B;EACvC,WAAW,kBAAiB,YAAW,KAAK,OAAO,OAAO,CAAC;EAC3D,WAAW,kBAAiB,YAAW;GACrC,MAAM,KAAK,QAAQ,SAAS,MAAM;GAClC,MAAM,YAAY,KAAK,OAAO,EAAE,MAAM,KAAA;GACtC,KAAK,MAAM,IAAI,EAAE,CAAC,EAAE,YAAY;GAChC,KAAK,MAAM,OAAO,EAAE;GACpB,IAAI,WAAW,KAAK,MAAM,YAAY,KAAK,kBAAkB,SAAS,OAAO;EAC/E,CAAC;CACH;CAEA,iBAAyB;EACvB,KAAK,iBAAiB,KAAK,IAAI,KAAK,IAAI,GAAG,KAAK,iBAAiB,CAAC;EAClE,OAAO,KAAK;CACd;CAEA,OAAO,SAA4B;EACjC,MAAM,8BAAc,IAAI,IAAoB;EAC5C,MAAM,cAAc,QAAQ,WAAU,UAAS;GAC7C,IAAI,MAAM,SAAS,kBAAkB,YAAY,IAAI,MAAM,YAAY,KAAK,eAAe,CAAC;QACvF,IAAI,MAAM,SAAS,6BAA6B,YAAY,OAAO,MAAM,UAAU;QACnF,IAAI,MAAM,SAAS,eAAe,MAAM,WAAW,aAAa,YAAY,MAAM;QAClF;GACL,KAAK,MAAM,YAAY,KAAK,kBAAkB,SAAS,OAAO;EAChE,CAAC;EACD,KAAK,MAAM,IAAI,QAAQ,SAAS,MAAM,GAAG;GAAE;GAAS,QAAQ,KAAK,IAAI;GAAG;GAAa;EAAY,CAAC;CACpG;;CAGA,UAAU,WAA4B;EACpC,OAAO,KAAK,MAAM,IAAI,SAAS,CAAC,EAAE,QAAQ,IAAI,UAAU,KAAK;CAC/D;;CAGA,OAAO,WAA0C;EAC/C,MAAM,UAAU,KAAK,MAAM,IAAI,SAAS;EACxC,IAAI,CAAC,SAAS,OAAO,KAAA;EACrB,IAAI;EACJ,KAAK,MAAM,CAAC,YAAY,EAAE,eAAe,QAAQ,QAAQ,aAAa,IAAI,CAAC,CAAC,oBAAoB;GAC9F,MAAM,cAAc,QAAQ,YAAY,IAAI,UAAU,KAAK,QAAQ;GACnE,IAAI,CAAC,UAAU,cAAc,OAAO,aAAa,SAAS;IAAE;IAAU;GAAY;EACpF;EACA,OAAO;CACT;;CAGA,SAAS,kBAAwE;EAC/E,MAAM,SAAuD,CAAC;EAC9D,KAAK,MAAM,CAAC,WAAW,YAAY,KAAK,OAAO;GAC7C,IAAI,QAAQ,QAAQ,MAAM,IAAI,CAAC,CAAC,qBAAqB,kBAAkB;GACvE,MAAM,MAAM,KAAK,OAAO,SAAS;GACjC,IAAI,KAAK,OAAO,KAAK;IAAE;IAAW;GAAI,CAAC;EACzC;EACA,OAAO;CACT;;CAGA,gBAAgB,UAAsD;EACpE,KAAK,iBAAiB,IAAI,QAAQ;EAClC,aAAa,KAAK,iBAAiB,OAAO,QAAQ;CACpD;AACF"}
@@ -13,7 +13,7 @@ export declare const DEFAULT_REFLECTION_THRESHOLD = 40000;
13
13
  export declare function layerPersonalMemorySettings(project: MemorySettingsRecord | null, personal: MemorySettingsRecord | null): MemorySettingsRecord | null;
14
14
  export interface MemorySettingsHydrationSession {
15
15
  readonly identity: {
16
- getResourceId(): string;
16
+ getId(): string;
17
17
  };
18
18
  state: {
19
19
  get: () => MastraCodeState | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"memory-settings-hydration.d.ts","sourceRoot":"","sources":["../../src/session/memory-settings-hydration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE/D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AACvF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAG5F,yDAAyD;AACzD,eAAO,MAAM,6BAA6B,QAAS,CAAC;AACpD,eAAO,MAAM,4BAA4B,QAAS,CAAC;AAEnD;;;;;GAKG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,oBAAoB,GAAG,IAAI,EACpC,QAAQ,EAAE,oBAAoB,GAAG,IAAI,GACpC,oBAAoB,GAAG,IAAI,CAW7B;AAED,MAAM,WAAW,8BAA8B;IAC7C,QAAQ,CAAC,QAAQ,EAAE;QAAE,aAAa,IAAI,MAAM,CAAA;KAAE,CAAC;IAC/C,KAAK,EAAE;QACL,GAAG,EAAE,MAAM,eAAe,GAAG,SAAS,CAAC;QACvC,GAAG,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,eAAe,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;KAClE,CAAC;CACH;AAED,MAAM,WAAW,mCAAmC;IAClD,4FAA4F;IAC5F,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,gBAAgB,CAAC,CAAC;KAC1E,CAAC;CACH;AAED;;;;;GAKG;AACH,wBAAsB,4BAA4B,CAChD,OAAO,EAAE,8BAA8B,EACvC,EAAE,aAAa,EAAE,EAAE,mCAAmC,GACrD,OAAO,CAAC,IAAI,CAAC,CAYf"}
1
+ {"version":3,"file":"memory-settings-hydration.d.ts","sourceRoot":"","sources":["../../src/session/memory-settings-hydration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE/D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AACvF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAG5F,yDAAyD;AACzD,eAAO,MAAM,6BAA6B,QAAS,CAAC;AACpD,eAAO,MAAM,4BAA4B,QAAS,CAAC;AAEnD;;;;;GAKG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,oBAAoB,GAAG,IAAI,EACpC,QAAQ,EAAE,oBAAoB,GAAG,IAAI,GACpC,oBAAoB,GAAG,IAAI,CAW7B;AAED,MAAM,WAAW,8BAA8B;IAC7C,QAAQ,CAAC,QAAQ,EAAE;QAAE,KAAK,IAAI,MAAM,CAAA;KAAE,CAAC;IACvC,KAAK,EAAE;QACL,GAAG,EAAE,MAAM,eAAe,GAAG,SAAS,CAAC;QACvC,GAAG,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,eAAe,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;KAClE,CAAC;CACH;AAED,MAAM,WAAW,mCAAmC;IAClD,4FAA4F;IAC5F,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,gBAAgB,CAAC,CAAC;KAC1E,CAAC;CACH;AAED;;;;;GAKG;AACH,wBAAsB,4BAA4B,CAChD,OAAO,EAAE,8BAA8B,EACvC,EAAE,aAAa,EAAE,EAAE,mCAAmC,GACrD,OAAO,CAAC,IAAI,CAAC,CAYf"}
@@ -31,7 +31,8 @@ async function hydrateSessionMemorySettings(session, { sourceControl }) {
31
31
  const state = session.state.get() ?? {};
32
32
  if (Boolean(state.factoryProjectId) && hasResolvedOrg(state.factoryOrgId)) return;
33
33
  try {
34
- await seedSessionOrg(session, (await sourceControl.sessions.getBySessionId(session.identity.getResourceId()))?.orgId);
34
+ const record = await sourceControl.sessions.getBySessionId(session.identity.getId());
35
+ await seedSessionOrg(session, record?.orgId);
35
36
  } catch (error) {
36
37
  console.warn("[Factory session hydration] Unable to resolve the session organization.", error);
37
38
  if (!session.state.get()?.factoryOrgId) await seedSessionOrg(session, void 0);
@@ -1 +1 @@
1
- {"version":3,"file":"memory-settings-hydration.js","names":[],"sources":["../../src/session/memory-settings-hydration.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\n\nimport type { MemorySettingsRecord } from '../storage/domains/memory-settings/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { hasResolvedOrg, seedSessionOrg } from './org-seed.js';\n\n/** Default thresholds mirror the TUI `/om` fallbacks. */\nexport const DEFAULT_OBSERVATION_THRESHOLD = 30_000;\nexport const DEFAULT_REFLECTION_THRESHOLD = 40_000;\n\n/**\n * Layer a channel sender's own row over the project's shared row. The sender\n * wins only for knobs they saved; an unsaved (`null`) knob keeps the project's\n * value rather than resetting to Auto or the built-in default, because the\n * project's choice may be the only credentialed one.\n */\nexport function layerPersonalMemorySettings(\n project: MemorySettingsRecord | null,\n personal: MemorySettingsRecord | null,\n): MemorySettingsRecord | null {\n if (!personal) return project;\n if (!project) return personal;\n return {\n ...project,\n observerModelId: personal.observerModelId ?? project.observerModelId,\n reflectorModelId: personal.reflectorModelId ?? project.reflectorModelId,\n observationThreshold: personal.observationThreshold ?? project.observationThreshold,\n reflectionThreshold: personal.reflectionThreshold ?? project.reflectionThreshold,\n observeAttachments: personal.observeAttachments ?? project.observeAttachments,\n };\n}\n\nexport interface MemorySettingsHydrationSession {\n readonly identity: { getResourceId(): string };\n state: {\n get: () => MastraCodeState | undefined;\n set: (updates: Partial<MastraCodeState>) => Promise<void> | void;\n };\n}\n\nexport interface MemorySettingsHydrationDependencies {\n /** GitHub-integration source-control rows — the only creator of web user sessions today. */\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'getBySessionId'>;\n };\n}\n\n/**\n * Seed a freshly created controller session's tenant org from its source-control\n * row. Memory settings remain DB-authoritative and are loaded into request\n * context for each invocation instead of being copied into mutable session\n * state.\n */\nexport async function hydrateSessionMemorySettings(\n session: MemorySettingsHydrationSession,\n { sourceControl }: MemorySettingsHydrationDependencies,\n): Promise<void> {\n const state: Partial<MastraCodeState> = session.state.get() ?? {};\n const isFactoryRun = Boolean(state.factoryProjectId);\n if (isFactoryRun && hasResolvedOrg(state.factoryOrgId)) return;\n\n try {\n const record = await sourceControl.sessions.getBySessionId(session.identity.getResourceId());\n await seedSessionOrg(session, record?.orgId);\n } catch (error) {\n console.warn('[Factory session hydration] Unable to resolve the session organization.', error);\n if (!session.state.get()?.factoryOrgId) await seedSessionOrg(session, undefined);\n }\n}\n"],"mappings":";;;AAOA,MAAa,gCAAgC;AAC7C,MAAa,+BAA+B;;;;;;;AAQ5C,SAAgB,4BACd,SACA,UAC6B;CAC7B,IAAI,CAAC,UAAU,OAAO;CACtB,IAAI,CAAC,SAAS,OAAO;CACrB,OAAO;EACL,GAAG;EACH,iBAAiB,SAAS,mBAAmB,QAAQ;EACrD,kBAAkB,SAAS,oBAAoB,QAAQ;EACvD,sBAAsB,SAAS,wBAAwB,QAAQ;EAC/D,qBAAqB,SAAS,uBAAuB,QAAQ;EAC7D,oBAAoB,SAAS,sBAAsB,QAAQ;CAC7D;AACF;;;;;;;AAuBA,eAAsB,6BACpB,SACA,EAAE,iBACa;CACf,MAAM,QAAkC,QAAQ,MAAM,IAAI,KAAK,CAAC;CAEhE,IADqB,QAAQ,MAAM,gBACpB,KAAK,eAAe,MAAM,YAAY,GAAG;CAExD,IAAI;EAEF,MAAM,eAAe,UAAS,MADT,cAAc,SAAS,eAAe,QAAQ,SAAS,cAAc,CAAC,EAAA,EACrD,KAAK;CAC7C,SAAS,OAAO;EACd,QAAQ,KAAK,2EAA2E,KAAK;EAC7F,IAAI,CAAC,QAAQ,MAAM,IAAI,CAAC,EAAE,cAAc,MAAM,eAAe,SAAS,KAAA,CAAS;CACjF;AACF"}
1
+ {"version":3,"file":"memory-settings-hydration.js","names":[],"sources":["../../src/session/memory-settings-hydration.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\n\nimport type { MemorySettingsRecord } from '../storage/domains/memory-settings/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { hasResolvedOrg, seedSessionOrg } from './org-seed.js';\n\n/** Default thresholds mirror the TUI `/om` fallbacks. */\nexport const DEFAULT_OBSERVATION_THRESHOLD = 30_000;\nexport const DEFAULT_REFLECTION_THRESHOLD = 40_000;\n\n/**\n * Layer a channel sender's own row over the project's shared row. The sender\n * wins only for knobs they saved; an unsaved (`null`) knob keeps the project's\n * value rather than resetting to Auto or the built-in default, because the\n * project's choice may be the only credentialed one.\n */\nexport function layerPersonalMemorySettings(\n project: MemorySettingsRecord | null,\n personal: MemorySettingsRecord | null,\n): MemorySettingsRecord | null {\n if (!personal) return project;\n if (!project) return personal;\n return {\n ...project,\n observerModelId: personal.observerModelId ?? project.observerModelId,\n reflectorModelId: personal.reflectorModelId ?? project.reflectorModelId,\n observationThreshold: personal.observationThreshold ?? project.observationThreshold,\n reflectionThreshold: personal.reflectionThreshold ?? project.reflectionThreshold,\n observeAttachments: personal.observeAttachments ?? project.observeAttachments,\n };\n}\n\nexport interface MemorySettingsHydrationSession {\n readonly identity: { getId(): string };\n state: {\n get: () => MastraCodeState | undefined;\n set: (updates: Partial<MastraCodeState>) => Promise<void> | void;\n };\n}\n\nexport interface MemorySettingsHydrationDependencies {\n /** GitHub-integration source-control rows — the only creator of web user sessions today. */\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'getBySessionId'>;\n };\n}\n\n/**\n * Seed a freshly created controller session's tenant org from its source-control\n * row. Memory settings remain DB-authoritative and are loaded into request\n * context for each invocation instead of being copied into mutable session\n * state.\n */\nexport async function hydrateSessionMemorySettings(\n session: MemorySettingsHydrationSession,\n { sourceControl }: MemorySettingsHydrationDependencies,\n): Promise<void> {\n const state: Partial<MastraCodeState> = session.state.get() ?? {};\n const isFactoryRun = Boolean(state.factoryProjectId);\n if (isFactoryRun && hasResolvedOrg(state.factoryOrgId)) return;\n\n try {\n const record = await sourceControl.sessions.getBySessionId(session.identity.getId());\n await seedSessionOrg(session, record?.orgId);\n } catch (error) {\n console.warn('[Factory session hydration] Unable to resolve the session organization.', error);\n if (!session.state.get()?.factoryOrgId) await seedSessionOrg(session, undefined);\n }\n}\n"],"mappings":";;;AAOA,MAAa,gCAAgC;AAC7C,MAAa,+BAA+B;;;;;;;AAQ5C,SAAgB,4BACd,SACA,UAC6B;CAC7B,IAAI,CAAC,UAAU,OAAO;CACtB,IAAI,CAAC,SAAS,OAAO;CACrB,OAAO;EACL,GAAG;EACH,iBAAiB,SAAS,mBAAmB,QAAQ;EACrD,kBAAkB,SAAS,oBAAoB,QAAQ;EACvD,sBAAsB,SAAS,wBAAwB,QAAQ;EAC/D,qBAAqB,SAAS,uBAAuB,QAAQ;EAC7D,oBAAoB,SAAS,sBAAsB,QAAQ;CAC7D;AACF;;;;;;;AAuBA,eAAsB,6BACpB,SACA,EAAE,iBACa;CACf,MAAM,QAAkC,QAAQ,MAAM,IAAI,KAAK,CAAC;CAEhE,IADqB,QAAQ,MAAM,gBACpB,KAAK,eAAe,MAAM,YAAY,GAAG;CAExD,IAAI;EACF,MAAM,SAAS,MAAM,cAAc,SAAS,eAAe,QAAQ,SAAS,MAAM,CAAC;EACnF,MAAM,eAAe,SAAS,QAAQ,KAAK;CAC7C,SAAS,OAAO;EACd,QAAQ,KAAK,2EAA2E,KAAK;EAC7F,IAAI,CAAC,QAAQ,MAAM,IAAI,CAAC,EAAE,cAAc,MAAM,eAAe,SAAS,KAAA,CAAS;CACjF;AACF"}
@@ -0,0 +1,105 @@
1
+ import type { StorageThreadType } from '@mastra/core/memory';
2
+ import type { MemoryStorage } from '@mastra/core/storage';
3
+ import type { SourceControlSession } from '../storage/domains/source-control/base.js';
4
+ import type { WorkItemRow } from '../storage/domains/work-items/base.js';
5
+ export interface SessionResourceMigrationDeps {
6
+ sessions: {
7
+ listSessionsAwaitingResourceMigration(): Promise<SourceControlSession[]>;
8
+ markResourcesMigrated(sessionId: string): Promise<void>;
9
+ };
10
+ workItems: {
11
+ listRunBoundItems(sessionId: string): Promise<(Pick<WorkItemRow, 'externalSource' | 'metadata'> | null)[]>;
12
+ moveRunBindingsToResource(input: {
13
+ sessionId: string;
14
+ resourceId: string;
15
+ }): Promise<number>;
16
+ };
17
+ /** Absent when the integrations domain is not ready; subscriptions then stay where they are. */
18
+ integrations?: {
19
+ moveSubscriptionsToResource(input: {
20
+ fromResourceId: string;
21
+ toResourceId: string;
22
+ }): Promise<number>;
23
+ };
24
+ memory: Pick<MemoryStorage, 'listThreads' | 'patchThread' | 'getObservationalMemory' | 'supportsObservationalMemory'>;
25
+ /**
26
+ * Moves a thread with everything keyed by its resource, such as observation vectors. Pass the
27
+ * sessions' `Memory`; the bare memory store only moves the thread and its messages.
28
+ */
29
+ threads: {
30
+ updateThreadResourceId(input: {
31
+ threadId: string;
32
+ resourceId: string;
33
+ }): Promise<StorageThreadType>;
34
+ };
35
+ }
36
+ export interface SessionResourceMigrationReport {
37
+ sessions: number;
38
+ factorySessions: number;
39
+ userSessions: number;
40
+ /** Runs on untrusted content; they keep their own resource. */
41
+ isolatedSessions: number;
42
+ /** Factory-owned sessions with no Factory to move them onto; left untouched. */
43
+ skipped: string[];
44
+ /** Sessions whose move threw; the next startup retries them. */
45
+ failed: string[];
46
+ /**
47
+ * Moved sessions whose subscriptions couldn't move because the integrations
48
+ * domain wasn't ready; left unmarked so a later startup moves them.
49
+ */
50
+ subscriptionsPending: string[];
51
+ threads: number;
52
+ runBindings: number;
53
+ subscriptions: number;
54
+ /** Moved sessions whose resource-scoped observational memory stays under their old resource. */
55
+ resourceObservationsLeft: string[];
56
+ }
57
+ /**
58
+ * The memory resource a session belongs to: its Factory for runs, side
59
+ * sessions and Slack channel threads, its owner for sessions a person opened,
60
+ * private side sessions and Slack DMs. A run on untrusted content (a pull request, or a card
61
+ * written outside the write-access circle) keeps its own resource, like a new
62
+ * run would; so does a run whose work item no longer loads, since nothing then
63
+ * shows its content was trusted. `null` when a Factory-owned session has no
64
+ * Factory recorded — guessing would merge it into the wrong resource.
65
+ */
66
+ export declare function sessionMemoryResource(session: SourceControlSession, boundItems: (Pick<WorkItemRow, 'externalSource' | 'metadata'> | null)[]): {
67
+ owner: 'factory' | 'user' | 'isolated';
68
+ resourceId: string | null;
69
+ };
70
+ /**
71
+ * Move sessions stored under the legacy `resourceId = sessionId` onto their
72
+ * Factory or user resource. Threads keep their id (`threadId === sessionId`)
73
+ * and get `factorySessionId` so per-session listings still find them.
74
+ *
75
+ * Threads move through the sessions' `Memory`, so their observation vectors
76
+ * follow them and recall search finds their past observations under the new
77
+ * resource. Every write only touches values still equal to the session id, so
78
+ * a rerun is a no-op and a crash leaves a state the next run resumes from. A
79
+ * session is marked once moved, so later starts only read sessions that are not
80
+ * (new sessions are created marked).
81
+ * Nothing is deleted. Thread-scoped observational memory is keyed by thread id
82
+ * and keeps working. Resource-scoped observational memory written under
83
+ * `resource:<sessionId>` stays under that key and is no longer read: several
84
+ * sessions merge into one resource, and their records cannot be merged.
85
+ */
86
+ export declare function migrateSessionResources(deps: SessionResourceMigrationDeps): Promise<SessionResourceMigrationReport>;
87
+ export interface SessionVisibilityBackfillDeps {
88
+ sessions: {
89
+ listSessionsAwaitingVisibilityCheck(): Promise<SourceControlSession[]>;
90
+ markVisibilityChecked(sessionId: string, options: {
91
+ makePrivate: boolean;
92
+ }): Promise<void>;
93
+ };
94
+ workItems: Pick<SessionResourceMigrationDeps['workItems'], 'listRunBoundItems'>;
95
+ memory: Pick<MemoryStorage, 'getThreadById'>;
96
+ }
97
+ /**
98
+ * Mark shared user sessions private when their conversation lives on their owner's resource.
99
+ * The resource already keeps teammates out of such a session; this makes lists agree, so they
100
+ * stop seeing a session they can't open. Sessions shared onto their Factory, runs, Slack threads
101
+ * and side sessions are left alone. Each session is checked once: new sessions start checked,
102
+ * and a session that throws stays unchecked so the next start retries it.
103
+ */
104
+ export declare function privatizeOwnerResourceSessions(deps: SessionVisibilityBackfillDeps): Promise<number>;
105
+ //# sourceMappingURL=resource-migration.d.ts.map
@@ -0,0 +1 @@
1
+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