@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":"session-retirement.js","names":["#invalidateSession","#sandbox","#warn","#destroyTimeoutMs","#locks","#withSessionLock","#retireSession","#recreateSessionSandbox","#teardownSessionSandbox","#invalidate","#destroyDetachedSandbox","#releaseSandbox","#destroyForRecreate","#settledWithin","#destroyDetachedForRecreate","#destroyDirectly"],"sources":["../../src/sandbox/session-retirement.ts"],"sourcesContent":["import type { FactorySandbox, WorkspaceSandbox } from '@mastra/core/workspace';\n\nimport { destroyDetachedSessionSandbox, releaseSessionSandbox } from '../integrations/github/sandbox-release.js';\nimport { DEFAULT_COMMAND_TIMEOUT_MS, runTeardownCommand } from '../integrations/github/sandbox.js';\nimport { peekSessionEnvironmentTeardown } from '../session/environment-state-processor.js';\nimport type {\n ProjectRepository,\n SourceControlSession,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { requireExec } from './materialization.js';\nimport { evictSessionSandbox, peekSessionSandbox } from './session-sandbox.js';\n\ntype WarningLogger = (message: string, details: Record<string, unknown>) => void;\n\nexport interface SessionRetirementCoordinatorOptions {\n invalidateSession?: (sessionId: string) => Promise<void> | void;\n /**\n * The deploy's sandbox configuration. Used to destroy a deleted session's\n * VM by identity when this process never attached to it (after a restart,\n * or on another replica). Recreate uses it the same way.\n */\n sandbox?: FactorySandbox;\n warn?: WarningLogger;\n /** How long recreate waits on a started sandbox's lifecycle destroy before falling back. */\n destroyTimeoutMs?: number;\n}\n\nexport interface RecreateSessionSandboxInput {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n sessionId: string;\n}\n\nconst DEFAULT_DESTROY_TIMEOUT_MS = 30_000;\n\n/**\n * A provider error meaning the VM is already gone: 410, or a 404 the proxy\n * marks `not_found` (or leaves uncoded). A routing 404 with another code is\n * not proof the VM is gone.\n */\nfunction isSandboxGoneError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n const { status, code } = error as { status?: unknown; code?: unknown };\n if (status === 410) return true;\n return status === 404 && (code === undefined || code === null || code === 'not_found');\n}\n\nexport interface RetireSessionInput {\n sourceControl: SourceControlStorageHandle;\n /** When provided, deleting the session row also strips its work-item refs. */\n workItems?: Pick<WorkItemsStorage, 'clearSessionReferences'>;\n orgId: string;\n sessionId: string;\n deleteSession: boolean;\n}\n\nfunction boundedError(error: unknown): string {\n const detail = error instanceof Error ? error.message : String(error);\n if (detail.length <= 2000) return detail;\n return `${detail.slice(0, 200)}...${detail.slice(-1797)}`;\n}\n\n/**\n * Owns terminal and destructive session cleanup. Each session is serialized so\n * duplicate role bindings and competing deletion/transition requests cannot\n * run teardown concurrently.\n *\n * Sandbox identity is the session id: retirement stops (or, for deleted\n * sessions, destroys) the sandbox this process holds in the session memo.\n * Sessions opened on another replica (or before a restart) have no memo entry\n * here: stopping them is left to the provider's idle lifecycle, but deleting a\n * materialized session destroys its VM by identity through the configured\n * sandbox. Providers such as E2B keep paused VMs forever, so the row's\n * deletion must never orphan one.\n */\nexport class SessionRetirementCoordinator {\n readonly #invalidateSession: NonNullable<SessionRetirementCoordinatorOptions['invalidateSession']>;\n readonly #sandbox: FactorySandbox | undefined;\n readonly #warn: WarningLogger;\n readonly #destroyTimeoutMs: number;\n readonly #locks = new Map<string, Promise<unknown>>();\n\n constructor(options: SessionRetirementCoordinatorOptions = {}) {\n this.#invalidateSession = options.invalidateSession ?? (() => {});\n this.#sandbox = options.sandbox;\n this.#warn = options.warn ?? ((message, details) => console.warn(`[Mastra Factory] ${message}`, details));\n this.#destroyTimeoutMs = options.destroyTimeoutMs ?? DEFAULT_DESTROY_TIMEOUT_MS;\n }\n\n async retireSession(input: RetireSessionInput): Promise<void> {\n await this.#withSessionLock(input.sessionId, () => this.#retireSession(input));\n }\n\n /**\n * Destroy a session's sandbox so its next message boots a fresh VM from the\n * template, keeping the session row, its conversation, and work-item refs.\n * Skips teardown commands, and works without a memo entry in this process\n * by destroying a detached instance built from the persisted `sandboxId`.\n * A destroy failure keeps the persisted id so a retry can reach the VM.\n */\n async recreateSessionSandbox(input: RecreateSessionSandboxInput): Promise<'recreated' | 'not-found'> {\n return this.#withSessionLock(input.sessionId, () => this.#recreateSessionSandbox(input));\n }\n\n async #withSessionLock<T>(sessionId: string, run: () => Promise<T>): Promise<T> {\n const previous = this.#locks.get(sessionId) ?? Promise.resolve();\n const current = previous.catch(() => {}).then(run);\n this.#locks.set(sessionId, current);\n try {\n return await current;\n } finally {\n if (this.#locks.get(sessionId) === current) this.#locks.delete(sessionId);\n }\n }\n\n async retireWorkItemSessions(options: {\n workItems: Pick<WorkItemsStorage, 'get'>;\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n workItemId: string;\n }): Promise<void> {\n const item = await options.workItems.get({ orgId: options.orgId, id: options.workItemId });\n if (!item) return;\n const sessionIds = [...new Set(Object.values(item.sessions).map(session => session.sessionId))];\n await Promise.all(\n sessionIds.map(sessionId =>\n this.retireSession({\n sourceControl: options.sourceControl,\n orgId: options.orgId,\n sessionId,\n deleteSession: false,\n }),\n ),\n );\n }\n\n async retireProjectRepositorySessions(options: {\n sourceControl: SourceControlStorageHandle;\n workItems?: Pick<WorkItemsStorage, 'clearSessionReferences'>;\n orgId: string;\n projectRepositoryId: string;\n }): Promise<void> {\n const sessions = await options.sourceControl.sessions.listByProjectRepository({\n projectRepositoryId: options.projectRepositoryId,\n });\n await Promise.all(\n sessions.map(session =>\n this.retireSession({\n sourceControl: options.sourceControl,\n ...(options.workItems ? { workItems: options.workItems } : {}),\n orgId: options.orgId,\n sessionId: session.sessionId,\n deleteSession: true,\n }),\n ),\n );\n }\n\n async #retireSession(input: RetireSessionInput): Promise<void> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return;\n\n try {\n await this.#teardownSessionSandbox(input, session);\n } finally {\n await this.#invalidate(session);\n\n if (input.deleteSession) {\n // Refs first: clearing again is a no-op, but refs on a deleted row would dangle forever.\n await input.workItems?.clearSessionReferences({ orgId: input.orgId, sessionId: input.sessionId });\n await input.sourceControl.sessions.delete(session.id);\n }\n }\n }\n\n async #teardownSessionSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<void> {\n const entry = peekSessionSandbox(session.id);\n if (!entry) {\n await this.#destroyDetachedSandbox(input, session);\n return;\n }\n\n // A session booted from its factory environment tears every repository\n // down in position order, each in its own directory; a failure is logged\n // and the next repository still runs.\n const environmentTeardown = peekSessionEnvironmentTeardown(session.sessionId);\n if (environmentTeardown.length > 0) {\n for (const repo of environmentTeardown) {\n try {\n await runTeardownCommand(requireExec(entry.sandbox), repo.dir, repo.command, {\n timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS,\n });\n } catch (error) {\n this.#warn('Factory teardown command failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n repository: repo.slug,\n error: boundedError(error),\n });\n }\n }\n await this.#releaseSandbox(input, session);\n return;\n }\n\n let projectRepository: ProjectRepository | null | undefined;\n try {\n projectRepository = session.projectRepositoryId\n ? await input.sourceControl.projectRepositories.get({ orgId: input.orgId, id: session.projectRepositoryId })\n : null;\n } catch (error) {\n this.#warn('Factory repository settings could not be loaded for session retirement', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n\n // An unresolved workdir means the sandbox never started in this process:\n // nothing was set up, so there is nothing for a teardown command to undo.\n if (projectRepository?.teardownCommand && entry.workdir) {\n try {\n await runTeardownCommand(requireExec(entry.sandbox), entry.workdir, projectRepository.teardownCommand, {\n timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS,\n });\n } catch (error) {\n this.#warn('Factory teardown command failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n\n await this.#releaseSandbox(input, session);\n }\n\n /**\n * Destroy a deleted session's VM that this process never attached to. Only\n * for sessions that materialized (a persisted `sandboxId`): nothing is\n * started, no teardown command runs — the provider kills by identity.\n */\n async #destroyDetachedSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<void> {\n if (!input.deleteSession || !session.sandboxId || !this.#sandbox) return;\n try {\n await destroyDetachedSessionSandbox({ sandbox: this.#sandbox, session });\n } catch (error) {\n this.#warn('Factory detached session sandbox destroy failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n\n /** Bump the session's workspace generation; a failing unregister is logged, never fatal. */\n async #invalidate(session: SourceControlSession): Promise<void> {\n try {\n await this.#invalidateSession(session.sessionId);\n } catch (error) {\n this.#warn('Factory session workspace cache invalidation failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n\n async #recreateSessionSandbox(input: RecreateSessionSandboxInput): Promise<'recreated' | 'not-found'> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return 'not-found';\n\n // Bump the generation first so an in-flight start hook for the old\n // instance throws instead of republishing its sandbox id.\n await this.#invalidate(session);\n const entry = peekSessionSandbox(session.id);\n evictSessionSandbox(session.id);\n\n await this.#destroyForRecreate(session, entry?.sandbox);\n await input.sourceControl.sessions.setSandbox({ id: session.id, sandboxId: null, sandboxWorkdir: '' });\n\n // A resolve that ran between the eviction and clearing the id could have\n // built a fresh instance from the old `sandboxId`; drop it and fence it.\n evictSessionSandbox(session.id);\n await this.#invalidate(session);\n return 'recreated';\n }\n\n /**\n * Destroy the session's VM. `_destroy()` silently no-ops on a never-started\n * (`pending`) instance, so pending and detached instances call the\n * provider's `destroy()` directly; a started instance goes through the\n * lifecycle wrapper, bounded so a hung start can't hold the session lock.\n */\n async #destroyForRecreate(session: SourceControlSession, memo: WorkspaceSandbox | undefined): Promise<void> {\n const lifecycle = memo as { _destroy?: () => Promise<void> } | undefined;\n if (memo && memo.status !== 'pending' && lifecycle?._destroy) {\n const destroying = lifecycle._destroy.call(memo);\n if (await this.#settledWithin(destroying)) {\n memo.status = 'destroyed';\n return;\n }\n // Load-bearing: once the hung start settles, this destroy reaps any VM it\n // provisioned. Its rejection must never surface as unhandled.\n destroying.catch(error =>\n this.#warn('Factory sandbox destroy failed after recreate stopped waiting', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n error: boundedError(error),\n }),\n );\n if (!this.#sandbox) {\n throw new Error(\n 'Timed out destroying the session sandbox, and no sandbox provider is configured to retry by identity.',\n );\n }\n await this.#destroyDetachedForRecreate(this.#sandbox, session);\n memo.status = 'destroyed';\n return;\n }\n\n if (memo) {\n await this.#destroyDirectly(memo);\n memo.status = 'destroyed';\n return;\n }\n\n // No instance in this process (restart, or another replica opened it):\n // destroy through a never-started instance carrying the persisted id.\n // Unlike retirement, this runs without a `sandboxId` too: E2B and Docker\n // find the VM by session identity, and Platform's destroy no-ops safely.\n if (this.#sandbox) await this.#destroyDetachedForRecreate(this.#sandbox, session);\n }\n\n async #destroyDetachedForRecreate(sandbox: FactorySandbox, session: SourceControlSession): Promise<void> {\n try {\n await destroyDetachedSessionSandbox({ sandbox, session });\n } catch (error) {\n if (!isSandboxGoneError(error)) throw error;\n }\n }\n\n /** True when the destroy finished in time; false on timeout. Gone-VM errors count as finished. */\n async #settledWithin(destroying: Promise<void>): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<false>(resolve => {\n timer = setTimeout(() => resolve(false), this.#destroyTimeoutMs);\n });\n try {\n return await Promise.race([destroying.then(() => true as const), timedOut]);\n } catch (error) {\n if (isSandboxGoneError(error)) return true;\n throw error;\n } finally {\n clearTimeout(timer);\n }\n }\n\n async #destroyDirectly(sandbox: WorkspaceSandbox): Promise<void> {\n try {\n await sandbox.destroy?.();\n } catch (error) {\n if (!isSandboxGoneError(error)) throw error;\n }\n }\n\n async #releaseSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<void> {\n try {\n await releaseSessionSandbox({ sessionId: session.id, destroy: input.deleteSession });\n } catch (error) {\n this.#warn('Factory session sandbox release failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n}\n"],"mappings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a,KAAK;GAC3B,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"session-retirement.js","names":[],"sources":["../../src/sandbox/session-retirement.ts"],"sourcesContent":["import type { FactorySandbox, WorkspaceSandbox } from '@mastra/core/workspace';\n\nimport { destroyDetachedSessionSandbox, releaseSessionSandbox } from '../integrations/github/sandbox-release.js';\nimport { DEFAULT_COMMAND_TIMEOUT_MS, runTeardownCommand } from '../integrations/github/sandbox.js';\nimport { peekSessionEnvironmentTeardown } from '../session/environment-state-processor.js';\nimport type {\n ProjectRepository,\n SourceControlSession,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { requireExec } from './materialization.js';\nimport { evictSessionSandbox, peekSessionSandbox } from './session-sandbox.js';\n\ntype WarningLogger = (message: string, details: Record<string, unknown>) => void;\n\nexport interface SessionRetirementCoordinatorOptions {\n invalidateSession?: (sessionId: string) => Promise<void> | void;\n /**\n * The deploy's sandbox configuration. Used to destroy a deleted session's\n * VM by identity when this process never attached to it (after a restart,\n * or on another replica). Recreate uses it the same way.\n */\n sandbox?: FactorySandbox;\n warn?: WarningLogger;\n /** How long recreate waits on a started sandbox's lifecycle destroy before falling back. */\n destroyTimeoutMs?: number;\n}\n\nexport interface RecreateSessionSandboxInput {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n sessionId: string;\n}\n\nconst DEFAULT_DESTROY_TIMEOUT_MS = 30_000;\n\n/**\n * A provider error meaning the VM is already gone: 410, or a 404 the proxy\n * marks `not_found` (or leaves uncoded). A routing 404 with another code is\n * not proof the VM is gone.\n */\nfunction isSandboxGoneError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n const { status, code } = error as { status?: unknown; code?: unknown };\n if (status === 410) return true;\n return status === 404 && (code === undefined || code === null || code === 'not_found');\n}\n\nexport interface RetireSessionInput {\n sourceControl: SourceControlStorageHandle;\n /** When provided, deleting the session row also strips its work-item refs. */\n workItems?: Pick<WorkItemsStorage, 'clearSessionReferences'>;\n orgId: string;\n sessionId: string;\n deleteSession: boolean;\n}\n\nfunction boundedError(error: unknown): string {\n const detail = error instanceof Error ? error.message : String(error);\n if (detail.length <= 2000) return detail;\n return `${detail.slice(0, 200)}...${detail.slice(-1797)}`;\n}\n\n/**\n * Owns terminal and destructive session cleanup. Each session is serialized so\n * duplicate role bindings and competing deletion/transition requests cannot\n * run teardown concurrently.\n *\n * Sandbox identity is the session id: retirement stops (or, for deleted\n * sessions, destroys) the sandbox this process holds in the session memo.\n * Sessions opened on another replica (or before a restart) have no memo entry\n * here: stopping them is left to the provider's idle lifecycle, but deleting a\n * materialized session destroys its VM by identity through the configured\n * sandbox. Providers such as E2B keep paused VMs forever, so the row's\n * deletion must never orphan one.\n */\nexport class SessionRetirementCoordinator {\n readonly #invalidateSession: NonNullable<SessionRetirementCoordinatorOptions['invalidateSession']>;\n readonly #sandbox: FactorySandbox | undefined;\n readonly #warn: WarningLogger;\n readonly #destroyTimeoutMs: number;\n readonly #locks = new Map<string, Promise<unknown>>();\n\n constructor(options: SessionRetirementCoordinatorOptions = {}) {\n this.#invalidateSession = options.invalidateSession ?? (() => {});\n this.#sandbox = options.sandbox;\n this.#warn = options.warn ?? ((message, details) => console.warn(`[Mastra Factory] ${message}`, details));\n this.#destroyTimeoutMs = options.destroyTimeoutMs ?? DEFAULT_DESTROY_TIMEOUT_MS;\n }\n\n async retireSession(input: RetireSessionInput): Promise<void> {\n await this.#withSessionLock(input.sessionId, () => this.#retireSession(input));\n }\n\n /**\n * Destroy a session's sandbox so its next message boots a fresh VM from the\n * template, keeping the session row, its conversation, and work-item refs.\n * Skips teardown commands, and works without a memo entry in this process\n * by destroying a detached instance built from the persisted `sandboxId`.\n * A destroy failure keeps the persisted id so a retry can reach the VM.\n */\n async recreateSessionSandbox(input: RecreateSessionSandboxInput): Promise<'recreated' | 'not-found'> {\n return this.#withSessionLock(input.sessionId, () => this.#recreateSessionSandbox(input));\n }\n\n async #withSessionLock<T>(sessionId: string, run: () => Promise<T>): Promise<T> {\n const previous = this.#locks.get(sessionId) ?? Promise.resolve();\n const current = previous.catch(() => {}).then(run);\n this.#locks.set(sessionId, current);\n try {\n return await current;\n } finally {\n if (this.#locks.get(sessionId) === current) this.#locks.delete(sessionId);\n }\n }\n\n async retireWorkItemSessions(options: {\n workItems: Pick<WorkItemsStorage, 'get'>;\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n workItemId: string;\n }): Promise<void> {\n const item = await options.workItems.get({ orgId: options.orgId, id: options.workItemId });\n if (!item) return;\n const sessionIds = [...new Set(Object.values(item.sessions).map(session => session.sessionId))];\n await Promise.all(\n sessionIds.map(sessionId =>\n this.retireSession({\n sourceControl: options.sourceControl,\n orgId: options.orgId,\n sessionId,\n deleteSession: false,\n }),\n ),\n );\n }\n\n async retireProjectRepositorySessions(options: {\n sourceControl: SourceControlStorageHandle;\n workItems?: Pick<WorkItemsStorage, 'clearSessionReferences'>;\n orgId: string;\n projectRepositoryId: string;\n }): Promise<void> {\n const sessions = await options.sourceControl.sessions.listByProjectRepository({\n projectRepositoryId: options.projectRepositoryId,\n });\n await Promise.all(\n sessions.map(session =>\n this.retireSession({\n sourceControl: options.sourceControl,\n ...(options.workItems ? { workItems: options.workItems } : {}),\n orgId: options.orgId,\n sessionId: session.sessionId,\n deleteSession: true,\n }),\n ),\n );\n }\n\n async #retireSession(input: RetireSessionInput): Promise<void> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return;\n\n try {\n await this.#teardownSessionSandbox(input, session);\n } finally {\n await this.#invalidate(session);\n\n if (input.deleteSession) {\n // Refs first: clearing again is a no-op, but refs on a deleted row would dangle forever.\n await input.workItems?.clearSessionReferences({ orgId: input.orgId, sessionId: input.sessionId });\n await input.sourceControl.sessions.delete(session.id);\n }\n }\n }\n\n async #teardownSessionSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<void> {\n const entry = peekSessionSandbox(session.id);\n if (!entry) {\n await this.#destroyDetachedSandbox(input, session);\n return;\n }\n\n // A session booted from its factory environment tears every repository\n // down in position order, each in its own directory; a failure is logged\n // and the next repository still runs.\n const environmentTeardown = peekSessionEnvironmentTeardown(session.sessionId);\n if (environmentTeardown.length > 0) {\n for (const repo of environmentTeardown) {\n try {\n await runTeardownCommand(requireExec(entry.sandbox), repo.dir, repo.command, {\n timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS,\n });\n } catch (error) {\n this.#warn('Factory teardown command failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n repository: repo.slug,\n error: boundedError(error),\n });\n }\n }\n await this.#releaseSandbox(input, session);\n return;\n }\n\n let projectRepository: ProjectRepository | null | undefined;\n try {\n projectRepository = session.projectRepositoryId\n ? await input.sourceControl.projectRepositories.get({ orgId: input.orgId, id: session.projectRepositoryId })\n : null;\n } catch (error) {\n this.#warn('Factory repository settings could not be loaded for session retirement', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n\n // An unresolved workdir means the sandbox never started in this process:\n // nothing was set up, so there is nothing for a teardown command to undo.\n if (projectRepository?.teardownCommand && entry.workdir) {\n try {\n await runTeardownCommand(requireExec(entry.sandbox), entry.workdir, projectRepository.teardownCommand, {\n timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS,\n });\n } catch (error) {\n this.#warn('Factory teardown command failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n\n await this.#releaseSandbox(input, session);\n }\n\n /**\n * Destroy a deleted session's VM that this process never attached to. Only\n * for sessions that materialized (a persisted `sandboxId`): nothing is\n * started, no teardown command runs — the provider kills by identity.\n */\n async #destroyDetachedSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<void> {\n if (!input.deleteSession || !session.sandboxId || !this.#sandbox) return;\n try {\n await destroyDetachedSessionSandbox({ sandbox: this.#sandbox, session });\n } catch (error) {\n this.#warn('Factory detached session sandbox destroy failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n\n /** Bump the session's workspace generation; a failing unregister is logged, never fatal. */\n async #invalidate(session: SourceControlSession): Promise<void> {\n try {\n await this.#invalidateSession(session.sessionId);\n } catch (error) {\n this.#warn('Factory session workspace cache invalidation failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n }\n }\n\n async #recreateSessionSandbox(input: RecreateSessionSandboxInput): Promise<'recreated' | 'not-found'> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return 'not-found';\n\n // Bump the generation first so an in-flight start hook for the old\n // instance throws instead of republishing its sandbox id.\n await this.#invalidate(session);\n const entry = peekSessionSandbox(session.id);\n evictSessionSandbox(session.id);\n\n await this.#destroyForRecreate(session, entry?.sandbox);\n await input.sourceControl.sessions.setSandbox({ id: session.id, sandboxId: null, sandboxWorkdir: '' });\n\n // A resolve that ran between the eviction and clearing the id could have\n // built a fresh instance from the old `sandboxId`; drop it and fence it.\n evictSessionSandbox(session.id);\n await this.#invalidate(session);\n return 'recreated';\n }\n\n /**\n * Destroy the session's VM. `_destroy()` silently no-ops on a never-started\n * (`pending`) instance, so pending and detached instances call the\n * provider's `destroy()` directly; a started instance goes through the\n * lifecycle wrapper, bounded so a hung start can't hold the session lock.\n */\n async #destroyForRecreate(session: SourceControlSession, memo: WorkspaceSandbox | undefined): Promise<void> {\n const lifecycle = memo as { _destroy?: () => Promise<void> } | undefined;\n if (memo && memo.status !== 'pending' && lifecycle?._destroy) {\n const destroying = lifecycle._destroy.call(memo);\n if (await this.#settledWithin(destroying)) {\n memo.status = 'destroyed';\n return;\n }\n // Load-bearing: once the hung start settles, this destroy reaps any VM it\n // provisioned. Its rejection must never surface as unhandled.\n destroying.catch(error =>\n this.#warn('Factory sandbox destroy failed after recreate stopped waiting', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n error: boundedError(error),\n }),\n );\n if (!this.#sandbox) {\n throw new Error(\n 'Timed out destroying the session sandbox, and no sandbox provider is configured to retry by identity.',\n );\n }\n await this.#destroyDetachedForRecreate(this.#sandbox, session);\n memo.status = 'destroyed';\n return;\n }\n\n if (memo) {\n await this.#destroyDirectly(memo);\n memo.status = 'destroyed';\n return;\n }\n\n // No instance in this process (restart, or another replica opened it):\n // destroy through a never-started instance carrying the persisted id.\n // Unlike retirement, this runs without a `sandboxId` too: E2B and Docker\n // find the VM by session identity, and Platform's destroy no-ops safely.\n if (this.#sandbox) await this.#destroyDetachedForRecreate(this.#sandbox, session);\n }\n\n async #destroyDetachedForRecreate(sandbox: FactorySandbox, session: SourceControlSession): Promise<void> {\n try {\n await destroyDetachedSessionSandbox({ sandbox, session });\n } catch (error) {\n if (!isSandboxGoneError(error)) throw error;\n }\n }\n\n /** True when the destroy finished in time; false on timeout. Gone-VM errors count as finished. */\n async #settledWithin(destroying: Promise<void>): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<false>(resolve => {\n timer = setTimeout(() => resolve(false), this.#destroyTimeoutMs);\n });\n try {\n return await Promise.race([destroying.then(() => true as const), timedOut]);\n } catch (error) {\n if (isSandboxGoneError(error)) return true;\n throw error;\n } finally {\n clearTimeout(timer);\n }\n }\n\n async #destroyDirectly(sandbox: WorkspaceSandbox): Promise<void> {\n try {\n await sandbox.destroy?.();\n } catch (error) {\n if (!isSandboxGoneError(error)) throw error;\n }\n }\n\n async #releaseSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<void> {\n try {\n await releaseSessionSandbox({ sessionId: session.id, destroy: input.deleteSession });\n } catch (error) {\n this.#warn('Factory session sandbox release failed', {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });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@ -1 +1 @@
1
- {"version":3,"file":"secret-encryption.d.ts","sourceRoot":"","sources":["../src/secret-encryption.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,sBAAsB,CAAC,CAAC;IACvC,KAAK,EAAE,CAAC,CAAC;IACT,iBAAiB,EAAE,OAAO,CAAC;CAC5B;AAED,kFAAkF;AAClF,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAAC,CAAC,CAAC,CAAC;CAChE;AAED,MAAM,WAAW,0BAA0B;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,UAAU,CAAC;CACjB;AAED,MAAM,WAAW,6BAA6B;IAC5C,OAAO,EAAE,0BAA0B,CAAC;IACpC,QAAQ,CAAC,EAAE,0BAA0B,EAAE,CAAC;CACzC;AAgCD;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,MAAM,EAAE,6BAA6B,GAAG,uBAAuB,CAyD5G;AAED,+EAA+E;AAC/E,wBAAgB,sCAAsC,IAAI,uBAAuB,CAiBhF"}
1
+ {"version":3,"file":"secret-encryption.d.ts","sourceRoot":"","sources":["../src/secret-encryption.ts"],"names":[],"mappings":"AAcA,MAAM,WAAW,sBAAsB,CAAC,CAAC;IACvC,KAAK,EAAE,CAAC,CAAC;IACT,iBAAiB,EAAE,OAAO,CAAC;CAC5B;AAED,kFAAkF;AAClF,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACtC,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAAC,CAAC,CAAC,CAAC;CAChE;AAED,MAAM,WAAW,0BAA0B;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,UAAU,CAAC;CACjB;AAED,MAAM,WAAW,6BAA6B;IAC5C,OAAO,EAAE,0BAA0B,CAAC;IACpC,QAAQ,CAAC,EAAE,0BAA0B,EAAE,CAAC;CACzC;AAgCD;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,MAAM,EAAE,6BAA6B,GAAG,uBAAuB,CA+E5G;AAED,+EAA+E;AAC/E,wBAAgB,sCAAsC,IAAI,uBAAuB,CA+BhF"}
@@ -3,6 +3,7 @@ import { createCipheriv, createDecipheriv } from "crypto";
3
3
  const ENVELOPE_PREFIX = "mastra:factory-secret:v1:";
4
4
  const ALGORITHM = "aes-256-gcm";
5
5
  const IV_BYTES = 12;
6
+ const MAX_NESTED_ENVELOPES = 4;
6
7
  function validateKey({ id, key }) {
7
8
  if (!id) throw new Error("[FactorySecretEncryption] Key id is required.");
8
9
  const buffer = Buffer.from(key);
@@ -43,38 +44,66 @@ function createFactorySecretEncryption(config) {
43
44
  };
44
45
  return `${ENVELOPE_PREFIX}${Buffer.from(JSON.stringify(envelope), "utf8").toString("base64url")}`;
45
46
  },
46
- async decrypt(value) {
47
- if (typeof value !== "string") return {
48
- value: structuredClone(value),
49
- needsReencryption: true
50
- };
51
- if (!value.startsWith(ENVELOPE_PREFIX)) try {
52
- return {
53
- value: JSON.parse(value),
54
- needsReencryption: true
55
- };
47
+ decrypt
48
+ };
49
+ async function decrypt(value, depth = 0) {
50
+ if (typeof value !== "string") return {
51
+ value: structuredClone(value),
52
+ needsReencryption: true
53
+ };
54
+ if (!value.startsWith(ENVELOPE_PREFIX)) {
55
+ let parsed;
56
+ try {
57
+ parsed = JSON.parse(value);
56
58
  } catch {
57
59
  return {
58
60
  value,
59
61
  needsReencryption: true
60
62
  };
61
63
  }
62
- const envelope = parseEnvelope(value);
63
- const key = keys.get(envelope.keyId);
64
- if (!key) throw new Error(`[FactorySecretEncryption] Unknown key id "${envelope.keyId}".`);
65
- try {
66
- const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, "base64url"));
67
- decipher.setAuthTag(Buffer.from(envelope.tag, "base64url"));
68
- const plaintext = Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, "base64url")), decipher.final()]).toString("utf8");
69
- return {
70
- value: JSON.parse(plaintext),
71
- needsReencryption: envelope.keyId !== config.primary.id
72
- };
73
- } catch {
74
- throw new Error("[FactorySecretEncryption] Unable to decrypt encrypted value.");
75
- }
64
+ return {
65
+ value: await unwrapNestedEnvelope(parsed, depth) ?? parsed,
66
+ needsReencryption: true
67
+ };
76
68
  }
77
- };
69
+ const envelope = parseEnvelope(value);
70
+ const key = keys.get(envelope.keyId);
71
+ if (!key) throw new Error(`[FactorySecretEncryption] Unknown key id "${envelope.keyId}".`);
72
+ let decoded;
73
+ try {
74
+ const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, "base64url"));
75
+ decipher.setAuthTag(Buffer.from(envelope.tag, "base64url"));
76
+ const plaintext = Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, "base64url")), decipher.final()]).toString("utf8");
77
+ decoded = JSON.parse(plaintext);
78
+ } catch {
79
+ throw new Error("[FactorySecretEncryption] Unable to decrypt encrypted value.");
80
+ }
81
+ const nested = await unwrapNestedEnvelope(decoded, depth);
82
+ if (nested !== void 0) return {
83
+ value: nested,
84
+ needsReencryption: true
85
+ };
86
+ return {
87
+ value: decoded,
88
+ needsReencryption: envelope.keyId !== config.primary.id
89
+ };
90
+ }
91
+ /**
92
+ * Older plaintext encryptors treated an envelope as a raw legacy secret and
93
+ * rewrote it as JSON text, which a keyed boot then re-encrypted. Peel those
94
+ * layers back to the real value so the row is repaired on the next write.
95
+ * A user-supplied secret can also look like an envelope, so anything that
96
+ * does not decrypt with our keys is kept as the literal value.
97
+ */
98
+ async function unwrapNestedEnvelope(value, depth) {
99
+ if (typeof value !== "string" || !value.startsWith(ENVELOPE_PREFIX)) return void 0;
100
+ if (depth >= MAX_NESTED_ENVELOPES) return void 0;
101
+ try {
102
+ return (await decrypt(value, depth + 1)).value;
103
+ } catch {
104
+ return;
105
+ }
106
+ }
78
107
  }
79
108
  /** Explicit plaintext compatibility for local, no-auth Factory development. */
80
109
  function createPlaintextFactorySecretEncryption() {
@@ -87,6 +116,17 @@ function createPlaintextFactorySecretEncryption() {
87
116
  value: structuredClone(value),
88
117
  needsReencryption: false
89
118
  };
119
+ if (value.startsWith(ENVELOPE_PREFIX)) {
120
+ try {
121
+ parseEnvelope(value);
122
+ } catch {
123
+ return {
124
+ value,
125
+ needsReencryption: true
126
+ };
127
+ }
128
+ throw new Error("[FactorySecretEncryption] Value is encrypted, but this instance has no secret encryption key configured. Configure 'secretEncryption' with the same key on every Factory instance.");
129
+ }
90
130
  try {
91
131
  return {
92
132
  value: JSON.parse(value),
@@ -1 +1 @@
1
- {"version":3,"file":"secret-encryption.js","names":[],"sources":["../src/secret-encryption.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv } from 'node:crypto';\n\nconst ENVELOPE_PREFIX = 'mastra:factory-secret:v1:';\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_BYTES = 12;\n\ninterface SecretEnvelopeV1 {\n keyId: string;\n iv: string;\n ciphertext: string;\n tag: string;\n}\n\nexport interface DecryptedFactorySecret<T> {\n value: T;\n needsReencryption: boolean;\n}\n\n/** Encrypts opaque JSON values before they cross the Factory storage boundary. */\nexport interface FactorySecretEncryption {\n encrypt<T>(value: T): Promise<string>;\n decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>>;\n}\n\nexport interface FactorySecretEncryptionKey {\n id: string;\n key: Uint8Array;\n}\n\nexport interface FactorySecretEncryptionConfig {\n primary: FactorySecretEncryptionKey;\n previous?: FactorySecretEncryptionKey[];\n}\n\nfunction validateKey({ id, key }: FactorySecretEncryptionKey): Buffer {\n if (!id) throw new Error('[FactorySecretEncryption] Key id is required.');\n const buffer = Buffer.from(key);\n if (buffer.byteLength !== 32) {\n throw new Error(`[FactorySecretEncryption] Key \"${id}\" must be exactly 32 bytes.`);\n }\n return buffer;\n}\n\nfunction parseEnvelope(value: string): SecretEnvelopeV1 {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(value.slice(ENVELOPE_PREFIX.length), 'base64url').toString('utf8'));\n } catch {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n\n if (\n !parsed ||\n typeof parsed !== 'object' ||\n typeof (parsed as SecretEnvelopeV1).keyId !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).iv !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).ciphertext !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).tag !== 'string'\n ) {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n return parsed as SecretEnvelopeV1;\n}\n\n/**\n * Creates a versioned AES-256-GCM encryptor. The primary key is used for new\n * writes; previous keys remain decrypt-only until stored values are rotated.\n */\nexport function createFactorySecretEncryption(config: FactorySecretEncryptionConfig): FactorySecretEncryption {\n const primaryKey = validateKey(config.primary);\n const keys = new Map<string, Buffer>([[config.primary.id, primaryKey]]);\n for (const previous of config.previous ?? []) {\n if (keys.has(previous.id)) throw new Error(`[FactorySecretEncryption] Duplicate key id \"${previous.id}\".`);\n keys.set(previous.id, validateKey(previous));\n }\n\n return {\n async encrypt<T>(value: T): Promise<string> {\n const iv = Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(IV_BYTES)));\n const cipher = createCipheriv(ALGORITHM, primaryKey, iv);\n const ciphertext = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()]);\n const envelope: SecretEnvelopeV1 = {\n keyId: config.primary.id,\n iv: iv.toString('base64url'),\n ciphertext: ciphertext.toString('base64url'),\n tag: cipher.getAuthTag().toString('base64url'),\n };\n return `${ENVELOPE_PREFIX}${Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64url')}`;\n },\n\n async decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') {\n return { value: structuredClone(value) as T, needsReencryption: true };\n }\n if (!value.startsWith(ENVELOPE_PREFIX)) {\n // JSON text written by the plaintext encryptor, or a raw pre-encryption\n // secret string. Decode it the same way the plaintext encryptor does so\n // migration encrypts the original value, not its JSON text.\n try {\n return { value: JSON.parse(value) as T, needsReencryption: true };\n } catch {\n return { value: value as T, needsReencryption: true };\n }\n }\n\n const envelope = parseEnvelope(value);\n const key = keys.get(envelope.keyId);\n if (!key) throw new Error(`[FactorySecretEncryption] Unknown key id \"${envelope.keyId}\".`);\n\n try {\n const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, 'base64url'));\n decipher.setAuthTag(Buffer.from(envelope.tag, 'base64url'));\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(envelope.ciphertext, 'base64url')),\n decipher.final(),\n ]).toString('utf8');\n return {\n value: JSON.parse(plaintext) as T,\n needsReencryption: envelope.keyId !== config.primary.id,\n };\n } catch {\n throw new Error('[FactorySecretEncryption] Unable to decrypt encrypted value.');\n }\n },\n };\n}\n\n/** Explicit plaintext compatibility for local, no-auth Factory development. */\nexport function createPlaintextFactorySecretEncryption(): FactorySecretEncryption {\n return {\n async encrypt<T>(value: T): Promise<string> {\n return JSON.stringify(value);\n },\n async decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') return { value: structuredClone(value) as T, needsReencryption: false };\n try {\n return { value: JSON.parse(value) as T, needsReencryption: false };\n } catch {\n // Pre-encryption rows stored raw secret strings (e.g. a bare\n // `custom_providers.api_key`), not JSON. Treat the raw string as the\n // value and flag it so migration rewrites it in the current format.\n return { value: value as T, needsReencryption: true };\n }\n },\n };\n}\n"],"mappings":";;AAEA,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,WAAW;AA8BjB,SAAS,YAAY,EAAE,IAAI,OAA2C;CACpE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C;CACxE,MAAM,SAAS,OAAO,KAA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AK,MAAM,KAAK;KAAQ,mBAAmB;IAAM;GACnE,QAAQ;IAIN,OAAO;KAAS;KAAY,mBAAmB;IAAK;GACtD;EACF;CACF;AACF"}
1
+ {"version":3,"file":"secret-encryption.js","names":[],"sources":["../src/secret-encryption.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv } from 'node:crypto';\n\nconst ENVELOPE_PREFIX = 'mastra:factory-secret:v1:';\nconst ALGORITHM = 'aes-256-gcm';\nconst IV_BYTES = 12;\nconst MAX_NESTED_ENVELOPES = 4;\n\ninterface SecretEnvelopeV1 {\n keyId: string;\n iv: string;\n ciphertext: string;\n tag: string;\n}\n\nexport interface DecryptedFactorySecret<T> {\n value: T;\n needsReencryption: boolean;\n}\n\n/** Encrypts opaque JSON values before they cross the Factory storage boundary. */\nexport interface FactorySecretEncryption {\n encrypt<T>(value: T): Promise<string>;\n decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>>;\n}\n\nexport interface FactorySecretEncryptionKey {\n id: string;\n key: Uint8Array;\n}\n\nexport interface FactorySecretEncryptionConfig {\n primary: FactorySecretEncryptionKey;\n previous?: FactorySecretEncryptionKey[];\n}\n\nfunction validateKey({ id, key }: FactorySecretEncryptionKey): Buffer {\n if (!id) throw new Error('[FactorySecretEncryption] Key id is required.');\n const buffer = Buffer.from(key);\n if (buffer.byteLength !== 32) {\n throw new Error(`[FactorySecretEncryption] Key \"${id}\" must be exactly 32 bytes.`);\n }\n return buffer;\n}\n\nfunction parseEnvelope(value: string): SecretEnvelopeV1 {\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(value.slice(ENVELOPE_PREFIX.length), 'base64url').toString('utf8'));\n } catch {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n\n if (\n !parsed ||\n typeof parsed !== 'object' ||\n typeof (parsed as SecretEnvelopeV1).keyId !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).iv !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).ciphertext !== 'string' ||\n typeof (parsed as SecretEnvelopeV1).tag !== 'string'\n ) {\n throw new Error('[FactorySecretEncryption] Invalid encrypted value.');\n }\n return parsed as SecretEnvelopeV1;\n}\n\n/**\n * Creates a versioned AES-256-GCM encryptor. The primary key is used for new\n * writes; previous keys remain decrypt-only until stored values are rotated.\n */\nexport function createFactorySecretEncryption(config: FactorySecretEncryptionConfig): FactorySecretEncryption {\n const primaryKey = validateKey(config.primary);\n const keys = new Map<string, Buffer>([[config.primary.id, primaryKey]]);\n for (const previous of config.previous ?? []) {\n if (keys.has(previous.id)) throw new Error(`[FactorySecretEncryption] Duplicate key id \"${previous.id}\".`);\n keys.set(previous.id, validateKey(previous));\n }\n\n return {\n async encrypt<T>(value: T): Promise<string> {\n const iv = Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(IV_BYTES)));\n const cipher = createCipheriv(ALGORITHM, primaryKey, iv);\n const ciphertext = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()]);\n const envelope: SecretEnvelopeV1 = {\n keyId: config.primary.id,\n iv: iv.toString('base64url'),\n ciphertext: ciphertext.toString('base64url'),\n tag: cipher.getAuthTag().toString('base64url'),\n };\n return `${ENVELOPE_PREFIX}${Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64url')}`;\n },\n\n decrypt,\n };\n\n async function decrypt<T>(value: unknown, depth = 0): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') {\n return { value: structuredClone(value) as T, needsReencryption: true };\n }\n if (!value.startsWith(ENVELOPE_PREFIX)) {\n // JSON text written by the plaintext encryptor, or a raw pre-encryption\n // secret string. Decode it the same way the plaintext encryptor does so\n // migration encrypts the original value, not its JSON text.\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return { value: value as T, needsReencryption: true };\n }\n return { value: (await unwrapNestedEnvelope<T>(parsed, depth)) ?? (parsed as T), needsReencryption: true };\n }\n\n const envelope = parseEnvelope(value);\n const key = keys.get(envelope.keyId);\n if (!key) throw new Error(`[FactorySecretEncryption] Unknown key id \"${envelope.keyId}\".`);\n\n let decoded: unknown;\n try {\n const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(envelope.iv, 'base64url'));\n decipher.setAuthTag(Buffer.from(envelope.tag, 'base64url'));\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(envelope.ciphertext, 'base64url')),\n decipher.final(),\n ]).toString('utf8');\n decoded = JSON.parse(plaintext);\n } catch {\n throw new Error('[FactorySecretEncryption] Unable to decrypt encrypted value.');\n }\n const nested = await unwrapNestedEnvelope<T>(decoded, depth);\n if (nested !== undefined) return { value: nested, needsReencryption: true };\n return { value: decoded as T, needsReencryption: envelope.keyId !== config.primary.id };\n }\n\n /**\n * Older plaintext encryptors treated an envelope as a raw legacy secret and\n * rewrote it as JSON text, which a keyed boot then re-encrypted. Peel those\n * layers back to the real value so the row is repaired on the next write.\n * A user-supplied secret can also look like an envelope, so anything that\n * does not decrypt with our keys is kept as the literal value.\n */\n async function unwrapNestedEnvelope<T>(value: unknown, depth: number): Promise<T | undefined> {\n if (typeof value !== 'string' || !value.startsWith(ENVELOPE_PREFIX)) return undefined;\n if (depth >= MAX_NESTED_ENVELOPES) return undefined;\n try {\n return (await decrypt<T>(value, depth + 1)).value;\n } catch {\n return undefined;\n }\n }\n}\n\n/** Explicit plaintext compatibility for local, no-auth Factory development. */\nexport function createPlaintextFactorySecretEncryption(): FactorySecretEncryption {\n return {\n async encrypt<T>(value: T): Promise<string> {\n return JSON.stringify(value);\n },\n async decrypt<T>(value: unknown): Promise<DecryptedFactorySecret<T>> {\n if (typeof value !== 'string') return { value: structuredClone(value) as T, needsReencryption: false };\n if (value.startsWith(ENVELOPE_PREFIX)) {\n // Never hand an envelope back as the secret, and never let migration\n // rewrite it as plaintext JSON: that corrupts the row for keyed instances.\n // A raw legacy secret can merely start with the prefix; keep those as-is.\n try {\n parseEnvelope(value);\n } catch {\n return { value: value as T, needsReencryption: true };\n }\n throw new Error(\n '[FactorySecretEncryption] Value is encrypted, but this instance has no secret encryption key configured. ' +\n \"Configure 'secretEncryption' with the same key on every Factory instance.\",\n );\n }\n try {\n return { value: JSON.parse(value) as T, needsReencryption: false };\n } catch {\n // Pre-encryption rows stored raw secret strings (e.g. a bare\n // `custom_providers.api_key`), not JSON. Treat the raw string as the\n // value and flag it so migration rewrites it in the current format.\n return { value: value as T, needsReencryption: true };\n }\n },\n };\n}\n"],"mappings":";;AAEA,MAAM,kBAAkB;AACxB,MAAM,YAAY;AAClB,MAAM,WAAW;AACjB,MAAM,uBAAuB;AA8B7B,SAAS,YAAY,EAAE,IAAI,OAA2C;CACpE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C;CACxE,MAAM,SAAS,OAAO,KAAK,GAAG;CAC9B,IAAI,OAAO,eAAe,IACxB,MAAM,IAAI,MAAM,kCAAkC,GAAG,4BAA4B;CAEnF,OAAO;AACT;AAEA,SAAS,cAAc,OAAiC;CACtD,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,OAAO,KAAK,MAAM,MAAM,EAAsB,GAAG,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;CACpG,QAAQ;EACN,MAAM,IAAI,MAAM,oDAAoD;CACtE;CAEA,IACE,CAAC,UACD,OAAO,WAAW,YAClB,OAAQ,OAA4B,UAAU,YAC9C,OAAQ,OAA4B,OAAO,YAC3C,OAAQ,OAA4B,eAAe,YACnD,OAAQ,OAA4B,QAAQ,UAE5C,MAAM,IAAI,MAAM,oDAAoD;CAEtE,OAAO;AACT;;;;;AAMA,SAAgB,8BAA8B,QAAgE;CAC5G,MAAM,aAAa,YAAY,OAAO,OAAO;CAC7C,MAAM,uBAAO,IAAI,IAAoB,CAAC,CAAC,OAAO,QAAQ,IAAI,UAAU,CAAC,CAAC;CACtE,KAAK,MAAM,YAAY,OAAO,YAAY,CAAC,GAAG;EAC5C,IAAI,KAAK,IAAI,SAAS,EAAE,GAAG,MAAM,IAAI,MAAM,+CAA+C,SAAS,GAAG,GAAG;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oryChannelReplyProcessor implements Processor {
20
20
  }
21
21
  export interface SessionLinkTarget {
22
22
  threadId: string;
23
+ sessionId: string;
23
24
  resourceId: string;
24
25
  factoryProjectId?: string;
25
26
  }
26
27
  /**
27
28
  * The web URL for a session, or undefined without a public origin. Same
28
- * routes the Factory UI navigates to: a repo-backed thread's resourceId is the
29
- * Factory user-session id and doubles as the workspace segment; chat-only
30
- * threads keep the literal `channel` segment and name their resource in the
31
- * query; a session with no factory falls back to the factory-agnostic
32
- * /threads/ redirect, which forwards the query through.
29
+ * routes the Factory UI navigates to: a repo-backed thread's Factory session
30
+ * id is the workspace segment; chat-only threads keep the literal `channel`
31
+ * segment and name their session in the query; a session with no factory
32
+ * falls back to the factory-agnostic /threads/ redirect, which forwards the
33
+ * query through.
33
34
  */
34
- export declare function sessionLink({ threadId, resourceId, factoryProjectId }: SessionLinkTarget): string | undefined;
35
+ export declare function sessionLink({ threadId, sessionId, resourceId, factoryProjectId, }: SessionLinkTarget): string | undefined;
35
36
  //# sourceMappingURL=channel-reply-processor.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"channel-reply-processor.d.ts","sourceRoot":"","sources":["../../src/session/channel-reply-processor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAI/E,eAAO,MAAM,kBAAkB,wBAAmB,CAAC;AAEnD;;;;;;;;;;;GAWG;AACH,qBAAa,4BAA6B,YAAW,SAAS;IAC5D,QAAQ,CAAC,EAAE,2BAAM;IAEjB,gBAAgB,CAAC,EAAE,WAAW,EAAE,cAAc,EAAE,EAAE,oBAAoB;;;CAcvE;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,gBAAgB,EAAE,EAAE,iBAAiB,GAAG,MAAM,GAAG,SAAS,CAQ7G"}
1
+ {"version":3,"file":"channel-reply-processor.d.ts","sourceRoot":"","sources":["../../src/session/channel-reply-processor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAI/E,eAAO,MAAM,kBAAkB,wBAAmB,CAAC;AAEnD;;;;;;;;;;;GAWG;AACH,qBAAa,4BAA6B,YAAW,SAAS;IAC5D,QAAQ,CAAC,EAAE,2BAAM;IAEjB,gBAAgB,CAAC,EAAE,WAAW,EAAE,cAAc,EAAE,EAAE,oBAAoB;;;CAcvE;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,EAC1B,QAAQ,EACR,SAAS,EACT,UAAU,EACV,gBAAgB,GACjB,EAAE,iBAAiB,GAAG,MAAM,GAAG,SAAS,CAQxC"}
@@ -26,19 +26,19 @@ var FactoryChannelReplyProcessor = class {
26
26
  };
27
27
  /**
28
28
  * The web URL for a session, or undefined without a public origin. Same
29
- * routes the Factory UI navigates to: a repo-backed thread's resourceId is the
30
- * Factory user-session id and doubles as the workspace segment; chat-only
31
- * threads keep the literal `channel` segment and name their resource in the
32
- * query; a session with no factory falls back to the factory-agnostic
33
- * /threads/ redirect, which forwards the query through.
29
+ * routes the Factory UI navigates to: a repo-backed thread's Factory session
30
+ * id is the workspace segment; chat-only threads keep the literal `channel`
31
+ * segment and name their session in the query; a session with no factory
32
+ * falls back to the factory-agnostic /threads/ redirect, which forwards the
33
+ * query through.
34
34
  */
35
- function sessionLink({ threadId, resourceId, factoryProjectId }) {
35
+ function sessionLink({ threadId, sessionId, resourceId, factoryProjectId }) {
36
36
  const origin = process.env.MASTRACODE_PUBLIC_URL;
37
37
  if (!origin) return void 0;
38
38
  const isChatOnly = resourceId.startsWith("channel:");
39
- const resourceParam = `?resourceId=${encodeURIComponent(resourceId)}`;
40
- if (!factoryProjectId) return `${origin}/threads/${encodeURIComponent(threadId)}${resourceParam}`;
41
- return `${origin}/factories/${encodeURIComponent(factoryProjectId)}/workspaces/${isChatOnly ? "channel" : encodeURIComponent(resourceId)}/threads/${encodeURIComponent(threadId)}${isChatOnly ? resourceParam : ""}`;
39
+ const sessionParam = `?sessionId=${encodeURIComponent(sessionId)}`;
40
+ if (!factoryProjectId) return `${origin}/threads/${encodeURIComponent(threadId)}${sessionParam}`;
41
+ return `${origin}/factories/${encodeURIComponent(factoryProjectId)}/workspaces/${isChatOnly ? "channel" : encodeURIComponent(sessionId)}/threads/${encodeURIComponent(threadId)}${isChatOnly ? sessionParam : ""}`;
42
42
  }
43
43
  //#endregion
44
44
  export { FactoryChannelReplyProcessor, SESSION_LINK_LABEL, sessionLink };
@@ -1 +1 @@
1
- {"version":3,"file":"channel-reply-processor.js","names":[],"sources":["../../src/session/channel-reply-processor.ts"],"sourcesContent":["import type { ProcessInputStepArgs, Processor } from '@mastra/core/processors';\n\nconst ID = 'factory-channel-reply';\n\nexport const SESSION_LINK_LABEL = 'Open session ↗';\n\n/**\n * Tells the agent how to open a reply when the run came in over a chat\n * channel (Slack, …): acknowledge a job in one line that names it — \"On it —\n * sleeping 30s, then running the echo\" — before starting, so the sender sees\n * a task-specific first message rather than a silent typing status until the\n * first tool finishes. The channel driver posts that opener on its own before\n * the tool widget, so the instruction and the rendering agree. The session\n * link is not the model's job: `FactoryChannelSessionLinkProcessor` appends it\n * to the first reply of a new session, so it is there whether or not the\n * model judged the request worth an opener. No-op for runs without channel\n * context (Studio, API, boards).\n */\nexport class FactoryChannelReplyProcessor implements Processor {\n readonly id = ID;\n\n processInputStep({ messageList, requestContext }: ProcessInputStepArgs) {\n if (!requestContext?.get('channel')) return undefined;\n messageList.addSystem(\n {\n role: 'system',\n content: [\n 'When a request will take tools or more than a moment to answer, reply first with one short line that says what you are about to do — \"On it — <the task in a few words>.\" — then do the work; the opener posts as its own message before any progress is shown. Give direct answers and trivial replies without an opener.',\n 'Finish with the outcome, not a replay of the steps.',\n ].join('\\n'),\n },\n ID,\n );\n return { messageList };\n }\n}\n\nexport interface SessionLinkTarget {\n threadId: string;\n resourceId: string;\n factoryProjectId?: string;\n}\n\n/**\n * The web URL for a session, or undefined without a public origin. Same\n * routes the Factory UI navigates to: a repo-backed thread's resourceId is the\n * Factory user-session id and doubles as the workspace segment; chat-only\n * threads keep the literal `channel` segment and name their resource in the\n * query; a session with no factory falls back to the factory-agnostic\n * /threads/ redirect, which forwards the query through.\n */\nexport function sessionLink({ threadId, resourceId, factoryProjectId }: SessionLinkTarget): string | undefined {\n const origin = process.env.MASTRACODE_PUBLIC_URL;\n if (!origin) return undefined;\n const isChatOnly = resourceId.startsWith('channel:');\n const resourceParam = `?resourceId=${encodeURIComponent(resourceId)}`;\n if (!factoryProjectId) return `${origin}/threads/${encodeURIComponent(threadId)}${resourceParam}`;\n const workspaceSegment = isChatOnly ? 'channel' : encodeURIComponent(resourceId);\n return `${origin}/factories/${encodeURIComponent(factoryProjectId)}/workspaces/${workspaceSegment}/threads/${encodeURIComponent(threadId)}${isChatOnly ? resourceParam : ''}`;\n}\n"],"mappings":";AAEA,MAAM,KAAK;AAEX,MAAa,qBAAqB;;;;;;;;;;;;;AAclC,IAAa,+BAAb,MAA+D;CAC7D,KAAc;CAEd,iBAAiB,EAAE,aAAa,kBAAwC;EACtE,IAAI,CAAC,gBAAgB,IAAI,SAAS,GAAG,OAAO,KAAA;EAC5C,YAAY,UACV;GACE,MAAM;GACN,SAAS,CACP,gUACA,qDACF,CAAC,CAAC,KAAK,IAAI;EACb,GACA,EACF;EACA,OAAO,EAAE,YAAY;CACvB;AACF;;;;;;;;;AAgBA,SAAgB,YAAY,EAAE,UAAU,YAAY,oBAA2D;CAC7G,MAAM,SAAS,QAAQ,IAAI;CAC3B,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,MAAM,aAAa,WAAW,WAAW,UAAU;CACnD,MAAM,gBAAgB,eAAe,mBAAmB,UAAU;CAClE,IAAI,CAAC,kBAAkB,OAAO,GAAG,OAAO,WAAW,mBAAmB,QAAQ,IAAI;CAElF,OAAO,GAAG,OAAO,aAAa,mBAAmB,gBAAgB,EAAE,cAD1C,aAAa,YAAY,mBAAmB,UAAU,EACmB,WAAW,mBAAmB,QAAQ,IAAI,aAAa,gBAAgB;AAC3K"}
1
+ {"version":3,"file":"channel-reply-processor.js","names":[],"sources":["../../src/session/channel-reply-processor.ts"],"sourcesContent":["import type { ProcessInputStepArgs, Processor } from '@mastra/core/processors';\n\nconst ID = 'factory-channel-reply';\n\nexport const SESSION_LINK_LABEL = 'Open session ↗';\n\n/**\n * Tells the agent how to open a reply when the run came in over a chat\n * channel (Slack, …): acknowledge a job in one line that names it — \"On it —\n * sleeping 30s, then running the echo\" — before starting, so the sender sees\n * a task-specific first message rather than a silent typing status until the\n * first tool finishes. The channel driver posts that opener on its own before\n * the tool widget, so the instruction and the rendering agree. The session\n * link is not the model's job: `FactoryChannelSessionLinkProcessor` appends it\n * to the first reply of a new session, so it is there whether or not the\n * model judged the request worth an opener. No-op for runs without channel\n * context (Studio, API, boards).\n */\nexport class FactoryChannelReplyProcessor implements Processor {\n readonly id = ID;\n\n processInputStep({ messageList, requestContext }: ProcessInputStepArgs) {\n if (!requestContext?.get('channel')) return undefined;\n messageList.addSystem(\n {\n role: 'system',\n content: [\n 'When a request will take tools or more than a moment to answer, reply first with one short line that says what you are about to do — \"On it — <the task in a few words>.\" — then do the work; the opener posts as its own message before any progress is shown. Give direct answers and trivial replies without an opener.',\n 'Finish with the outcome, not a replay of the steps.',\n ].join('\\n'),\n },\n ID,\n );\n return { messageList };\n }\n}\n\nexport interface SessionLinkTarget {\n threadId: string;\n sessionId: string;\n resourceId: string;\n factoryProjectId?: string;\n}\n\n/**\n * The web URL for a session, or undefined without a public origin. Same\n * routes the Factory UI navigates to: a repo-backed thread's Factory session\n * id is the workspace segment; chat-only threads keep the literal `channel`\n * segment and name their session in the query; a session with no factory\n * falls back to the factory-agnostic /threads/ redirect, which forwards the\n * query through.\n */\nexport function sessionLink({\n threadId,\n sessionId,\n resourceId,\n factoryProjectId,\n}: SessionLinkTarget): string | undefined {\n const origin = process.env.MASTRACODE_PUBLIC_URL;\n if (!origin) return undefined;\n const isChatOnly = resourceId.startsWith('channel:');\n const sessionParam = `?sessionId=${encodeURIComponent(sessionId)}`;\n if (!factoryProjectId) return `${origin}/threads/${encodeURIComponent(threadId)}${sessionParam}`;\n const workspaceSegment = isChatOnly ? 'channel' : encodeURIComponent(sessionId);\n return `${origin}/factories/${encodeURIComponent(factoryProjectId)}/workspaces/${workspaceSegment}/threads/${encodeURIComponent(threadId)}${isChatOnly ? sessionParam : ''}`;\n}\n"],"mappings":";AAEA,MAAM,KAAK;AAEX,MAAa,qBAAqB;;;;;;;;;;;;;AAclC,IAAa,+BAAb,MAA+D;CAC7D,KAAc;CAEd,iBAAiB,EAAE,aAAa,kBAAwC;EACtE,IAAI,CAAC,gBAAgB,IAAI,SAAS,GAAG,OAAO,KAAA;EAC5C,YAAY,UACV;GACE,MAAM;GACN,SAAS,CACP,gUACA,qDACF,CAAC,CAAC,KAAK,IAAI;EACb,GACA,EACF;EACA,OAAO,EAAE,YAAY;CACvB;AACF;;;;;;;;;AAiBA,SAAgB,YAAY,EAC1B,UACA,WACA,YACA,oBACwC;CACxC,MAAM,SAAS,QAAQ,IAAI;CAC3B,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,MAAM,aAAa,WAAW,WAAW,UAAU;CACnD,MAAM,eAAe,cAAc,mBAAmB,SAAS;CAC/D,IAAI,CAAC,kBAAkB,OAAO,GAAG,OAAO,WAAW,mBAAmB,QAAQ,IAAI;CAElF,OAAO,GAAG,OAAO,aAAa,mBAAmB,gBAAgB,EAAE,cAD1C,aAAa,YAAY,mBAAmB,SAAS,EACoB,WAAW,mBAAmB,QAAQ,IAAI,aAAa,eAAe;AAC1K"}
@@ -89,6 +89,7 @@ function sessionLinkFromRequest(requestContext) {
89
89
  if (!controller?.threadId) return void 0;
90
90
  return sessionLink({
91
91
  threadId: controller.threadId,
92
+ sessionId: controller.sessionId,
92
93
  resourceId: controller.resourceId,
93
94
  factoryProjectId: readFactorySessionScope(requestContext)?.factoryProjectId
94
95
  });
@@ -1 +1 @@
1
- {"version":3,"file":"channel-session-link-processor.js","names":[],"sources":["../../src/session/channel-session-link-processor.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Processor, ProcessOutputStepArgs, ProcessOutputStreamArgs } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ChunkType } from '@mastra/core/stream';\n\nimport { readFactorySessionScope } from '../rules/binding-context.js';\nimport { SESSION_LINK_LABEL, sessionLink } from './channel-reply-processor.js';\n\n/**\n * Request-context marker a channel handler sets on the run that opens a new\n * thread. Only that run gets the link; follow-ups in the same thread don't.\n */\nexport const NEW_CHANNEL_SESSION_KEY = 'factory__newChannelSession';\n\nexport function markNewChannelSession(requestContext: RequestContext): void {\n requestContext.set(NEW_CHANNEL_SESSION_KEY, true);\n}\n\n/**\n * State key the core ProcessorRunner reads to re-drive one extra part through\n * the output chain after the part a processor returned. Internal to core\n * (`processors/stream-reprocess.ts`, used by `BatchPartsProcessor`); mirrored\n * here rather than exported so Factory's one use doesn't widen core's API.\n */\nconst REPROCESS_PART_KEY = '__mastraReprocessPart';\n\n/** Text-part id of the link delta; never collides with a model block id. */\nconst LINK_PART_ID = 'factory-session-link';\n\n/**\n * Emits an `Open session ↗` link right after the first reply of a new channel\n * session, so the link closes the reply rather than leading it. The channel\n * driver ends a post at `text-end`, so Slack shows the link as its own short\n * message after the reply.\n *\n * \"End of the reply\" is not `text-end`: a reply with citations is several\n * text blocks (`text … source … text`), each with its own `text-end`. The\n * reply ends at the first `tool-call` (the opener before tools run) or at\n * `step-finish` (a reply with no tools), whichever comes first after some\n * text. A processor can only return one part, so on that chunk this returns\n * a `text-delta` carrying the link and stashes the chunk itself under\n * `REPROCESS_PART_KEY`, which the runner re-drives through the chain right\n * after — the link lands before it and downstream processors see both.\n * Factory-emitted rather than left to the model so a skipped opener can't\n * drop it. No-op without the new-session marker or a public origin.\n *\n * The streamed text is also what gets persisted, and the link is a Slack\n * display detail: in memory it would show the model its own `[↗](…)` on\n * later turns (inviting it to fabricate links) and render a self-link in\n * the web transcript. The link delta opens its own text part, so\n * `processOutputStep` drops that part from the assistant message before\n * `MessageHistory` saves it.\n */\nexport class FactoryChannelSessionLinkProcessor implements Processor {\n readonly id = 'factory-channel-session-link';\n\n async processOutputStream({ part, state, requestContext }: ProcessOutputStreamArgs): Promise<ChunkType> {\n if (state.linked || !requestContext?.get(NEW_CHANNEL_SESSION_KEY)) return part;\n if (part.type === 'text-delta') {\n state.textStarted = true;\n return part;\n }\n if ((part.type !== 'tool-call' && part.type !== 'step-finish') || !state.textStarted) return part;\n state.linked = true;\n const link = sessionLinkFromRequest(requestContext);\n if (!link) return part;\n state[REPROCESS_PART_KEY] = part;\n return {\n type: 'text-delta',\n runId: part.runId,\n from: part.from,\n payload: { id: LINK_PART_ID, text: linkSuffix(link) },\n };\n }\n\n processOutputStep({ messageList, requestContext }: ProcessOutputStepArgs) {\n if (!requestContext?.get(NEW_CHANNEL_SESSION_KEY)) return messageList;\n const link = sessionLinkFromRequest(requestContext);\n if (!link) return messageList;\n const suffix = linkSuffix(link);\n for (const message of messageList.get.response.db()) {\n if (message.role !== 'assistant') continue;\n const index = message.content.parts.findIndex(part => part.type === 'text' && part.text === suffix);\n if (index === -1) continue;\n message.content.parts.splice(index, 1);\n if (typeof message.content.content === 'string' && message.content.content.endsWith(suffix)) {\n message.content.content = message.content.content.slice(0, -suffix.length);\n }\n return messageList;\n }\n return messageList;\n }\n}\n\nfunction linkSuffix(link: string): string {\n // Own paragraph: the link closes the message, it is not part of the last sentence.\n return `\\n\\n[${SESSION_LINK_LABEL}](${link})`;\n}\n\nfunction sessionLinkFromRequest(requestContext: RequestContext): string | undefined {\n const controller = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n if (!controller?.threadId) return undefined;\n return sessionLink({\n threadId: controller.threadId,\n resourceId: controller.resourceId,\n factoryProjectId: readFactorySessionScope(requestContext)?.factoryProjectId,\n });\n}\n"],"mappings":";;;;;;;AAYA,MAAa,0BAA0B;AAEvC,SAAgB,sBAAsB,gBAAsC;CAC1E,eAAe,IAAI,yBAAyB,IAAI;AAClD;;;;;;;AAQA,MAAM,qBAAqB;;AAG3B,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;AA0BrB,IAAa,qCAAb,MAAqE;CACnE,KAAc;CAEd,MAAM,oBAAoB,EAAE,MAAM,OAAO,kBAA+D;EACtG,IAAI,MAAM,UAAU,CAAC,gBAAgB,IAAA,4BAA2B,GAAG,OAAO;EAC1E,IAAI,KAAK,SAAS,cAAc;GAC9B,MAAM,cAAc;GACpB,OAAO;EACT;EACA,IAAK,KAAK,SAAS,eAAe,KAAK,SAAS,iBAAkB,CAAC,MAAM,aAAa,OAAO;EAC7F,MAAM,SAAS;EACf,MAAM,OAAO,uBAAuB,cAAc;EAClD,IAAI,CAAC,MAAM,OAAO;EAClB,MAAM,sBAAsB;EAC5B,OAAO;GACL,MAAM;GACN,OAAO,KAAK;GACZ,MAAM,KAAK;GACX,SAAS;IAAE,IAAI;IAAc,MAAM,WAAW,IAAI;GAAE;EACtD;CACF;CAEA,kBAAkB,EAAE,aAAa,kBAAyC;EACxE,IAAI,CAAC,gBAAgB,IAAA,4BAA2B,GAAG,OAAO;EAC1D,MAAM,OAAO,uBAAuB,cAAc;EAClD,IAAI,CAAC,MAAM,OAAO;EAClB,MAAM,SAAS,WAAW,IAAI;EAC9B,KAAK,MAAM,WAAW,YAAY,IAAI,SAAS,GAAG,GAAG;GACnD,IAAI,QAAQ,SAAS,aAAa;GAClC,MAAM,QAAQ,QAAQ,QAAQ,MAAM,WAAU,SAAQ,KAAK,SAAS,UAAU,KAAK,SAAS,MAAM;GAClG,IAAI,UAAU,IAAI;GAClB,QAAQ,QAAQ,MAAM,OAAO,OAAO,CAAC;GACrC,IAAI,OAAO,QAAQ,QAAQ,YAAY,YAAY,QAAQ,QAAQ,QAAQ,SAAS,MAAM,GACxF,QAAQ,QAAQ,UAAU,QAAQ,QAAQ,QAAQ,MAAM,GAAG,CAAC,OAAO,MAAM;GAE3E,OAAO;EACT;EACA,OAAO;CACT;AACF;AAEA,SAAS,WAAW,MAAsB;CAExC,OAAO,QAAQ,mBAAmB,IAAI,KAAK;AAC7C;AAEA,SAAS,uBAAuB,gBAAoD;CAClF,MAAM,aAAa,eAAe,IAAI,YAAY;CAClD,IAAI,CAAC,YAAY,UAAU,OAAO,KAAA;CAClC,OAAO,YAAY;EACjB,UAAU,WAAW;EACrB,YAAY,WAAW;EACvB,kBAAkB,wBAAwB,cAAc,CAAC,EAAE;CAC7D,CAAC;AACH"}
1
+ {"version":3,"file":"channel-session-link-processor.js","names":[],"sources":["../../src/session/channel-session-link-processor.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Processor, ProcessOutputStepArgs, ProcessOutputStreamArgs } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ChunkType } from '@mastra/core/stream';\n\nimport { readFactorySessionScope } from '../rules/binding-context.js';\nimport { SESSION_LINK_LABEL, sessionLink } from './channel-reply-processor.js';\n\n/**\n * Request-context marker a channel handler sets on the run that opens a new\n * thread. Only that run gets the link; follow-ups in the same thread don't.\n */\nexport const NEW_CHANNEL_SESSION_KEY = 'factory__newChannelSession';\n\nexport function markNewChannelSession(requestContext: RequestContext): void {\n requestContext.set(NEW_CHANNEL_SESSION_KEY, true);\n}\n\n/**\n * State key the core ProcessorRunner reads to re-drive one extra part through\n * the output chain after the part a processor returned. Internal to core\n * (`processors/stream-reprocess.ts`, used by `BatchPartsProcessor`); mirrored\n * here rather than exported so Factory's one use doesn't widen core's API.\n */\nconst REPROCESS_PART_KEY = '__mastraReprocessPart';\n\n/** Text-part id of the link delta; never collides with a model block id. */\nconst LINK_PART_ID = 'factory-session-link';\n\n/**\n * Emits an `Open session ↗` link right after the first reply of a new channel\n * session, so the link closes the reply rather than leading it. The channel\n * driver ends a post at `text-end`, so Slack shows the link as its own short\n * message after the reply.\n *\n * \"End of the reply\" is not `text-end`: a reply with citations is several\n * text blocks (`text … source … text`), each with its own `text-end`. The\n * reply ends at the first `tool-call` (the opener before tools run) or at\n * `step-finish` (a reply with no tools), whichever comes first after some\n * text. A processor can only return one part, so on that chunk this returns\n * a `text-delta` carrying the link and stashes the chunk itself under\n * `REPROCESS_PART_KEY`, which the runner re-drives through the chain right\n * after — the link lands before it and downstream processors see both.\n * Factory-emitted rather than left to the model so a skipped opener can't\n * drop it. No-op without the new-session marker or a public origin.\n *\n * The streamed text is also what gets persisted, and the link is a Slack\n * display detail: in memory it would show the model its own `[↗](…)` on\n * later turns (inviting it to fabricate links) and render a self-link in\n * the web transcript. The link delta opens its own text part, so\n * `processOutputStep` drops that part from the assistant message before\n * `MessageHistory` saves it.\n */\nexport class FactoryChannelSessionLinkProcessor implements Processor {\n readonly id = 'factory-channel-session-link';\n\n async processOutputStream({ part, state, requestContext }: ProcessOutputStreamArgs): Promise<ChunkType> {\n if (state.linked || !requestContext?.get(NEW_CHANNEL_SESSION_KEY)) return part;\n if (part.type === 'text-delta') {\n state.textStarted = true;\n return part;\n }\n if ((part.type !== 'tool-call' && part.type !== 'step-finish') || !state.textStarted) return part;\n state.linked = true;\n const link = sessionLinkFromRequest(requestContext);\n if (!link) return part;\n state[REPROCESS_PART_KEY] = part;\n return {\n type: 'text-delta',\n runId: part.runId,\n from: part.from,\n payload: { id: LINK_PART_ID, text: linkSuffix(link) },\n };\n }\n\n processOutputStep({ messageList, requestContext }: ProcessOutputStepArgs) {\n if (!requestContext?.get(NEW_CHANNEL_SESSION_KEY)) return messageList;\n const link = sessionLinkFromRequest(requestContext);\n if (!link) return messageList;\n const suffix = linkSuffix(link);\n for (const message of messageList.get.response.db()) {\n if (message.role !== 'assistant') continue;\n const index = message.content.parts.findIndex(part => part.type === 'text' && part.text === suffix);\n if (index === -1) continue;\n message.content.parts.splice(index, 1);\n if (typeof message.content.content === 'string' && message.content.content.endsWith(suffix)) {\n message.content.content = message.content.content.slice(0, -suffix.length);\n }\n return messageList;\n }\n return messageList;\n }\n}\n\nfunction linkSuffix(link: string): string {\n // Own paragraph: the link closes the message, it is not part of the last sentence.\n return `\\n\\n[${SESSION_LINK_LABEL}](${link})`;\n}\n\nfunction sessionLinkFromRequest(requestContext: RequestContext): string | undefined {\n const controller = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n if (!controller?.threadId) return undefined;\n return sessionLink({\n threadId: controller.threadId,\n sessionId: controller.sessionId,\n resourceId: controller.resourceId,\n factoryProjectId: readFactorySessionScope(requestContext)?.factoryProjectId,\n });\n}\n"],"mappings":";;;;;;;AAYA,MAAa,0BAA0B;AAEvC,SAAgB,sBAAsB,gBAAsC;CAC1E,eAAe,IAAI,yBAAyB,IAAI;AAClD;;;;;;;AAQA,MAAM,qBAAqB;;AAG3B,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;AA0BrB,IAAa,qCAAb,MAAqE;CACnE,KAAc;CAEd,MAAM,oBAAoB,EAAE,MAAM,OAAO,kBAA+D;EACtG,IAAI,MAAM,UAAU,CAAC,gBAAgB,IAAA,4BAA2B,GAAG,OAAO;EAC1E,IAAI,KAAK,SAAS,cAAc;GAC9B,MAAM,cAAc;GACpB,OAAO;EACT;EACA,IAAK,KAAK,SAAS,eAAe,KAAK,SAAS,iBAAkB,CAAC,MAAM,aAAa,OAAO;EAC7F,MAAM,SAAS;EACf,MAAM,OAAO,uBAAuB,cAAc;EAClD,IAAI,CAAC,MAAM,OAAO;EAClB,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AU,8BAA8B;IACtC,QAAQ,EAAE,IAAI,CAAC,sBAAsB,EAAE,SAAS,CAAC,CAAC;IAClD,aAAa,EAAE,IAAI,CAAC,0BAA0B,EAAE,gBAAgB,CAAC,CAAC;IAClE,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,wBAAwB,CAAC,CAAC;CAC7D;AAED,uGAAuG;AACvG,wBAAsB,8BAA8B,CAClD,cAAc,EAAE,cAAc,EAC9B,IAAI,EAAE,8BAA8B,GACnC,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAEvC;AAED,+FAA+F;AAC/F,wBAAsB,yBAAyB,CAC7C,cAAc,EAAE,cAAc,EAC9B,IAAI,EAAE,8BAA8B,GACnC,OAAO,CAAC;IAAE,MAAM,EAAE,gBAAgB,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,qBAAqB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,GAAG,SAAS,CAAC,CAwDrH"}
@@ -12,18 +12,19 @@ async function resolveFactoryModelPolicy(requestContext, deps) {
12
12
  const principal = resolveAuthenticatedCredentialTenant(requestContext);
13
13
  if (!principal) return void 0;
14
14
  const controller = requestContext.get("controller");
15
- if (!controller?.resourceId) return { tenant: principal };
16
- const sourceSession = await deps.sourceControl.getBySessionId(controller.resourceId);
15
+ if (!controller?.sessionId || !controller.resourceId) return { tenant: principal };
16
+ const { sessionId, resourceId } = controller;
17
+ const sourceSession = await deps.sourceControl.getBySessionId(sessionId);
17
18
  const binding = principal.orgId && controller.threadId ? await deps.workItems.findRunBindingByThread({
18
19
  orgId: principal.orgId,
19
- resourceId: controller.resourceId,
20
- sessionId: controller.resourceId,
20
+ resourceId,
21
+ sessionId,
21
22
  threadId: controller.threadId,
22
23
  rejectAmbiguous: true
23
24
  }) : null;
24
25
  if (!sourceSession) {
25
- if (!binding && (controller.resourceId === principal.userId || controller.resourceId.startsWith("channel:"))) return { tenant: principal };
26
- const factoryProject = !binding && FACTORY_PROJECT_ID.test(controller.resourceId) ? await deps.projects.getById({ id: controller.resourceId }) : null;
26
+ if (!binding && (resourceId === principal.userId || resourceId.startsWith("channel:"))) return { tenant: principal };
27
+ const factoryProject = !binding && sessionId === resourceId && FACTORY_PROJECT_ID.test(resourceId) ? await deps.projects.getById({ id: resourceId }) : null;
27
28
  if (factoryProject && factoryProject.orgId === principal.orgId) return {
28
29
  factoryProjectId: factoryProject.id,
29
30
  factoryDefaultModelId: factoryProject.defaultModelId,
@@ -1 +1 @@
1
- {"version":3,"file":"credential-policy.js","names":[],"sources":["../../src/session/credential-policy.ts"],"sourcesContent":["import { resolveAuthenticatedCredentialTenant } from '@mastra/code-sdk/agents/credential-resolver';\nimport type { CredentialTenant } from '@mastra/code-sdk/agents/credential-resolver';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport { UUID_PATTERN } from '../routes/contracts.js';\nimport { effectiveModelScope } from '../storage/domains/projects/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { SourceControlSessionLookup } from './factory-session.js';\n\nconst FACTORY_PROJECT_ID = new RegExp(UUID_PATTERN);\n\ninterface FactoryModelPolicyDependencies {\n projects: Pick<FactoryProjectsStorage, 'getById'>;\n sourceControl: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n workItems: Pick<WorkItemsStorage, 'findRunBindingByThread'>;\n}\n\n/** Resolve billing authority from authenticated identity and durable bindings, never session state. */\nexport async function resolveFactoryCredentialTenant(\n requestContext: RequestContext,\n deps: FactoryModelPolicyDependencies,\n): Promise<CredentialTenant | undefined> {\n return (await resolveFactoryModelPolicy(requestContext, deps))?.tenant;\n}\n\n/** Shared invocation and model-picker policy; no client-supplied owner or scope is trusted. */\nexport async function resolveFactoryModelPolicy(\n requestContext: RequestContext,\n deps: FactoryModelPolicyDependencies,\n): Promise<{ tenant: CredentialTenant; factoryProjectId?: string; factoryDefaultModelId?: string | null } | undefined> {\n const principal = resolveAuthenticatedCredentialTenant(requestContext);\n if (!principal) return undefined;\n const controller = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n if (!controller?.resourceId) return { tenant: principal };\n\n const sourceSession = await deps.sourceControl.getBySessionId(controller.resourceId);\n const binding =\n principal.orgId && controller.threadId\n ? await deps.workItems.findRunBindingByThread({\n orgId: principal.orgId,\n resourceId: controller.resourceId,\n sessionId: controller.resourceId,\n threadId: controller.threadId,\n rejectAmbiguous: true,\n })\n : null;\n if (!sourceSession) {\n if (!binding && (controller.resourceId === principal.userId || controller.resourceId.startsWith('channel:')))\n return { tenant: principal };\n // Session-less Factory pages address the Factory itself: the resourceId is the project id.\n const factoryProject =\n !binding && FACTORY_PROJECT_ID.test(controller.resourceId)\n ? await deps.projects.getById({ id: controller.resourceId })\n : null;\n if (factoryProject && factoryProject.orgId === principal.orgId) {\n return {\n factoryProjectId: factoryProject.id,\n factoryDefaultModelId: factoryProject.defaultModelId,\n tenant: { ...principal, credentialScope: effectiveModelScope(factoryProject.modelScope, 'session') },\n };\n }\n throw new Error('Factory session ownership is unavailable.');\n }\n if (\n sourceSession.orgId !== principal.orgId ||\n (sourceSession.visibility === 'private' && sourceSession.userId !== principal.userId)\n ) {\n throw new Error('Factory session is not available to the current user.');\n }\n if (!sourceSession.factoryProjectId) throw new Error('Factory session ownership is unavailable.');\n const projectId = binding?.factoryProjectId ?? sourceSession.factoryProjectId;\n const project = await deps.projects.getById({ id: projectId });\n if (!project || project.orgId !== sourceSession.orgId) throw new Error('Factory model policy is unavailable.');\n // Work-item threads keep their billing scope after revocation; history never restores run authority.\n return {\n factoryProjectId: project.id,\n factoryDefaultModelId: project.defaultModelId,\n tenant: {\n orgId: project.orgId,\n userId: sourceSession.userId,\n credentialScope: effectiveModelScope(project.modelScope, binding ? 'run' : 'session'),\n },\n };\n}\n"],"mappings":";;;;AAWA,MAAM,qBAAqB,IAAI,OAAO,YAAY;;A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I,UAAU,CAAC;CAC7D,IAAI,CAAC,WAAW,QAAQ,UAAU,cAAc,OAAO,MAAM,IAAI,MAAM,sCAAsC;CAE7G,OAAO;EACL,kBAAkB,QAAQ;EAC1B,uBAAuB,QAAQ;EAC/B,QAAQ;GACN,OAAO,QAAQ;GACf,QAAQ,cAAc;GACtB,iBAAiB,oBAAoB,QAAQ,YAAY,UAAU,QAAQ,SAAS;EACtF;CACF;AACF"}
1
+ {"version":3,"file":"credential-policy.js","names":[],"sources":["../../src/session/credential-policy.ts"],"sourcesContent":["import { resolveAuthenticatedCredentialTenant } from '@mastra/code-sdk/agents/credential-resolver';\nimport type { CredentialTenant } from '@mastra/code-sdk/agents/credential-resolver';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport { UUID_PATTERN } from '../routes/contracts.js';\nimport { effectiveModelScope } from '../storage/domains/projects/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { SourceControlSessionLookup } from './factory-session.js';\n\nconst FACTORY_PROJECT_ID = new RegExp(UUID_PATTERN);\n\ninterface FactoryModelPolicyDependencies {\n projects: Pick<FactoryProjectsStorage, 'getById'>;\n sourceControl: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n workItems: Pick<WorkItemsStorage, 'findRunBindingByThread'>;\n}\n\n/** Resolve billing authority from authenticated identity and durable bindings, never session state. */\nexport async function resolveFactoryCredentialTenant(\n requestContext: RequestContext,\n deps: FactoryModelPolicyDependencies,\n): Promise<CredentialTenant | undefined> {\n return (await resolveFactoryModelPolicy(requestContext, deps))?.tenant;\n}\n\n/** Shared invocation and model-picker policy; no client-supplied owner or scope is trusted. */\nexport async function resolveFactoryModelPolicy(\n requestContext: RequestContext,\n deps: FactoryModelPolicyDependencies,\n): Promise<{ tenant: CredentialTenant; factoryProjectId?: string; factoryDefaultModelId?: string | null } | undefined> {\n const principal = resolveAuthenticatedCredentialTenant(requestContext);\n if (!principal) return undefined;\n const controller = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n if (!controller?.sessionId || !controller.resourceId) return { tenant: principal };\n const { sessionId, resourceId } = controller;\n\n const sourceSession = await deps.sourceControl.getBySessionId(sessionId);\n const binding =\n principal.orgId && controller.threadId\n ? await deps.workItems.findRunBindingByThread({\n orgId: principal.orgId,\n resourceId,\n sessionId,\n threadId: controller.threadId,\n rejectAmbiguous: true,\n })\n : null;\n if (!sourceSession) {\n if (!binding && (resourceId === principal.userId || resourceId.startsWith('channel:')))\n return { tenant: principal };\n // Session-less Factory pages address the Factory itself: session and resource are both the\n // project id. A run session under its Factory's resource whose row is gone is not a page.\n const factoryProject =\n !binding && sessionId === resourceId && FACTORY_PROJECT_ID.test(resourceId)\n ? await deps.projects.getById({ id: resourceId })\n : null;\n if (factoryProject && factoryProject.orgId === principal.orgId) {\n return {\n factoryProjectId: factoryProject.id,\n factoryDefaultModelId: factoryProject.defaultModelId,\n tenant: { ...principal, credentialScope: effectiveModelScope(factoryProject.modelScope, 'session') },\n };\n }\n throw new Error('Factory session ownership is unavailable.');\n }\n if (\n sourceSession.orgId !== principal.orgId ||\n (sourceSession.visibility === 'private' && sourceSession.userId !== principal.userId)\n ) {\n throw new Error('Factory session is not available to the current user.');\n }\n if (!sourceSession.factoryProjectId) throw new Error('Factory session ownership is unavailable.');\n const projectId = binding?.factoryProjectId ?? sourceSession.factoryProjectId;\n const project = await deps.projects.getById({ id: projectId });\n if (!project || project.orgId !== sourceSession.orgId) throw new Error('Factory model policy is unavailable.');\n // Work-item threads keep their billing scope after revocation; history never restores run authority.\n return {\n factoryProjectId: project.id,\n factoryDefaultModelId: project.defaultModelId,\n tenant: {\n orgId: project.orgId,\n userId: sourceSession.userId,\n credentialScope: effectiveModelScope(project.modelScope, binding ? 'run' : 'session'),\n },\n };\n}\n"],"mappings":";;;;AAWA,MAAM,qBAAqB,IAAI,OAAO,YAAY;;AASlD,eA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UAAU,CAAC;CAC7D,IAAI,CAAC,WAAW,QAAQ,UAAU,cAAc,OAAO,MAAM,IAAI,MAAM,sCAAsC;CAE7G,OAAO;EACL,kBAAkB,QAAQ;EAC1B,uBAAuB,QAAQ;EAC/B,QAAQ;GACN,OAAO,QAAQ;GACf,QAAQ,cAAc;GACtB,iBAAiB,oBAAoB,QAAQ,YAAY,UAAU,QAAQ,SAAS;EACtF;CACF;AACF"}
@@ -17,6 +17,7 @@ export interface DefaultModelApplicableSession {
17
17
  }
18
18
  export interface DefaultModelHydrationSession extends DefaultModelApplicableSession {
19
19
  readonly identity: {
20
+ getId(): string;
20
21
  getResourceId(): string;
21
22
  };
22
23
  model: DefaultModelApplicableSession['model'] & {
@@ -1 +1 @@
1
- {"version":3,"file":"default-model-hydration.d.ts","sourceRoot":"","sources":["../../src/session/default-model-hydration.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAEtF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAEvE,MAAM,WAAW,6BAA6B;IAC5C,KAAK,EAAE;QAAE,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;KAAE,CAAC;IACrD,SAAS,EAAE;QAAE,KAAK,EAAE;YAAE,GAAG,CAAC,IAAI,EAAE;gBAAE,OAAO,EAAE,MAAM,CAAC;gBAAC,SAAS,EAAE,MAAM,CAAA;aAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;SAAE,CAAA;KAAE,CAAC;CAC/F;AAED,MAAM,WAAW,4BAA6B,SAAQ,6BAA6B;IACjF,QAAQ,CAAC,QAAQ,EAAE;QAAE,aAAa,IAAI,MAAM,CAAA;KAAE,CAAC;IA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IAAI,CAAC,0BAA0B,EAAE,gBAAgB,CAAC,CAAC;IAClE,QAAQ,EAAE,IAAI,CAAC,sBAAsB,EAAE,SAAS,CAAC,CAAC;IAClD,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,wBAAwB,CAAC,CAAC;IAC5D,aAAa,EAAE,IAAI,CAAC,oBAAoB,EAAE,KAAK,CAAC,CAAC;CAClD;AAED,0FAA0F;AAC1F,wBAAsB,0BAA0B,CAC9C,OAAO,EAAE,4BAA4B,EACrC,EAAE,aAAa,EAAE,QAAQ,EAAE,SAAS,EAAE,aAAa,EAAE,EAAE,iCAAiC,GACvF,OAAO,CAAC,IAAI,CAAC,CA+Ef"}
@@ -14,6 +14,7 @@ async function applyDefaultModel(session, modelId) {
14
14
  }
15
15
  /** Seed a new chat's scoped default model; a chat with a user message keeps its model. */
16
16
  async function hydrateSessionDefaultModel(session, { sourceControl, projects, workItems, modelDefaults }) {
17
+ const sessionId = session.identity.getId();
17
18
  const resourceId = session.identity.getResourceId();
18
19
  const initialState = session.state.get() ?? {};
19
20
  if (initialState.factoryProjectId || typeof session.thread.firstUserMessage !== "function") return;
@@ -29,7 +30,7 @@ async function hydrateSessionDefaultModel(session, { sourceControl, projects, wo
29
30
  });
30
31
  let identityResolved = false;
31
32
  try {
32
- const sourceSession = await sourceControl.getBySessionId(resourceId);
33
+ const sourceSession = await sourceControl.getBySessionId(sessionId);
33
34
  if (!sourceSession) {
34
35
  await clearFactoryIdentity();
35
36
  return;
@@ -43,7 +44,7 @@ async function hydrateSessionDefaultModel(session, { sourceControl, projects, wo
43
44
  orgId: sourceSession.orgId,
44
45
  threadId,
45
46
  resourceId,
46
- sessionId: resourceId,
47
+ sessionId,
47
48
  rejectAmbiguous: true
48
49
  }) : null;
49
50
  const project = await projects.getById({ id: binding?.factoryProjectId ?? sourceSession.factoryProjectId });
@@ -1 +1 @@
1
- {"version":3,"file":"default-model-hydration.js","names":[],"sources":["../../src/session/default-model-hydration.ts"],"sourcesContent":["import { primeTenantCredentialsForTenant, resolveTenantProviderDefaultModel } from '../routes/tenant-credentials.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope } from '../storage/domains/projects/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { SourceControlSessionLookup } from './factory-session.js';\n\nexport interface DefaultModelApplicableSession {\n model: { switch(modelId: string): Promise<unknown> };\n subagents: { model: { set(args: { modelId: string; agentType: string }): Promise<unknown> } };\n}\n\nexport interface DefaultModelHydrationSession extends DefaultModelApplicableSession {\n readonly identity: { getResourceId(): string };\n model: DefaultModelApplicableSession['model'] & { get(): string; setDefault(args: { modelId: string }): void };\n state: {\n get(): Record<string, unknown> | undefined;\n set(updates: Record<string, unknown>): Promise<unknown>;\n };\n thread: {\n getId(): string | null | undefined;\n firstUserMessage(args: { threadId: string }): Promise<unknown>;\n };\n}\n\nasync function applyDefaultModel(session: DefaultModelApplicableSession, modelId: string): Promise<void> {\n await session.model.switch(modelId);\n\n for (const agentType of ['explore', 'plan', 'execute']) {\n await session.subagents.model.set({ modelId, agentType });\n }\n}\n\nexport interface DefaultModelHydrationDependencies {\n sourceControl: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n projects: Pick<FactoryProjectsStorage, 'getById'>;\n workItems: Pick<WorkItemsStorage, 'findRunBindingByThread'>;\n modelDefaults: Pick<ModelDefaultsStorage, 'get'>;\n}\n\n/** Seed a new chat's scoped default model; a chat with a user message keeps its model. */\nexport async function hydrateSessionDefaultModel(\n session: DefaultModelHydrationSession,\n { sourceControl, projects, workItems, modelDefaults }: DefaultModelHydrationDependencies,\n): Promise<void> {\n const resourceId = session.identity.getResourceId();\n const initialState = session.state.get() ?? {};\n if (initialState.factoryProjectId || typeof session.thread.firstUserMessage !== 'function') return;\n const hadFactoryIdentity = initialState.factoryModelScope === 'factory' || initialState.factoryModelScope === 'user';\n const clearFactoryIdentity = () =>\n session.state.set({ factoryOrgId: undefined, factoryModelScope: undefined, factoryOwnerUserId: undefined });\n const failClosedWithoutIdentity = () =>\n session.state.set({ factoryModelScope: 'user', factoryOwnerUserId: undefined });\n let identityResolved = false;\n try {\n const sourceSession = await sourceControl.getBySessionId(resourceId);\n if (!sourceSession) {\n await clearFactoryIdentity();\n return;\n }\n if (!sourceSession.factoryProjectId) {\n await clearFactoryIdentity();\n return;\n }\n // Historical thread membership keeps completed work items on Factory billing in hybrid scope.\n const threadId = session.thread.getId();\n const binding = threadId\n ? await workItems.findRunBindingByThread({\n orgId: sourceSession.orgId,\n threadId,\n resourceId,\n sessionId: resourceId,\n rejectAmbiguous: true,\n })\n : null;\n const project = await projects.getById({ id: binding?.factoryProjectId ?? sourceSession.factoryProjectId });\n if (!project || project.orgId !== sourceSession.orgId) {\n await clearFactoryIdentity();\n return;\n }\n const modelScope = effectiveModelScope(project.modelScope, binding ? 'run' : 'session');\n await session.state.set({\n factoryOrgId: sourceSession.orgId,\n factoryModelScope: modelScope,\n factoryOwnerUserId: sourceSession.userId,\n });\n identityResolved = true;\n await primeTenantCredentialsForTenant({\n orgId: sourceSession.orgId,\n userId: sourceSession.userId,\n credentialScope: modelScope,\n });\n\n if (binding) return;\n if (threadId && (await session.thread.firstUserMessage({ threadId }))) return;\n\n const scopedModelId =\n (modelScope === 'factory'\n ? project.defaultModelId\n : (await modelDefaults.get({ orgId: sourceSession.orgId, userId: sourceSession.userId }))?.modelId) ??\n // No chosen default: a connected provider's default, unless the current model is usable.\n (await resolveTenantProviderDefaultModel(\n { orgId: sourceSession.orgId, userId: sourceSession.userId, credentialScope: modelScope },\n session.model.get() || undefined,\n ).catch(error => {\n console.warn('[Factory default-model hydration] Unable to resolve a provider default model.', error);\n return undefined;\n }));\n if (!scopedModelId) return;\n // A thread the session creates later (the UI binding its conventional\n // thread after a thread-agnostic request opened the session) starts from\n // the session default, not from the thread hydrated here.\n session.model.setDefault({ modelId: scopedModelId });\n await applyDefaultModel(session, scopedModelId);\n } catch (error) {\n if (!identityResolved && !hadFactoryIdentity) {\n try {\n await failClosedWithoutIdentity();\n } catch {}\n }\n console.warn('[Factory default-model hydration] Unable to apply the scoped default model.', error);\n }\n}\n"],"mappings":";;;AAyBA,eAAe,kBAAkB,SAAwC,SAAgC;CACvG,MAAM,QAAQ,MAAM,OAAO,OAAO;CAElC,KAAK,MAAM,aAAa;EAAC;EAAW;EAAQ;CAAS,GACnD,MAAM,QAAQ,UAAU,MAAM,IAAI;EAAE;EAAS;CAAU,CAAC;AAE5D;;AAUA,eAAsB,2BACpB,SACA,EAAE,eAAe,UAAU,WAAW,iBACvB;CACf,MAAM,aAAa,QAAQ,SAAS,cAAc;CAClD,MAAM,eAAe,QAAQ,MAAM,IAAI,KAAK,CAAC;CAC7C,IAAI,aAAa,oBAAoB,OAAO,QAAQ,OAAO,qBAAqB,YAAY;CAC5F,MAAM,qBAAqB,aAAa,sBAAsB,aAAa,aAAa,sBAAsB;CAC9G,MAAM,6BACJ,QAAQ,MAAM,IAAI;EAAE,cAAc,KAAA;EAAW,mBAAmB,KAAA;EAAW,oBAAoB,KAAA;CAAU,CAAC;CAC5G,MAAM,kCACJ,QAAQ,MAAM,IAAI;EAAE,mBAAmB;EAAQ,oBAAoB,KAAA;CAAU,CAAC;CAChF,IAAI,mBAAmB;CACvB,IAAI;EACF,MAAM,gBAAgB,MAAM,cAAc,eAAe,UAAU;EACnE,IAAI,CAAC,eAAe;GAClB,MAAM,qBAAqB;GAC3B;EACF;EACA,IAAI,CAAC,cAAc,kBAAkB;GACnC,MAAM,qBAAqB;GAC3B;EACF;EAEA,MAAM,WAAW,QAAQ,OAAO,MAAM;EACtC,MAAM,UAAU,WACZ,MAAM,UAAU,uBAAuB;GACrC,OAAO,cAAc;GACrB;GACA;GACA,WAAW;GACX,iBAAiB;EACnB,CAAC,IACD;EACJ,MAAM,UAAU,MAAM,SAAS,QAAQ,EAAE,IAAI,SAAS,oBAAoB,cAAc,iBAAiB,CAAC;EAC1G,IAAI,CAAC,WAAW,QAAQ,UAAU,cAAc,OAAO;GACrD,MAAM,qBAAqB;GAC3B;EACF;EACA,MAAM,aAAa,oBAAoB,QAAQ,YAAY,UAAU,QAAQ,SAAS;EACtF,MAAM,QAAQ,MAAM,IAAI;GACtB,cAAc,cAAc;GAC5B,mBAAmB;GACnB,oBAAoB,cAAc;EACpC,CAAC;EACD,mBAAmB;EACnB,MAAM,gCAAgC;GACpC,OAAO,cAAc;GACrB,QAAQ,cAAc;GACtB,iBAAiB;EACnB,CAAC;EAED,IAAI,SAAS;EACb,IAAI,YAAa,MAAM,QAAQ,OAAO,iBAAiB,EAAE,SAAS,CAAC,GAAI;EAEvE,MAAM,iBACH,eAAe,YACZ,QAAQ,kBACP,MAAM,cAAc,IAAI;GAAE,OAAO,cAAc;GAAO,QAAQ,cAAc;EAAO,CAAC,EAAA,EAAI,YAE5F,MAAM,kCACL;GAAE,OAAO,cAAc;GAAO,QAAQ,cAAc;GAAQ,iBAAiB;EAAW,GACxF,QAAQ,MAAM,IAAI,KAAK,KAAA,CACzB,CAAC,CAAC,OAAM,UAAS;GACf,QAAQ,KAAK,iFAAiF,KAAK;EAErG,CAAC;EACH,IAAI,CAAC,eAAe;EAIpB,QAAQ,MAAM,WAAW,EAAE,SAAS,cAAc,CAAC;EACnD,MAAM,kBAAkB,SAAS,aAAa;CAChD,SAAS,OAAO;EACd,IAAI,CAAC,oBAAoB,CAAC,oBACxB,IAAI;GACF,MAAM,0BAA0B;EAClC,QAAQ,CAAC;EAEX,QAAQ,KAAK,+EAA+E,KAAK;CACnG;AACF"}
1
+ {"version":3,"file":"default-model-hydration.js","names":[],"sources":["../../src/session/default-model-hydration.ts"],"sourcesContent":["import { primeTenantCredentialsForTenant, resolveTenantProviderDefaultModel } from '../routes/tenant-credentials.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope } from '../storage/domains/projects/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { SourceControlSessionLookup } from './factory-session.js';\n\nexport interface DefaultModelApplicableSession {\n model: { switch(modelId: string): Promise<unknown> };\n subagents: { model: { set(args: { modelId: string; agentType: string }): Promise<unknown> } };\n}\n\nexport interface DefaultModelHydrationSession extends DefaultModelApplicableSession {\n readonly identity: { getId(): string; getResourceId(): string };\n model: DefaultModelApplicableSession['model'] & { get(): string; setDefault(args: { modelId: string }): void };\n state: {\n get(): Record<string, unknown> | undefined;\n set(updates: Record<string, unknown>): Promise<unknown>;\n };\n thread: {\n getId(): string | null | undefined;\n firstUserMessage(args: { threadId: string }): Promise<unknown>;\n };\n}\n\nasync function applyDefaultModel(session: DefaultModelApplicableSession, modelId: string): Promise<void> {\n await session.model.switch(modelId);\n\n for (const agentType of ['explore', 'plan', 'execute']) {\n await session.subagents.model.set({ modelId, agentType });\n }\n}\n\nexport interface DefaultModelHydrationDependencies {\n sourceControl: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n projects: Pick<FactoryProjectsStorage, 'getById'>;\n workItems: Pick<WorkItemsStorage, 'findRunBindingByThread'>;\n modelDefaults: Pick<ModelDefaultsStorage, 'get'>;\n}\n\n/** Seed a new chat's scoped default model; a chat with a user message keeps its model. */\nexport async function hydrateSessionDefaultModel(\n session: DefaultModelHydrationSession,\n { sourceControl, projects, workItems, modelDefaults }: DefaultModelHydrationDependencies,\n): Promise<void> {\n const sessionId = session.identity.getId();\n const resourceId = session.identity.getResourceId();\n const initialState = session.state.get() ?? {};\n if (initialState.factoryProjectId || typeof session.thread.firstUserMessage !== 'function') return;\n const hadFactoryIdentity = initialState.factoryModelScope === 'factory' || initialState.factoryModelScope === 'user';\n const clearFactoryIdentity = () =>\n session.state.set({ factoryOrgId: undefined, factoryModelScope: undefined, factoryOwnerUserId: undefined });\n const failClosedWithoutIdentity = () =>\n session.state.set({ factoryModelScope: 'user', factoryOwnerUserId: undefined });\n let identityResolved = false;\n try {\n const sourceSession = await sourceControl.getBySessionId(sessionId);\n if (!sourceSession) {\n await clearFactoryIdentity();\n return;\n }\n if (!sourceSession.factoryProjectId) {\n await clearFactoryIdentity();\n return;\n }\n // Historical thread membership keeps completed work items on Factory billing in hybrid scope.\n const threadId = session.thread.getId();\n const binding = threadId\n ? await workItems.findRunBindingByThread({\n orgId: sourceSession.orgId,\n threadId,\n resourceId,\n sessionId,\n rejectAmbiguous: true,\n })\n : null;\n const project = await projects.getById({ id: binding?.factoryProjectId ?? sourceSession.factoryProjectId });\n if (!project || project.orgId !== sourceSession.orgId) {\n await clearFactoryIdentity();\n return;\n }\n const modelScope = effectiveModelScope(project.modelScope, binding ? 'run' : 'session');\n await session.state.set({\n factoryOrgId: sourceSession.orgId,\n factoryModelScope: modelScope,\n factoryOwnerUserId: sourceSession.userId,\n });\n identityResolved = true;\n await primeTenantCredentialsForTenant({\n orgId: sourceSession.orgId,\n userId: sourceSession.userId,\n credentialScope: modelScope,\n });\n\n if (binding) return;\n if (threadId && (await session.thread.firstUserMessage({ threadId }))) return;\n\n const scopedModelId =\n (modelScope === 'factory'\n ? project.defaultModelId\n : (await modelDefaults.get({ orgId: sourceSession.orgId, userId: sourceSession.userId }))?.modelId) ??\n // No chosen default: a connected provider's default, unless the current model is usable.\n (await resolveTenantProviderDefaultModel(\n { orgId: sourceSession.orgId, userId: sourceSession.userId, credentialScope: modelScope },\n session.model.get() || undefined,\n ).catch(error => {\n console.warn('[Factory default-model hydration] Unable to resolve a provider default model.', error);\n return undefined;\n }));\n if (!scopedModelId) return;\n // A thread the session creates later (the UI binding its conventional\n // thread after a thread-agnostic request opened the session) starts from\n // the session default, not from the thread hydrated here.\n session.model.setDefault({ modelId: scopedModelId });\n await applyDefaultModel(session, scopedModelId);\n } catch (error) {\n if (!identityResolved && !hadFactoryIdentity) {\n try {\n await failClosedWithoutIdentity();\n } catch {}\n }\n console.warn('[Factory default-model hydration] Unable to apply the scoped default model.', error);\n }\n}\n"],"mappings":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,YAAY,UAAU,QAAQ,SAAS;EACtF,MAAM,QAAQ,MAAM,IAAI;GACtB,cAAc,cAAc;GAC5B,mBAAmB;GACnB,oBAAoB,cAAc;EACpC,CAAC;EACD,mBAAmB;EACnB,MAAM,gCAAgC;GACpC,OAAO,cAAc;GACrB,QAAQ,cAAc;GACtB,iBAAiB;EACnB,CAAC;EAED,IAAI,SAAS;EACb,IAAI,YAAa,MAAM,QAAQ,OAAO,iBAAiB,EAAE,SAAS,CAAC,GAAI;EAEvE,MAAM,iBACH,eAAe,YACZ,QAAQ,kBACP,MAAM,cAAc,IAAI;GAAE,OAAO,cAAc;GAAO,QAAQ,cAAc;EAAO,CAAC,EAAA,EAAI,YAE5F,MAAM,kCACL;GAAE,OAAO,cAAc;GAAO,QAAQ,cAAc;GAAQ,iBAAiB;EAAW,GACxF,QAAQ,MAAM,IAAI,KAAK,KAAA,CACzB,CAAC,CAAC,OAAM,UAAS;GACf,QAAQ,KAAK,iFAAiF,KAAK;EAErG,CAAC;EACH,IAAI,CAAC,eAAe;EAIpB,QAAQ,MAAM,WAAW,EAAE,SAAS,cAAc,CAAC;EACnD,MAAM,kBAAkB,SAAS,aAAa;CAChD,SAAS,OAAO;EACd,IAAI,CAAC,oBAAoB,CAAC,oBACxB,IAAI;GACF,MAAM,0BAA0B;EAClC,QAAQ,CAAC;EAEX,QAAQ,KAAK,+EAA+E,KAAK;CACnG;AACF"}
@@ -60,7 +60,7 @@ function escapeText(value) {
60
60
  function sessionIdFromContext(requestContext) {
61
61
  if (!requestContext || typeof requestContext.get !== "function") return null;
62
62
  const controller = requestContext.get("controller");
63
- return typeof controller?.resourceId === "string" && controller.resourceId ? controller.resourceId : null;
63
+ return typeof controller?.sessionId === "string" && controller.sessionId ? controller.sessionId : null;
64
64
  }
65
65
  function environmentCacheKey(state) {
66
66
  return `environment:${createHash("sha256").update(JSON.stringify(state)).digest("hex").slice(0, 16)}`;