@mastra/factory 0.29.0-alpha.5 → 0.29.0-alpha.6

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 (183) hide show
  1. package/README.md +55 -31
  2. package/dist/boards/semantics.d.ts.map +1 -1
  3. package/dist/boards/semantics.js +7 -1
  4. package/dist/boards/semantics.js.map +1 -1
  5. package/dist/factory.d.ts +10 -0
  6. package/dist/factory.d.ts.map +1 -1
  7. package/dist/factory.js +98 -41
  8. package/dist/factory.js.map +1 -1
  9. package/dist/integrations/github/issue-intake.d.ts +15 -0
  10. package/dist/integrations/github/issue-intake.d.ts.map +1 -0
  11. package/dist/integrations/github/issue-intake.js +50 -0
  12. package/dist/integrations/github/issue-intake.js.map +1 -0
  13. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  14. package/dist/integrations/github/issue-reconciler.js +10 -1
  15. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  16. package/dist/integrations/github/rules.d.ts +2 -0
  17. package/dist/integrations/github/rules.d.ts.map +1 -1
  18. package/dist/integrations/github/rules.js +3 -0
  19. package/dist/integrations/github/rules.js.map +1 -1
  20. package/dist/integrations/platform/connect/routes.d.ts +43 -1
  21. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  22. package/dist/integrations/platform/connect/routes.js +82 -7
  23. package/dist/integrations/platform/connect/routes.js.map +1 -1
  24. package/dist/integrations/platform/connect/session-tools.d.ts +12 -0
  25. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -1
  26. package/dist/integrations/platform/connect/session-tools.js +28 -10
  27. package/dist/integrations/platform/connect/session-tools.js.map +1 -1
  28. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
  29. package/dist/integrations/platform/vanta/integration.js +3 -3
  30. package/dist/integrations/platform/vanta/integration.js.map +1 -1
  31. package/dist/integrations/vanta/sync.d.ts +9 -0
  32. package/dist/integrations/vanta/sync.d.ts.map +1 -1
  33. package/dist/integrations/vanta/sync.js +10 -1
  34. package/dist/integrations/vanta/sync.js.map +1 -1
  35. package/dist/routes/board-snapshot.d.ts +5 -5
  36. package/dist/routes/board-snapshot.d.ts.map +1 -1
  37. package/dist/routes/board-snapshot.js +10 -14
  38. package/dist/routes/board-snapshot.js.map +1 -1
  39. package/dist/routes/config.d.ts +11 -2
  40. package/dist/routes/config.d.ts.map +1 -1
  41. package/dist/routes/config.js +242 -75
  42. package/dist/routes/config.js.map +1 -1
  43. package/dist/routes/contracts.d.ts +43 -14
  44. package/dist/routes/contracts.d.ts.map +1 -1
  45. package/dist/routes/contracts.js +27 -17
  46. package/dist/routes/contracts.js.map +1 -1
  47. package/dist/routes/custom-endpoint-url.d.ts +8 -0
  48. package/dist/routes/custom-endpoint-url.d.ts.map +1 -0
  49. package/dist/routes/custom-endpoint-url.js +45 -0
  50. package/dist/routes/custom-endpoint-url.js.map +1 -0
  51. package/dist/routes/custom-provider-source.d.ts +24 -8
  52. package/dist/routes/custom-provider-source.d.ts.map +1 -1
  53. package/dist/routes/custom-provider-source.js +93 -43
  54. package/dist/routes/custom-provider-source.js.map +1 -1
  55. package/dist/routes/intake.d.ts +6 -0
  56. package/dist/routes/intake.d.ts.map +1 -1
  57. package/dist/routes/intake.js +20 -0
  58. package/dist/routes/intake.js.map +1 -1
  59. package/dist/routes/project-sessions.d.ts +15 -3
  60. package/dist/routes/project-sessions.d.ts.map +1 -1
  61. package/dist/routes/project-sessions.js +56 -14
  62. package/dist/routes/project-sessions.js.map +1 -1
  63. package/dist/routes/projects.d.ts +6 -1
  64. package/dist/routes/projects.d.ts.map +1 -1
  65. package/dist/routes/projects.js +19 -3
  66. package/dist/routes/projects.js.map +1 -1
  67. package/dist/routes/provider-credentials.d.ts +10 -1
  68. package/dist/routes/provider-credentials.d.ts.map +1 -1
  69. package/dist/routes/provider-credentials.js +13 -16
  70. package/dist/routes/provider-credentials.js.map +1 -1
  71. package/dist/routes/session-rows.d.ts +1 -1
  72. package/dist/routes/session-rows.d.ts.map +1 -1
  73. package/dist/routes/session-rows.js +38 -42
  74. package/dist/routes/session-rows.js.map +1 -1
  75. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  76. package/dist/routes/source-control-sessions.js +4 -4
  77. package/dist/routes/source-control-sessions.js.map +1 -1
  78. package/dist/routes/surface.d.ts +3 -0
  79. package/dist/routes/surface.d.ts.map +1 -1
  80. package/dist/routes/surface.js +20 -7
  81. package/dist/routes/surface.js.map +1 -1
  82. package/dist/routes/tenant-credentials.d.ts.map +1 -1
  83. package/dist/routes/tenant-credentials.js +4 -4
  84. package/dist/routes/tenant-credentials.js.map +1 -1
  85. package/dist/routes/work-items.d.ts +9 -3
  86. package/dist/routes/work-items.d.ts.map +1 -1
  87. package/dist/routes/work-items.js +39 -16
  88. package/dist/routes/work-items.js.map +1 -1
  89. package/dist/rules/binding-context.d.ts +5 -0
  90. package/dist/rules/binding-context.d.ts.map +1 -1
  91. package/dist/rules/binding-context.js +51 -5
  92. package/dist/rules/binding-context.js.map +1 -1
  93. package/dist/rules/dispatcher.d.ts.map +1 -1
  94. package/dist/rules/dispatcher.js +2 -1
  95. package/dist/rules/dispatcher.js.map +1 -1
  96. package/dist/rules/start-coordinator.d.ts.map +1 -1
  97. package/dist/rules/start-coordinator.js +2 -7
  98. package/dist/rules/start-coordinator.js.map +1 -1
  99. package/dist/sandbox/session-retirement.d.ts +6 -0
  100. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  101. package/dist/sandbox/session-retirement.js +17 -0
  102. package/dist/sandbox/session-retirement.js.map +1 -1
  103. package/dist/session/factory-session.d.ts.map +1 -1
  104. package/dist/session/factory-session.js +2 -1
  105. package/dist/session/factory-session.js.map +1 -1
  106. package/dist/session/live-sessions.d.ts +6 -1
  107. package/dist/session/live-sessions.d.ts.map +1 -1
  108. package/dist/session/live-sessions.js +4 -0
  109. package/dist/session/live-sessions.js.map +1 -1
  110. package/dist/session/run-audit.d.ts +1 -1
  111. package/dist/session/run-audit.d.ts.map +1 -1
  112. package/dist/session/run-audit.js.map +1 -1
  113. package/dist/session/session-row-status.d.ts +3 -3
  114. package/dist/session/session-row-status.js +4 -4
  115. package/dist/session/session-row-status.js.map +1 -1
  116. package/dist/session/session-row-view.d.ts +3 -4
  117. package/dist/session/session-row-view.d.ts.map +1 -1
  118. package/dist/session/session-row-view.js +14 -21
  119. package/dist/session/session-row-view.js.map +1 -1
  120. package/dist/session/session-rows.d.ts +22 -8
  121. package/dist/session/session-rows.d.ts.map +1 -1
  122. package/dist/session/session-rows.js +158 -83
  123. package/dist/session/session-rows.js.map +1 -1
  124. package/dist/session/session-unloader.d.ts +101 -0
  125. package/dist/session/session-unloader.d.ts.map +1 -0
  126. package/dist/session/session-unloader.js +278 -0
  127. package/dist/session/session-unloader.js.map +1 -0
  128. package/dist/session/work-item-repository.d.ts +5 -1
  129. package/dist/session/work-item-repository.d.ts.map +1 -1
  130. package/dist/session/work-item-repository.js +39 -15
  131. package/dist/session/work-item-repository.js.map +1 -1
  132. package/dist/session-list-changes.d.ts +9 -0
  133. package/dist/session-list-changes.d.ts.map +1 -0
  134. package/dist/session-list-changes.js +54 -0
  135. package/dist/session-list-changes.js.map +1 -0
  136. package/dist/storage/announced-lists.d.ts +14 -0
  137. package/dist/storage/announced-lists.d.ts.map +1 -0
  138. package/dist/storage/announced-lists.js +78 -0
  139. package/dist/storage/announced-lists.js.map +1 -0
  140. package/dist/storage/domains/boards/base.d.ts +1 -1
  141. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  142. package/dist/storage/domains/boards/base.js +27 -9
  143. package/dist/storage/domains/boards/base.js.map +1 -1
  144. package/dist/storage/domains/custom-providers/base.d.ts +62 -19
  145. package/dist/storage/domains/custom-providers/base.d.ts.map +1 -1
  146. package/dist/storage/domains/custom-providers/base.js +131 -100
  147. package/dist/storage/domains/custom-providers/base.js.map +1 -1
  148. package/dist/storage/domains/intake/base.d.ts +25 -7
  149. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  150. package/dist/storage/domains/intake/base.js +83 -19
  151. package/dist/storage/domains/intake/base.js.map +1 -1
  152. package/dist/storage/domains/source-control/base.d.ts +8 -0
  153. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  154. package/dist/storage/domains/source-control/base.js +110 -64
  155. package/dist/storage/domains/source-control/base.js.map +1 -1
  156. package/dist/storage/domains/source-control/inmemory.d.ts +4 -0
  157. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  158. package/dist/storage/domains/source-control/inmemory.js +8 -5
  159. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  160. package/dist/storage/domains/work-items/base.d.ts +9 -1
  161. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  162. package/dist/storage/domains/work-items/base.js +43 -11
  163. package/dist/storage/domains/work-items/base.js.map +1 -1
  164. package/dist/tools/read-tools.d.ts +9 -2
  165. package/dist/tools/read-tools.d.ts.map +1 -1
  166. package/dist/tools/read-tools.js +57 -12
  167. package/dist/tools/read-tools.js.map +1 -1
  168. package/dist/tools/session-tools.d.ts +0 -13
  169. package/dist/tools/session-tools.d.ts.map +1 -1
  170. package/dist/tools/session-tools.js +127 -336
  171. package/dist/tools/session-tools.js.map +1 -1
  172. package/dist/tools/work-item-tools.d.ts.map +1 -1
  173. package/dist/tools/work-item-tools.js +91 -23
  174. package/dist/tools/work-item-tools.js.map +1 -1
  175. package/dist/work-items/card-reference.d.ts +21 -0
  176. package/dist/work-items/card-reference.d.ts.map +1 -0
  177. package/dist/work-items/card-reference.js +58 -0
  178. package/dist/work-items/card-reference.js.map +1 -0
  179. package/package.json +8 -8
  180. package/dist/storage/probed-list.d.ts +0 -11
  181. package/dist/storage/probed-list.d.ts.map +0 -1
  182. package/dist/storage/probed-list.js +0 -52
  183. package/dist/storage/probed-list.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"start-coordinator.d.ts","sourceRoot":"","sources":["../../src/rules/start-coordinator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,y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AAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,SAAS,GAAG,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,QAAQ,CAAC;IAClE,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,KAAK,iBAAiB,GAAG,eAAe,CAAC,eAAe,CAAC,CAAC;AA0C1D,qBAAa,uBAAuB;;IAclC,YACE,UAAU,EAAE,iBAAiB,EAC7B,OAAO,EAAE,gBAAgB,EACzB,iBAAiB,CAAC,EAAE,IAAI,CAAC,wBAAwB,EAAE,YAAY,CAAC,EAChE,aAAa,CAAC,EACV,0BAA0B,GAC1B,CAAC,CACC,OAAO,EAAE,mBAAmB,KACzB,0BAA0B,GAAG,SAAS,GAAG,OAAO,CAAC,0BAA0B,GAAG,SAAS,CAAC,CAAC,EAClG,MAAM,CAAC,EAAE,aAAa,EACtB,YAAY,CAAC,EAAE;QAAE,QAAQ,EAAE,sBAAsB,CAAC;QAAC,aAAa,EAAE,oBAAoB,CAAA;KAAE;IACxF,uIAAuI;IACvI,MAAM,CAAC,EAAE,aAAa,GAAG,kBAAkB,EAU5C;IAEK,OAAO,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,0BAA0B,CAAC,CA8M/E;CACF"}
@@ -4,7 +4,7 @@ import { boardForWorkItem, hasPullRequest, isPullRequestReviewPhase } from "../b
4
4
  import { toBoardSource } from "../boards/project-boards.js";
5
5
  import { primeTenantCredentialsForTenant } from "../routes/tenant-credentials.js";
6
6
  import { hydrateFactorySession, resolveFactorySessionModel } from "../session/factory-session.js";
7
- import { isRunRepositoryInstruction, repositoryChosenByRun, resolveRunRepository, runRepositoryInstruction } from "../session/work-item-repository.js";
7
+ import { isRunRepositoryInstruction, repositoryChosenByRun, resolveRunRepositoryFromIntake, runRepositoryInstruction } from "../session/work-item-repository.js";
8
8
  import { isFactoryPrincipalId } from "../storage/domains/projects/base.js";
9
9
  import { externallyAuthoredWorkItem } from "./types.js";
10
10
  import { RequestContext } from "@mastra/core/request-context";
@@ -131,20 +131,15 @@ var FactoryStartCoordinator = class {
131
131
  orgId: request.orgId,
132
132
  id: request.workItem.id
133
133
  }) : null;
134
- const intakeConfig = await this.#intake?.getConfig({
135
- orgId: request.orgId,
136
- integrationIds: ["linear"]
137
- });
138
134
  const runItem = storedItem ?? {
139
135
  metadata: request.workItem.input.metadata ?? null,
140
136
  workItem: { metadata: request.workItem.input.metadata ?? null }
141
137
  };
142
- const repository = await resolveRunRepository({
138
+ const repository = await resolveRunRepositoryFromIntake(this.#intake, {
143
139
  sourceControl,
144
140
  orgId: request.orgId,
145
141
  factoryProjectId: request.factoryProjectId,
146
142
  item: runItem,
147
- linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject,
148
143
  boundProjectRepositoryId: sourceSession.projectRepositoryId
149
144
  });
150
145
  if (repository.status === "unlinked") throw new WorkItemRepositoryError("repository_unlinked", repository.hint);
@@ -1 +1 @@
1
- {"version":3,"file":"start-coordinator.js","names":[],"sources":["../../src/rules/start-coordinator.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\n\nimport { boardForWorkItem, hasPullRequest, isPullRequestReviewPhase, REVIEW_CONTEXT } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { primeTenantCredentialsForTenant } from '../routes/tenant-credentials.js';\nimport { hydrateFactorySession, resolveFactorySessionModel } from '../session/factory-session.js';\nimport {\n isRunRepositoryInstruction,\n repositoryChosenByRun,\n resolveRunRepository,\n runRepositoryInstruction,\n} from '../session/work-item-repository.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { isFactoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { EffectiveModelScope, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlSession, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { CreateWorkItemInput, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { externallyAuthoredWorkItem } from './types.js';\nimport type { FactoryRuleActor, FactoryRuleStage, FactoryTransitionResult } from './types.js';\n\nexport interface FactoryStartRequest {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n /**\n * Who started the work, where that is not the session's owner: the Factory owns the\n * sessions it runs, and the move a start makes is still the mover's.\n */\n startedBy?: FactoryRuleActor;\n sessionId: string;\n expectedBindingId?: string;\n threadTitle: string;\n kickoffKey: string;\n /** Where the arrival path lands the card; a session opened on an existing card names none. */\n destinationStage?: FactoryRuleStage;\n /** The run's effective scope; a hybrid Factory's runs use the Factory's model and credentials. */\n modelScope: EffectiveModelScope;\n defaultModelId?: string;\n workItem: {\n id?: string;\n role: string;\n input: CreateWorkItemInput;\n };\n requestContext?: RequestContext;\n}\n\nexport class UntrustedSharedSessionError extends Error {\n constructor(readonly sessionId: string) {\n super(\n `Session ${sessionId} already shares memory with this Factory, so it cannot run untrusted content. Start the run in a new session.`,\n );\n this.name = 'UntrustedSharedSessionError';\n }\n}\n\n/**\n * The memory resource a run works on. Trusted runs share the Factory's resource.\n * A run that reads attacker-controllable content (a pull request checkout, or a\n * card written outside the write-access circle) keeps its own resource, so it can\n * neither plant observations that trusted runs read nor read what they observed.\n * A session that was isolated stays isolated; one already sharing memory refuses\n * untrusted work instead of carrying that memory into it.\n */\nasync function runMemoryResource(\n controller: Pick<FactoryController, 'queryThreadById'>,\n input: { sessionId: string; factoryProjectId: string; untrusted: boolean },\n): Promise<string> {\n const existing = await controller.queryThreadById({ threadId: input.sessionId });\n if (existing?.resourceId === input.sessionId) return input.sessionId;\n if (!input.untrusted) return existing?.resourceId ?? input.factoryProjectId;\n if (existing) throw new UntrustedSharedSessionError(input.sessionId);\n return input.sessionId;\n}\n\nexport class WorkItemRepositoryError extends Error {\n constructor(\n readonly code: 'repository_mismatch' | 'repository_unlinked',\n message: string,\n ) {\n super(message);\n this.name = 'WorkItemRepositoryError';\n }\n}\n\nexport class FactoryStartTransitionError extends Error {\n readonly result: Extract<FactoryTransitionResult, { status: 'rejected' }>;\n\n constructor(result: Extract<FactoryTransitionResult, { status: 'rejected' }>) {\n super(result.reason);\n this.name = 'FactoryStartTransitionError';\n this.result = result;\n }\n}\n\nexport interface FactoryStartPreparedResult {\n workItemId: string;\n bindingId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n branch: string;\n revision: number;\n kickoffStatus: 'pending' | 'leased' | 'retry' | 'sent' | 'failed';\n replayed: boolean;\n}\n\ntype FactoryController = AgentController<MastraCodeState>;\ntype FactorySession = Awaited<ReturnType<FactoryController['createSession']>>;\n\nasync function resolveSourceSession(\n storage: SourceControlStorageHandle,\n request: FactoryStartRequest,\n): Promise<SourceControlSession & { projectRepositoryId: string }> {\n const session = await storage.sessions.getBySessionId(request.sessionId);\n if (!session || session.orgId !== request.orgId || session.userId !== request.userId) {\n throw new Error('Factory session not found');\n }\n const projectRepositoryId = session.projectRepositoryId;\n if (!projectRepositoryId) throw new Error('Factory session repository not found');\n const projectRepository = await storage.projectRepositories.get({ orgId: request.orgId, id: projectRepositoryId });\n if (!projectRepository) throw new Error('Factory session repository not found');\n const connection = await storage.connections.get({ orgId: request.orgId, id: projectRepository.connectionId });\n if (!connection || connection.factoryProjectId !== request.factoryProjectId) {\n throw new Error('Factory session does not belong to this project');\n }\n return { ...session, projectRepositoryId };\n}\n\nasync function sessionRepositorySlug(\n storage: SourceControlStorageHandle,\n orgId: string,\n projectRepositoryId: string,\n): Promise<string> {\n const link = await storage.projectRepositories.get({ orgId, id: projectRepositoryId });\n const repository = link && (await storage.repositories.get({ orgId, id: link.repositoryId }));\n if (!repository) throw new Error('Factory session repository not found');\n return repository.slug;\n}\n\nasync function configureThread(session: FactorySession, request: FactoryStartRequest): Promise<string> {\n const threadId = session.thread.requireId();\n // Derived from the work item, not a user rename, so leave the title\n // unpinned and let auto-naming keep refining it.\n await session.thread.rename({ title: request.threadTitle, pin: false });\n await session.thread.setSetting({ key: 'factorySessionId', value: request.sessionId });\n return threadId;\n}\n\nexport class FactoryStartCoordinator {\n readonly #controller: FactoryController;\n readonly #storage: WorkItemsStorage;\n readonly #transitionService?: Pick<FactoryTransitionService, 'transition'>;\n readonly #sourceControl?:\n | SourceControlStorageHandle\n | ((\n request: FactoryStartRequest,\n ) => SourceControlStorageHandle | undefined | Promise<SourceControlStorageHandle | undefined>);\n readonly #intake?: IntakeStorage;\n readonly #projects?: FactoryProjectsStorage;\n readonly #modelDefaults?: ModelDefaultsStorage;\n readonly #boards?: ProjectBoardSource;\n\n constructor(\n controller: FactoryController,\n storage: WorkItemsStorage,\n transitionService?: Pick<FactoryTransitionService, 'transition'>,\n sourceControl?:\n | SourceControlStorageHandle\n | ((\n request: FactoryStartRequest,\n ) => SourceControlStorageHandle | undefined | Promise<SourceControlStorageHandle | undefined>),\n intake?: IntakeStorage,\n sessionModel?: { projects: FactoryProjectsStorage; modelDefaults: ModelDefaultsStorage },\n /** Tells a pull request review run from the card's other review runs; without it every review run with a pull request is untrusted. */\n boards?: BoardRegistry | ProjectBoardSource,\n ) {\n this.#controller = controller;\n this.#storage = storage;\n this.#transitionService = transitionService;\n this.#sourceControl = sourceControl;\n this.#intake = intake;\n this.#projects = sessionModel?.projects;\n this.#modelDefaults = sessionModel?.modelDefaults;\n this.#boards = boards ? toBoardSource(boards) : undefined;\n }\n\n async prepare(request: FactoryStartRequest): Promise<FactoryStartPreparedResult> {\n const storage = this.#storage;\n const sourceControl =\n typeof this.#sourceControl === 'function' ? await this.#sourceControl(request) : this.#sourceControl;\n if (!sourceControl) throw new Error('Factory source control storage is unavailable');\n const sourceSession = await resolveSourceSession(sourceControl, request);\n const sessionModel =\n this.#projects && this.#modelDefaults\n ? await resolveFactorySessionModel({\n projects: this.#projects,\n modelDefaults: this.#modelDefaults,\n factoryProjectId: request.factoryProjectId,\n orgId: request.orgId,\n ownerUserId: sourceSession.userId,\n context: 'run',\n })\n : { modelScope: request.modelScope, modelId: request.defaultModelId };\n const storedItem = request.workItem.id\n ? await storage.get({ orgId: request.orgId, id: request.workItem.id })\n : null;\n const intakeConfig = await this.#intake?.getConfig({ orgId: request.orgId, integrationIds: ['linear'] });\n const runItem = storedItem ?? {\n metadata: request.workItem.input.metadata ?? null,\n workItem: { metadata: request.workItem.input.metadata ?? null },\n };\n // A card that names no repository runs in the session's own repository,\n // and its agent determines from the card which repository to work in.\n const repository = await resolveRunRepository({\n sourceControl,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n item: runItem,\n linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject,\n boundProjectRepositoryId: sourceSession.projectRepositoryId,\n });\n if (repository.status === 'unlinked') {\n throw new WorkItemRepositoryError('repository_unlinked', repository.hint);\n }\n if (\n repository.projectRepositoryId !== sourceSession.projectRepositoryId &&\n !repositoryChosenByRun(runItem, repository.slug)\n ) {\n throw new WorkItemRepositoryError(\n 'repository_mismatch',\n `This run session is bound to a different repository than ${repository.slug}.`,\n );\n }\n const ownSlug =\n repository.projectRepositoryId === sourceSession.projectRepositoryId\n ? repository.slug\n : await sessionRepositorySlug(sourceControl, request.orgId, sourceSession.projectRepositoryId);\n const requestContext = request.requestContext ?? new RequestContext();\n // Preserve an authenticated caller when present. Autonomous starts still\n // need a principal so deployed credential resolution can authenticate the\n // request before selecting the stamped session owner's exclusive scope.\n const existingUser = requestContext.get('user');\n if (!existingUser || typeof existingUser !== 'object') {\n requestContext.set('user', {\n workosId: request.userId,\n organizationId: request.orgId,\n });\n }\n // Sessions kicked off against third-party content (a PR under review, or\n // any pull-request-sourced work item) get `untrustedCheckout` so the SDK\n // never ingests the checkout's AGENTS.md/CLAUDE.md into the system prompt\n // or reminders — those files are attacker-writable in a PR branch.\n // An issue card's PR review checks out the attached pull request's head, so it counts too.\n // The run's stage is where the card is going: a card started from its resting phase into\n // its board's pull request review is moved only after the session is ready.\n const runStage = request.destinationStage ?? storedItem?.stages[0];\n const reviewsAttachedPullRequest =\n request.workItem.role === REVIEW_CONTEXT &&\n storedItem != null &&\n hasPullRequest({ workItem: storedItem.workItem }) &&\n (!this.#boards ||\n isPullRequestReviewPhase((await this.#boards.load(request)).get(boardForWorkItem(storedItem)), runStage));\n const untrustedCheckout =\n request.workItem.input.externalSource?.type === 'pull-request' || reviewsAttachedPullRequest;\n // The trusted ref the SDK may serve project instruction files from on an\n // untrusted checkout (the PR's base branch). Prefer the session record's\n // base branch; fall back to the intake metadata captured from the PR.\n const metadataBaseBranch = storedItem\n ? storedItem.workItem.metadata?.baseBranch\n : request.workItem.input.metadata?.baseBranch;\n const baseRef =\n (sourceSession.baseBranch || undefined) ??\n (typeof metadataBaseBranch === 'string' && metadataBaseBranch ? metadataBaseBranch : undefined);\n const memoryResourceId = await runMemoryResource(this.#controller, {\n sessionId: sourceSession.sessionId,\n factoryProjectId: request.factoryProjectId,\n untrusted:\n untrustedCheckout ||\n externallyAuthoredWorkItem(\n storedItem ?? {\n externalSource: request.workItem.input.externalSource ?? null,\n metadata: request.workItem.input.metadata ?? null,\n },\n ),\n });\n const sessionTags = {\n factoryProjectId: request.factoryProjectId,\n projectRepositoryId: sourceSession.projectRepositoryId,\n };\n // The run is addressed by its session id; its threads and memory belong to\n // the Factory, so concurrent runs share one memory resource.\n const session = await this.#controller.createSession({\n id: sourceSession.sessionId,\n ownerId: request.userId,\n resourceId: memoryResourceId,\n threadId: sourceSession.sessionId,\n requestContext,\n tags: sessionTags,\n });\n // Bound-agent authority gates (the transition tool, the factory-phase\n // processor, workspace token selection) resolve the session address from\n // controller state. Seed it server-side — `tags` covers fresh creation,\n // the explicit setState covers get-or-create returning a session another\n // caller created without them — so autonomous runs never depend on a\n // browser connecting to populate the state. `untrustedCheckout` is a\n // boolean so it rides only on state (tags are string-valued).\n const targetRepositoryInstruction = runRepositoryInstruction(repository, ownSlug);\n const existingPluginInstructions = session.state.get()?.pluginInstructions ?? [];\n await session.state.set({\n ...sessionTags,\n // The authoritative org id for every downstream identity read (the\n // memory seam's organizationId): the session owner is a USER id, not an\n // org, so it must never be improvised from ownerId.\n factoryOrgId: request.orgId,\n factoryModelScope: sessionModel.modelScope,\n factoryOwnerUserId: sourceSession.userId,\n pluginInstructions: [\n ...existingPluginInstructions.filter(instruction => !isRunRepositoryInstruction(instruction)),\n targetRepositoryInstruction,\n ],\n ...(untrustedCheckout ? { untrustedCheckout: true, ...(baseRef ? { baseRef } : {}) } : {}),\n });\n await primeTenantCredentialsForTenant({\n orgId: request.orgId,\n userId: sourceSession.userId,\n credentialScope: sessionModel.modelScope,\n });\n // Apply the factory's main model before any model-dependent run work.\n // Observational-memory settings are loaded per invocation by the input processor.\n await hydrateFactorySession(session, {\n orgId: request.orgId,\n modelScope: sessionModel.modelScope,\n ownerUserId: sourceSession.userId,\n defaultModelId: sessionModel.modelId,\n });\n // The tool is `requireApproval`, and that prompt parks the run whether or not\n // someone pressed Start — a person is reading the plan, not an approval queue.\n // Starting the run was already the say-so; the rules engine still governs.\n await session.permissions.setForTool({ toolName: 'factory_transition_work_item', policy: 'allow' });\n const threadId = await configureThread(session, request);\n const prepared = await storage.prepareRunStart({\n orgId: request.orgId,\n userId: request.userId,\n factoryProjectId: request.factoryProjectId,\n workItem: { id: request.workItem.id, input: request.workItem.input },\n role: request.workItem.role,\n expectedBindingId: request.expectedBindingId,\n session: { sessionId: sourceSession.sessionId, branch: sourceSession.branch, threadId },\n resourceId: memoryResourceId,\n kickoffKey: request.kickoffKey,\n kickoffMessage: null,\n });\n await session.thread.setSetting({ key: 'factoryWorkItemId', value: prepared.item.id });\n\n let revision = prepared.item.revision;\n const destinationStage = request.destinationStage;\n if (destinationStage && (prepared.item.stages.length !== 1 || prepared.item.stages[0] !== destinationStage)) {\n if (!this.#transitionService) throw new Error('Factory transition service is unavailable.');\n const transition = await this.#transitionService.transition({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: prepared.item.id,\n board: boardForWorkItem(prepared.item),\n stage: destinationStage,\n expectedRevision: prepared.item.revision,\n actor:\n request.startedBy ??\n (isFactoryPrincipalId(request.userId)\n ? { type: 'system', id: request.userId }\n : { type: 'human', id: request.userId }),\n ingress: { type: 'human', identity: `start:${request.kickoffKey}:transition` },\n cause: 'run_start',\n });\n if (transition.status === 'rejected') {\n await storage.markPendingStart(prepared.binding.id, 'failed');\n throw new FactoryStartTransitionError(transition);\n }\n revision = transition.revision;\n }\n\n await storage.markPendingStart(prepared.binding.id, 'sent');\n prepared.pendingStart.status = 'sent';\n\n return {\n workItemId: prepared.item.id,\n bindingId: prepared.binding.id,\n threadId,\n resourceId: memoryResourceId,\n sessionId: sourceSession.sessionId,\n branch: sourceSession.branch,\n revision,\n kickoffStatus: prepared.pendingStart.status,\n replayed: prepared.replayed,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AAoDA,IAAa,8BAAb,cAAiD,MAAM;CAChC;CAArB,YAAY,WAA4B;EACtC,MACE,WAAW,UAAU,8GACvB;EAHmB,KAAA,YAAA;EAInB,KAAK,OAAO;CACd;AACF;;;;;;;;;AAUA,eAAe,kBACb,YACA,OACiB;CACjB,MAAM,WAAW,MAAM,WAAW,gBAAgB,EAAE,UAAU,MAAM,UAAU,CAAC;CAC/E,IAAI,UAAU,eAAe,MAAM,WAAW,OAAO,MAAM;CAC3D,IAAI,CAAC,MAAM,WAAW,OAAO,UAAU,cAAc,MAAM;CAC3D,IAAI,UAAU,MAAM,IAAI,4BAA4B,MAAM,SAAS;CACnE,OAAO,MAAM;AACf;AAEA,IAAa,0BAAb,cAA6C,MAAM;CAEtC;CADX,YACE,MACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,OAAA;EAIT,KAAK,OAAO;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.js","names":[],"sources":["../../src/rules/start-coordinator.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\n\nimport { boardForWorkItem, hasPullRequest, isPullRequestReviewPhase, REVIEW_CONTEXT } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { primeTenantCredentialsForTenant } from '../routes/tenant-credentials.js';\nimport { hydrateFactorySession, resolveFactorySessionModel } from '../session/factory-session.js';\nimport {\n isRunRepositoryInstruction,\n repositoryChosenByRun,\n resolveRunRepositoryFromIntake,\n runRepositoryInstruction,\n} from '../session/work-item-repository.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { isFactoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { EffectiveModelScope, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlSession, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { CreateWorkItemInput, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { externallyAuthoredWorkItem } from './types.js';\nimport type { FactoryRuleActor, FactoryRuleStage, FactoryTransitionResult } from './types.js';\n\nexport interface FactoryStartRequest {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n /**\n * Who started the work, where that is not the session's owner: the Factory owns the\n * sessions it runs, and the move a start makes is still the mover's.\n */\n startedBy?: FactoryRuleActor;\n sessionId: string;\n expectedBindingId?: string;\n threadTitle: string;\n kickoffKey: string;\n /** Where the arrival path lands the card; a session opened on an existing card names none. */\n destinationStage?: FactoryRuleStage;\n /** The run's effective scope; a hybrid Factory's runs use the Factory's model and credentials. */\n modelScope: EffectiveModelScope;\n defaultModelId?: string;\n workItem: {\n id?: string;\n role: string;\n input: CreateWorkItemInput;\n };\n requestContext?: RequestContext;\n}\n\nexport class UntrustedSharedSessionError extends Error {\n constructor(readonly sessionId: string) {\n super(\n `Session ${sessionId} already shares memory with this Factory, so it cannot run untrusted content. Start the run in a new session.`,\n );\n this.name = 'UntrustedSharedSessionError';\n }\n}\n\n/**\n * The memory resource a run works on. Trusted runs share the Factory's resource.\n * A run that reads attacker-controllable content (a pull request checkout, or a\n * card written outside the write-access circle) keeps its own resource, so it can\n * neither plant observations that trusted runs read nor read what they observed.\n * A session that was isolated stays isolated; one already sharing memory refuses\n * untrusted work instead of carrying that memory into it.\n */\nasync function runMemoryResource(\n controller: Pick<FactoryController, 'queryThreadById'>,\n input: { sessionId: string; factoryProjectId: string; untrusted: boolean },\n): Promise<string> {\n const existing = await controller.queryThreadById({ threadId: input.sessionId });\n if (existing?.resourceId === input.sessionId) return input.sessionId;\n if (!input.untrusted) return existing?.resourceId ?? input.factoryProjectId;\n if (existing) throw new UntrustedSharedSessionError(input.sessionId);\n return input.sessionId;\n}\n\nexport class WorkItemRepositoryError extends Error {\n constructor(\n readonly code: 'repository_mismatch' | 'repository_unlinked',\n message: string,\n ) {\n super(message);\n this.name = 'WorkItemRepositoryError';\n }\n}\n\nexport class FactoryStartTransitionError extends Error {\n readonly result: Extract<FactoryTransitionResult, { status: 'rejected' }>;\n\n constructor(result: Extract<FactoryTransitionResult, { status: 'rejected' }>) {\n super(result.reason);\n this.name = 'FactoryStartTransitionError';\n this.result = result;\n }\n}\n\nexport interface FactoryStartPreparedResult {\n workItemId: string;\n bindingId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n branch: string;\n revision: number;\n kickoffStatus: 'pending' | 'leased' | 'retry' | 'sent' | 'failed';\n replayed: boolean;\n}\n\ntype FactoryController = AgentController<MastraCodeState>;\ntype FactorySession = Awaited<ReturnType<FactoryController['createSession']>>;\n\nasync function resolveSourceSession(\n storage: SourceControlStorageHandle,\n request: FactoryStartRequest,\n): Promise<SourceControlSession & { projectRepositoryId: string }> {\n const session = await storage.sessions.getBySessionId(request.sessionId);\n if (!session || session.orgId !== request.orgId || session.userId !== request.userId) {\n throw new Error('Factory session not found');\n }\n const projectRepositoryId = session.projectRepositoryId;\n if (!projectRepositoryId) throw new Error('Factory session repository not found');\n const projectRepository = await storage.projectRepositories.get({ orgId: request.orgId, id: projectRepositoryId });\n if (!projectRepository) throw new Error('Factory session repository not found');\n const connection = await storage.connections.get({ orgId: request.orgId, id: projectRepository.connectionId });\n if (!connection || connection.factoryProjectId !== request.factoryProjectId) {\n throw new Error('Factory session does not belong to this project');\n }\n return { ...session, projectRepositoryId };\n}\n\nasync function sessionRepositorySlug(\n storage: SourceControlStorageHandle,\n orgId: string,\n projectRepositoryId: string,\n): Promise<string> {\n const link = await storage.projectRepositories.get({ orgId, id: projectRepositoryId });\n const repository = link && (await storage.repositories.get({ orgId, id: link.repositoryId }));\n if (!repository) throw new Error('Factory session repository not found');\n return repository.slug;\n}\n\nasync function configureThread(session: FactorySession, request: FactoryStartRequest): Promise<string> {\n const threadId = session.thread.requireId();\n // Derived from the work item, not a user rename, so leave the title\n // unpinned and let auto-naming keep refining it.\n await session.thread.rename({ title: request.threadTitle, pin: false });\n await session.thread.setSetting({ key: 'factorySessionId', value: request.sessionId });\n return threadId;\n}\n\nexport class FactoryStartCoordinator {\n readonly #controller: FactoryController;\n readonly #storage: WorkItemsStorage;\n readonly #transitionService?: Pick<FactoryTransitionService, 'transition'>;\n readonly #sourceControl?:\n | SourceControlStorageHandle\n | ((\n request: FactoryStartRequest,\n ) => SourceControlStorageHandle | undefined | Promise<SourceControlStorageHandle | undefined>);\n readonly #intake?: IntakeStorage;\n readonly #projects?: FactoryProjectsStorage;\n readonly #modelDefaults?: ModelDefaultsStorage;\n readonly #boards?: ProjectBoardSource;\n\n constructor(\n controller: FactoryController,\n storage: WorkItemsStorage,\n transitionService?: Pick<FactoryTransitionService, 'transition'>,\n sourceControl?:\n | SourceControlStorageHandle\n | ((\n request: FactoryStartRequest,\n ) => SourceControlStorageHandle | undefined | Promise<SourceControlStorageHandle | undefined>),\n intake?: IntakeStorage,\n sessionModel?: { projects: FactoryProjectsStorage; modelDefaults: ModelDefaultsStorage },\n /** Tells a pull request review run from the card's other review runs; without it every review run with a pull request is untrusted. */\n boards?: BoardRegistry | ProjectBoardSource,\n ) {\n this.#controller = controller;\n this.#storage = storage;\n this.#transitionService = transitionService;\n this.#sourceControl = sourceControl;\n this.#intake = intake;\n this.#projects = sessionModel?.projects;\n this.#modelDefaults = sessionModel?.modelDefaults;\n this.#boards = boards ? toBoardSource(boards) : undefined;\n }\n\n async prepare(request: FactoryStartRequest): Promise<FactoryStartPreparedResult> {\n const storage = this.#storage;\n const sourceControl =\n typeof this.#sourceControl === 'function' ? await this.#sourceControl(request) : this.#sourceControl;\n if (!sourceControl) throw new Error('Factory source control storage is unavailable');\n const sourceSession = await resolveSourceSession(sourceControl, request);\n const sessionModel =\n this.#projects && this.#modelDefaults\n ? await resolveFactorySessionModel({\n projects: this.#projects,\n modelDefaults: this.#modelDefaults,\n factoryProjectId: request.factoryProjectId,\n orgId: request.orgId,\n ownerUserId: sourceSession.userId,\n context: 'run',\n })\n : { modelScope: request.modelScope, modelId: request.defaultModelId };\n const storedItem = request.workItem.id\n ? await storage.get({ orgId: request.orgId, id: request.workItem.id })\n : null;\n const runItem = storedItem ?? {\n metadata: request.workItem.input.metadata ?? null,\n workItem: { metadata: request.workItem.input.metadata ?? null },\n };\n // A card that names no repository runs in the session's own repository,\n // and its agent determines from the card which repository to work in.\n const repository = await resolveRunRepositoryFromIntake(this.#intake, {\n sourceControl,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n item: runItem,\n boundProjectRepositoryId: sourceSession.projectRepositoryId,\n });\n if (repository.status === 'unlinked') {\n throw new WorkItemRepositoryError('repository_unlinked', repository.hint);\n }\n if (\n repository.projectRepositoryId !== sourceSession.projectRepositoryId &&\n !repositoryChosenByRun(runItem, repository.slug)\n ) {\n throw new WorkItemRepositoryError(\n 'repository_mismatch',\n `This run session is bound to a different repository than ${repository.slug}.`,\n );\n }\n const ownSlug =\n repository.projectRepositoryId === sourceSession.projectRepositoryId\n ? repository.slug\n : await sessionRepositorySlug(sourceControl, request.orgId, sourceSession.projectRepositoryId);\n const requestContext = request.requestContext ?? new RequestContext();\n // Preserve an authenticated caller when present. Autonomous starts still\n // need a principal so deployed credential resolution can authenticate the\n // request before selecting the stamped session owner's exclusive scope.\n const existingUser = requestContext.get('user');\n if (!existingUser || typeof existingUser !== 'object') {\n requestContext.set('user', {\n workosId: request.userId,\n organizationId: request.orgId,\n });\n }\n // Sessions kicked off against third-party content (a PR under review, or\n // any pull-request-sourced work item) get `untrustedCheckout` so the SDK\n // never ingests the checkout's AGENTS.md/CLAUDE.md into the system prompt\n // or reminders — those files are attacker-writable in a PR branch.\n // An issue card's PR review checks out the attached pull request's head, so it counts too.\n // The run's stage is where the card is going: a card started from its resting phase into\n // its board's pull request review is moved only after the session is ready.\n const runStage = request.destinationStage ?? storedItem?.stages[0];\n const reviewsAttachedPullRequest =\n request.workItem.role === REVIEW_CONTEXT &&\n storedItem != null &&\n hasPullRequest({ workItem: storedItem.workItem }) &&\n (!this.#boards ||\n isPullRequestReviewPhase((await this.#boards.load(request)).get(boardForWorkItem(storedItem)), runStage));\n const untrustedCheckout =\n request.workItem.input.externalSource?.type === 'pull-request' || reviewsAttachedPullRequest;\n // The trusted ref the SDK may serve project instruction files from on an\n // untrusted checkout (the PR's base branch). Prefer the session record's\n // base branch; fall back to the intake metadata captured from the PR.\n const metadataBaseBranch = storedItem\n ? storedItem.workItem.metadata?.baseBranch\n : request.workItem.input.metadata?.baseBranch;\n const baseRef =\n (sourceSession.baseBranch || undefined) ??\n (typeof metadataBaseBranch === 'string' && metadataBaseBranch ? metadataBaseBranch : undefined);\n const memoryResourceId = await runMemoryResource(this.#controller, {\n sessionId: sourceSession.sessionId,\n factoryProjectId: request.factoryProjectId,\n untrusted:\n untrustedCheckout ||\n externallyAuthoredWorkItem(\n storedItem ?? {\n externalSource: request.workItem.input.externalSource ?? null,\n metadata: request.workItem.input.metadata ?? null,\n },\n ),\n });\n const sessionTags = {\n factoryProjectId: request.factoryProjectId,\n projectRepositoryId: sourceSession.projectRepositoryId,\n };\n // The run is addressed by its session id; its threads and memory belong to\n // the Factory, so concurrent runs share one memory resource.\n const session = await this.#controller.createSession({\n id: sourceSession.sessionId,\n ownerId: request.userId,\n resourceId: memoryResourceId,\n threadId: sourceSession.sessionId,\n requestContext,\n tags: sessionTags,\n });\n // Bound-agent authority gates (the transition tool, the factory-phase\n // processor, workspace token selection) resolve the session address from\n // controller state. Seed it server-side — `tags` covers fresh creation,\n // the explicit setState covers get-or-create returning a session another\n // caller created without them — so autonomous runs never depend on a\n // browser connecting to populate the state. `untrustedCheckout` is a\n // boolean so it rides only on state (tags are string-valued).\n const targetRepositoryInstruction = runRepositoryInstruction(repository, ownSlug);\n const existingPluginInstructions = session.state.get()?.pluginInstructions ?? [];\n await session.state.set({\n ...sessionTags,\n // The authoritative org id for every downstream identity read (the\n // memory seam's organizationId): the session owner is a USER id, not an\n // org, so it must never be improvised from ownerId.\n factoryOrgId: request.orgId,\n factoryModelScope: sessionModel.modelScope,\n factoryOwnerUserId: sourceSession.userId,\n pluginInstructions: [\n ...existingPluginInstructions.filter(instruction => !isRunRepositoryInstruction(instruction)),\n targetRepositoryInstruction,\n ],\n ...(untrustedCheckout ? { untrustedCheckout: true, ...(baseRef ? { baseRef } : {}) } : {}),\n });\n await primeTenantCredentialsForTenant({\n orgId: request.orgId,\n userId: sourceSession.userId,\n credentialScope: sessionModel.modelScope,\n });\n // Apply the factory's main model before any model-dependent run work.\n // Observational-memory settings are loaded per invocation by the input processor.\n await hydrateFactorySession(session, {\n orgId: request.orgId,\n modelScope: sessionModel.modelScope,\n ownerUserId: sourceSession.userId,\n defaultModelId: sessionModel.modelId,\n });\n // The tool is `requireApproval`, and that prompt parks the run whether or not\n // someone pressed Start — a person is reading the plan, not an approval queue.\n // Starting the run was already the say-so; the rules engine still governs.\n await session.permissions.setForTool({ toolName: 'factory_transition_work_item', policy: 'allow' });\n const threadId = await configureThread(session, request);\n const prepared = await storage.prepareRunStart({\n orgId: request.orgId,\n userId: request.userId,\n factoryProjectId: request.factoryProjectId,\n workItem: { id: request.workItem.id, input: request.workItem.input },\n role: request.workItem.role,\n expectedBindingId: request.expectedBindingId,\n session: { sessionId: sourceSession.sessionId, branch: sourceSession.branch, threadId },\n resourceId: memoryResourceId,\n kickoffKey: request.kickoffKey,\n kickoffMessage: null,\n });\n await session.thread.setSetting({ key: 'factoryWorkItemId', value: prepared.item.id });\n\n let revision = prepared.item.revision;\n const destinationStage = request.destinationStage;\n if (destinationStage && (prepared.item.stages.length !== 1 || prepared.item.stages[0] !== destinationStage)) {\n if (!this.#transitionService) throw new Error('Factory transition service is unavailable.');\n const transition = await this.#transitionService.transition({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: prepared.item.id,\n board: boardForWorkItem(prepared.item),\n stage: destinationStage,\n expectedRevision: prepared.item.revision,\n actor:\n request.startedBy ??\n (isFactoryPrincipalId(request.userId)\n ? { type: 'system', id: request.userId }\n : { type: 'human', id: request.userId }),\n ingress: { type: 'human', identity: `start:${request.kickoffKey}:transition` },\n cause: 'run_start',\n });\n if (transition.status === 'rejected') {\n await storage.markPendingStart(prepared.binding.id, 'failed');\n throw new FactoryStartTransitionError(transition);\n }\n revision = transition.revision;\n }\n\n await storage.markPendingStart(prepared.binding.id, 'sent');\n prepared.pendingStart.status = 'sent';\n\n return {\n workItemId: prepared.item.id,\n bindingId: prepared.binding.id,\n threadId,\n resourceId: memoryResourceId,\n sessionId: sourceSession.sessionId,\n branch: sourceSession.branch,\n revision,\n kickoffStatus: prepared.pendingStart.status,\n replayed: prepared.replayed,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AAoDA,IAAa,8BAAb,cAAiD,MAAM;CAChC;CAArB,YAAY,WAA4B;EACtC,MACE,WAA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D,MAAM,IAAI,4BAA4B,UAAU;GAClD;GACA,WAAW,WAAW;EACxB;EAEA,MAAM,QAAQ,iBAAiB,SAAS,QAAQ,IAAI,MAAM;EAC1D,SAAS,aAAa,SAAS;EAE/B,OAAO;GACL,YAAY,SAAS,KAAK;GAC1B,WAAW,SAAS,QAAQ;GAC5B;GACA,YAAY;GACZ,WAAW,cAAc;GACzB,QAAQ,cAAc;GACtB;GACA,eAAe,SAAS,aAAa;GACrC,UAAU,SAAS;EACrB;CACF;AACF"}
@@ -4,6 +4,12 @@ import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
4
4
  type WarningLogger = (message: string, details: Record<string, unknown>) => void;
5
5
  export interface SessionRetirementCoordinatorOptions {
6
6
  invalidateSession?: (sessionId: string) => Promise<void> | void;
7
+ /**
8
+ * Unload the session from the controller once its sandbox is stopped or released, so its
9
+ * in-memory state is freed. Must keep the thread, the row and the VM. Not called by
10
+ * recreate or reset, which keep the session working.
11
+ */
12
+ unloadSession?: (sessionId: string) => Promise<unknown> | unknown;
7
13
  /**
8
14
  * The deploy's sandbox configuration. Used to destroy a deleted session's
9
15
  * VM by identity when this process never attached to it (after a restart,
@@ -1 +1 @@
1
- {"version":3,"file":"session-retirement.d.ts","sourceRoot":"","sources":["../../src/sandbox/session-retirement.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAoB,MAAM,wBAAwB,CAAC;AAU/E,OAAO,KAAK,EAGV,0BAA0B,EAC3B,MAAM,2CAA2C,CAAC;AACnD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAI9E,KAAK,aAAa,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;AAEjF,MAAM,WAAW,mCAAmC;IAClD,iBAAiB,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,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 @@ function boundedError(error) {
36
36
  */
37
37
  var SessionRetirementCoordinator = class {
38
38
  #invalidateSession;
39
+ #unloadSession;
39
40
  #sandbox;
40
41
  #warn;
41
42
  #destroyTimeoutMs;
42
43
  #locks = /* @__PURE__ */ new Map();
43
44
  constructor(options = {}) {
44
45
  this.#invalidateSession = options.invalidateSession ?? (() => {});
46
+ this.#unloadSession = options.unloadSession ?? (() => {});
45
47
  this.#sandbox = options.sandbox;
46
48
  this.#warn = options.warn ?? ((message, details) => console.warn(`[Mastra Factory] ${message}`, details));
47
49
  this.#destroyTimeoutMs = options.destroyTimeoutMs ?? DEFAULT_DESTROY_TIMEOUT_MS;
@@ -95,6 +97,7 @@ var SessionRetirementCoordinator = class {
95
97
  }, session);
96
98
  } finally {
97
99
  await this.#invalidate(session);
100
+ await this.#unload(session);
98
101
  }
99
102
  });
100
103
  }
@@ -140,6 +143,7 @@ var SessionRetirementCoordinator = class {
140
143
  released = await this.#teardownSessionSandbox(input, session);
141
144
  } finally {
142
145
  await this.#invalidate(session);
146
+ await this.#unload(session);
143
147
  if (input.deleteSession) {
144
148
  await input.workItems?.clearSessionReferences({
145
149
  orgId: input.orgId,
@@ -235,6 +239,19 @@ var SessionRetirementCoordinator = class {
235
239
  });
236
240
  }
237
241
  }
242
+ /** Unload the session from this process's controller; a failure is logged, never fatal. */
243
+ async #unload(session) {
244
+ try {
245
+ await this.#unloadSession(session.sessionId);
246
+ } catch (error) {
247
+ this.#warn("Factory session unload failed", {
248
+ orgId: session.orgId,
249
+ sessionId: session.sessionId,
250
+ projectRepositoryId: session.projectRepositoryId,
251
+ error: boundedError(error)
252
+ });
253
+ }
254
+ }
238
255
  async #recreateSessionSandbox(input) {
239
256
  const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);
240
257
  if (!session || session.orgId !== input.orgId) return "not-found";
@@ -1 +1 @@
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 {\n destroyDetachedSessionSandbox,\n releaseSessionSandbox,\n stopDetachedSessionSandbox,\n} from '../integrations/github/sandbox-release.js';\nimport { DEFAULT_COMMAND_TIMEOUT_MS, runTeardownCommand } from '../integrations/github/sandbox.js';\nimport { factoryMetrics } from '../metrics/metrics.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 { clearFailedSetupCommands, 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: a materialized one is stopped (or, when deleted, destroyed) by\n * identity through the configured sandbox. Providers such as E2B keep paused\n * VMs forever, so the row's 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 const retired = await this.#withSessionLock(input.sessionId, () => this.#retireSession(input));\n if (retired) factoryMetrics().count('sandbox', 'mastra_factory_sandbox_retired_total');\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 const result = await this.#withSessionLock(input.sessionId, () => this.#recreateSessionSandbox(input));\n if (result === 'recreated')\n factoryMetrics().count('sandbox', 'mastra_factory_sandbox_recreated_total', { kind: 'recreate' });\n return result;\n }\n\n /**\n * Replace the session's VM while keeping its sandbox instance, for the\n * session's own agent. A run holds the instance it started with until the\n * run ends, so recreate (which destroys the instance) would leave every\n * later command in that run failing. Here the VM is destroyed and the\n * instance is left `stopped` with no VM id, so the run's next command starts\n * a fresh VM and the start hook sets it up again.\n *\n * `not-here` means this process holds no instance for the session.\n */\n async resetSessionSandbox(input: RecreateSessionSandboxInput): Promise<'reset' | 'not-found' | 'not-here'> {\n const result = await this.#withSessionLock(input.sessionId, () => this.#resetSessionSandbox(input));\n if (result === 'reset')\n factoryMetrics().count('sandbox', 'mastra_factory_sandbox_recreated_total', { kind: 'reset' });\n return result;\n }\n\n /**\n * Stop a session's sandbox and keep everything else: the row, its files and\n * its work-item refs, so the session's next start resumes the same sandbox.\n * Unlike retirement no teardown command runs, because a resume does not\n * run setup again. Reaches the VM by identity when this process never\n * attached to it.\n */\n async stopSessionSandbox(input: Omit<RetireSessionInput, 'deleteSession' | 'workItems'>): Promise<void> {\n await this.#withSessionLock(input.sessionId, async () => {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return;\n try {\n if (peekSessionSandbox(session.id)) await releaseSessionSandbox({ sessionId: session.id });\n else await this.#releaseDetachedSandbox({ ...input, deleteSession: false }, session);\n } finally {\n await this.#invalidate(session);\n }\n });\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 /** Resolves `true` when the session had a sandbox and releasing it succeeded. */\n async #retireSession(input: RetireSessionInput): Promise<boolean> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return false;\n\n let released = false;\n try {\n released = 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 return released;\n }\n\n async #teardownSessionSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<boolean> {\n const entry = peekSessionSandbox(session.id);\n if (!entry) return this.#releaseDetachedSandbox(input, session);\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 return this.#releaseSandbox(input, session);\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 return this.#releaseSandbox(input, session);\n }\n\n /**\n * Stop (or, for a deleted session, destroy) a session's VM that this\n * process never attached to. Only for sessions that materialized (a\n * persisted `sandboxId`): nothing is started, no teardown command runs —\n * the provider pauses or kills by identity. Resolves whether a sandbox was released.\n */\n async #releaseDetachedSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<boolean> {\n if (!session.sandboxId || !this.#sandbox) return false;\n try {\n if (input.deleteSession) await destroyDetachedSessionSandbox({ sandbox: this.#sandbox, session });\n else await stopDetachedSessionSandbox({ sandbox: this.#sandbox, session });\n return true;\n } catch (error) {\n this.#warn(`Factory detached session sandbox ${input.deleteSession ? 'destroy' : 'stop'} failed`, {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n return false;\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 async #resetSessionSandbox(input: RecreateSessionSandboxInput): Promise<'reset' | 'not-found' | 'not-here'> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return 'not-found';\n const sandbox = peekSessionSandbox(session.id)?.sandbox;\n if (!sandbox) return 'not-here';\n\n // The provider's own destroy, not the lifecycle wrapper: the wrapper marks\n // the instance destroyed for good. Bounded, so a VM that won't answer\n // can't hold the session lock.\n const destroy = async () => {\n if (!(await this.#settledWithin(this.#destroyDirectly(sandbox)))) {\n throw new Error('Timed out destroying the sandbox. Try again.');\n }\n };\n // Destroyed before waiting on a start in flight, so a start hung on the\n // dead VM can't block recovery; its commands fail fast once the VM is gone.\n await destroy();\n const starting = (sandbox as { _startPromise?: Promise<unknown> })._startPromise;\n if (starting) {\n const settled = await this.#settledWithin(\n starting.then(\n () => {},\n () => {},\n ),\n );\n if (!settled) throw new Error('The old sandbox is still starting. Try again.');\n // That start may have found the old VM gone and provisioned another.\n await destroy();\n }\n\n sandbox.status = 'stopped';\n // The new VM runs setup from scratch, including commands that failed on the old one.\n clearFailedSetupCommands(session.id);\n // Re-read: a start that settled while this reset waited may have stored a newer workdir.\n const latest = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n await input.sourceControl.sessions.setSandbox({\n id: session.id,\n sandboxId: null,\n sandboxWorkdir: latest?.sandboxWorkdir ?? session.sandboxWorkdir ?? '',\n });\n return 'reset';\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<boolean> {\n try {\n await releaseSessionSandbox({ sessionId: session.id, destroy: input.deleteSession });\n return true;\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 return false;\n }\n }\n}\n"],"mappings":";;;;;;;AAwCA,MAAM,6BAA6B;;;;;;AAOnC,SAAS,mBAAmB,OAAyB;CACnD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,EAAE,QAAQ,SAAS;CACzB,IAAI,WAAW,KAAK,OAAO;CAC3B,OAAO,WAAW,QAAQ,SAAS,KAAA,KAAa,SAAS,QAAQ,SAAS;AAC5E;AAWA,SAAS,aAAa,OAAwB;CAC5C,MAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CACpE,IAAI,OAAO,UAAU,KAAM,OAAO;CAClC,OAAO,GAAG,OAAO,MAAM,GAAG,GAAG,EAAE,KAAK,OAAO,MAAM,KAAK;AACxD;;;;;;;;;;;;;AAcA,IAAa,+BAAb,MAA0C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O;EACT;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 {\n destroyDetachedSessionSandbox,\n releaseSessionSandbox,\n stopDetachedSessionSandbox,\n} from '../integrations/github/sandbox-release.js';\nimport { DEFAULT_COMMAND_TIMEOUT_MS, runTeardownCommand } from '../integrations/github/sandbox.js';\nimport { factoryMetrics } from '../metrics/metrics.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 { clearFailedSetupCommands, 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 * Unload the session from the controller once its sandbox is stopped or released, so its\n * in-memory state is freed. Must keep the thread, the row and the VM. Not called by\n * recreate or reset, which keep the session working.\n */\n unloadSession?: (sessionId: string) => Promise<unknown> | unknown;\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: a materialized one is stopped (or, when deleted, destroyed) by\n * identity through the configured sandbox. Providers such as E2B keep paused\n * VMs forever, so the row's deletion must never orphan one.\n */\nexport class SessionRetirementCoordinator {\n readonly #invalidateSession: NonNullable<SessionRetirementCoordinatorOptions['invalidateSession']>;\n readonly #unloadSession: NonNullable<SessionRetirementCoordinatorOptions['unloadSession']>;\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.#unloadSession = options.unloadSession ?? (() => {});\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 const retired = await this.#withSessionLock(input.sessionId, () => this.#retireSession(input));\n if (retired) factoryMetrics().count('sandbox', 'mastra_factory_sandbox_retired_total');\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 const result = await this.#withSessionLock(input.sessionId, () => this.#recreateSessionSandbox(input));\n if (result === 'recreated')\n factoryMetrics().count('sandbox', 'mastra_factory_sandbox_recreated_total', { kind: 'recreate' });\n return result;\n }\n\n /**\n * Replace the session's VM while keeping its sandbox instance, for the\n * session's own agent. A run holds the instance it started with until the\n * run ends, so recreate (which destroys the instance) would leave every\n * later command in that run failing. Here the VM is destroyed and the\n * instance is left `stopped` with no VM id, so the run's next command starts\n * a fresh VM and the start hook sets it up again.\n *\n * `not-here` means this process holds no instance for the session.\n */\n async resetSessionSandbox(input: RecreateSessionSandboxInput): Promise<'reset' | 'not-found' | 'not-here'> {\n const result = await this.#withSessionLock(input.sessionId, () => this.#resetSessionSandbox(input));\n if (result === 'reset')\n factoryMetrics().count('sandbox', 'mastra_factory_sandbox_recreated_total', { kind: 'reset' });\n return result;\n }\n\n /**\n * Stop a session's sandbox and keep everything else: the row, its files and\n * its work-item refs, so the session's next start resumes the same sandbox.\n * Unlike retirement no teardown command runs, because a resume does not\n * run setup again. Reaches the VM by identity when this process never\n * attached to it.\n */\n async stopSessionSandbox(input: Omit<RetireSessionInput, 'deleteSession' | 'workItems'>): Promise<void> {\n await this.#withSessionLock(input.sessionId, async () => {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return;\n try {\n if (peekSessionSandbox(session.id)) await releaseSessionSandbox({ sessionId: session.id });\n else await this.#releaseDetachedSandbox({ ...input, deleteSession: false }, session);\n } finally {\n await this.#invalidate(session);\n await this.#unload(session);\n }\n });\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 /** Resolves `true` when the session had a sandbox and releasing it succeeded. */\n async #retireSession(input: RetireSessionInput): Promise<boolean> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return false;\n\n let released = false;\n try {\n released = await this.#teardownSessionSandbox(input, session);\n } finally {\n await this.#invalidate(session);\n await this.#unload(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 return released;\n }\n\n async #teardownSessionSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<boolean> {\n const entry = peekSessionSandbox(session.id);\n if (!entry) return this.#releaseDetachedSandbox(input, session);\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 return this.#releaseSandbox(input, session);\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 return this.#releaseSandbox(input, session);\n }\n\n /**\n * Stop (or, for a deleted session, destroy) a session's VM that this\n * process never attached to. Only for sessions that materialized (a\n * persisted `sandboxId`): nothing is started, no teardown command runs —\n * the provider pauses or kills by identity. Resolves whether a sandbox was released.\n */\n async #releaseDetachedSandbox(input: RetireSessionInput, session: SourceControlSession): Promise<boolean> {\n if (!session.sandboxId || !this.#sandbox) return false;\n try {\n if (input.deleteSession) await destroyDetachedSessionSandbox({ sandbox: this.#sandbox, session });\n else await stopDetachedSessionSandbox({ sandbox: this.#sandbox, session });\n return true;\n } catch (error) {\n this.#warn(`Factory detached session sandbox ${input.deleteSession ? 'destroy' : 'stop'} failed`, {\n orgId: session.orgId,\n sessionId: session.sessionId,\n projectRepositoryId: session.projectRepositoryId,\n error: boundedError(error),\n });\n return false;\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 /** Unload the session from this process's controller; a failure is logged, never fatal. */\n async #unload(session: SourceControlSession): Promise<void> {\n try {\n await this.#unloadSession(session.sessionId);\n } catch (error) {\n this.#warn('Factory session unload 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 async #resetSessionSandbox(input: RecreateSessionSandboxInput): Promise<'reset' | 'not-found' | 'not-here'> {\n const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n if (!session || session.orgId !== input.orgId) return 'not-found';\n const sandbox = peekSessionSandbox(session.id)?.sandbox;\n if (!sandbox) return 'not-here';\n\n // The provider's own destroy, not the lifecycle wrapper: the wrapper marks\n // the instance destroyed for good. Bounded, so a VM that won't answer\n // can't hold the session lock.\n const destroy = async () => {\n if (!(await this.#settledWithin(this.#destroyDirectly(sandbox)))) {\n throw new Error('Timed out destroying the sandbox. Try again.');\n }\n };\n // Destroyed before waiting on a start in flight, so a start hung on the\n // dead VM can't block recovery; its commands fail fast once the VM is gone.\n await destroy();\n const starting = (sandbox as { _startPromise?: Promise<unknown> })._startPromise;\n if (starting) {\n const settled = await this.#settledWithin(\n starting.then(\n () => {},\n () => {},\n ),\n );\n if (!settled) throw new Error('The old sandbox is still starting. Try again.');\n // That start may have found the old VM gone and provisioned another.\n await destroy();\n }\n\n sandbox.status = 'stopped';\n // The new VM runs setup from scratch, including commands that failed on the old one.\n clearFailedSetupCommands(session.id);\n // Re-read: a start that settled while this reset waited may have stored a newer workdir.\n const latest = await input.sourceControl.sessions.getBySessionId(input.sessionId);\n await input.sourceControl.sessions.setSandbox({\n id: session.id,\n sandboxId: null,\n sandboxWorkdir: latest?.sandboxWorkdir ?? session.sandboxWorkdir ?? '',\n });\n return 'reset';\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<boolean> {\n try {\n await releaseSessionSandbox({ sessionId: session.id, destroy: input.deleteSession });\n return true;\n } catch (error) {\n this.#warn('Factory session sandbox release failed', {\n orgId: session.orgId,\n sessionId: session.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C,CAAC;IACpE,sFAAsF;IACtF,eAAe,CAAC,EAAE,IAAI,CAAC,sBAAsB,EAAE,aAAa,GAAG,MAAM,CAAC,CAAC;IACvE,yFAAyF;IACzF,wBAAwB,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;CAChD;AAED;;;;GAIG;AACH,wBAAsB,2BAA2B,CAC/C,OAAO,EAAE,wBAAwB,GAAG,SAAS,EAC7C,OAAO,EAAE,IAAI,CAAC,cAAc,EAAE,IAAI,GAAG,OAAO,CAAC,GAC5C,OAAO,CAAC,IAAI,CAAC,CAaf"}
@@ -1,3 +1,4 @@
1
+ import { customEndpointUrlProblem } from "../routes/custom-endpoint-url.js";
1
2
  import { resolveTenantProviderDefaultModel } from "../routes/tenant-credentials.js";
2
3
  import { FactoryDispatchError } from "../rules/dispatch-errors.js";
3
4
  import { effectiveModelScope, factoryPrincipalId } from "../storage/domains/projects/base.js";
@@ -260,7 +261,7 @@ async function requireOrganizationModelKey(sources, project) {
260
261
  if ((await sources.modelCredentials.listCredentials(project.orgId, factoryPrincipalId(project.id))).some((credential) => credential.scope === "org")) return;
261
262
  if (sources.customProviders) {
262
263
  await sources.customProviders.ensureReady();
263
- if ((await sources.customProviders.list({ orgId: project.orgId })).length) return;
264
+ if ((await sources.customProviders.list({ orgId: project.orgId })).some((provider) => !customEndpointUrlProblem(provider.url))) return;
264
265
  }
265
266
  throw new FactoryDispatchError("factory_org_key_missing", "This Factory runs its cards on the organization's model keys, and none is set. Add an organization key or provider under Settings → Models, then retry.");
266
267
  }
@@ -1 +1 @@
1
- {"version":3,"file":"factory-session.js","names":[],"sources":["../../src/session/factory-session.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\n\nimport { resolveTenantProviderDefaultModel } from '../routes/tenant-credentials.js';\nimport { FactoryDispatchError } from '../rules/dispatch-errors.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope, factoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { EffectiveModelScope, FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport { SourceControlConnectionNotFoundError } from '../storage/domains/source-control/base.js';\nimport type {\n SourceControlSession,\n SourceControlSessionVisibility,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport { legacyGithubWorkItemBranch } from '../work-item-branch.js';\nimport { resolveEnvironmentRepositories } from './environment-repositories.js';\nimport { seedSessionOrg } from './org-seed.js';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\nexport class FactorySourceControlConflictError extends Error {}\n\n/** Resolve the model and exclusive credential scope for a Factory session. */\nexport async function resolveFactorySessionModel(args: {\n projects: FactoryProjectsStorage | undefined;\n modelDefaults: ModelDefaultsStorage | undefined;\n factoryProjectId: string | undefined;\n orgId: string;\n ownerUserId: string;\n /** A work-item run or an interactive session; a hybrid Factory resolves a different scope for each. */\n context: 'run' | 'session';\n}): Promise<{ modelScope: EffectiveModelScope; modelId?: string }> {\n if (!args.projects || !args.factoryProjectId) throw new Error('Factory model policy is unavailable.');\n\n const project = await args.projects.getById({ id: args.factoryProjectId });\n if (!project || project.orgId !== args.orgId) throw new Error('Factory model policy is unavailable.');\n if (effectiveModelScope(project.modelScope, args.context) === 'factory') {\n return { modelScope: 'factory', ...(project.defaultModelId ? { modelId: project.defaultModelId } : {}) };\n }\n\n try {\n const userDefault = await args.modelDefaults?.get({ orgId: args.orgId, userId: args.ownerUserId });\n return { modelScope: 'user', ...(userDefault?.modelId ? { modelId: userDefault.modelId } : {}) };\n } catch (error) {\n console.warn('[Factory] Owner default model lookup failed; using the mode default model', {\n orgId: args.orgId,\n ownerUserId: args.ownerUserId,\n error: error instanceof Error ? error.message : String(error),\n });\n return { modelScope: 'user' };\n }\n}\n\nexport interface SourceControlSessionLookup {\n getBySessionId(sessionId: string): Promise<SourceControlSession | null>;\n getSourceControlBySessionId(sessionId: string): Promise<SourceControlStorageHandle | null>;\n /** Side sessions started by `originSessionId`, across every provider. */\n listByOrigin(args: { orgId: string; originSessionId: string }): Promise<SourceControlSession[]>;\n rename(args: { sessionId: string; title: string }): Promise<void>;\n setOriginMuted(args: { sessionId: string; muted: boolean }): Promise<void>;\n markFirstMessage(args: { sessionId: string }): Promise<void>;\n markFirstMeaningfulExec(args: { sessionId: string }): Promise<void>;\n}\n\n/**\n * Read or update a session across every registered source-control partition.\n * Session ids are globally generated, so more than one match is invalid and\n * fails closed instead of mutating an arbitrary provider.\n */\nexport function createSourceControlSessionLookup(\n sourceControls: readonly SourceControlStorageHandle[],\n): SourceControlSessionLookup {\n const resolve = async (\n sessionId: string,\n ): Promise<{ sourceControl: SourceControlStorageHandle; session: SourceControlSession } | null> => {\n const matches = (\n await Promise.all(\n sourceControls.map(async sourceControl => ({\n sourceControl,\n session: await sourceControl.sessions.getBySessionId(sessionId),\n })),\n )\n ).filter(\n (match): match is { sourceControl: SourceControlStorageHandle; session: SourceControlSession } =>\n match.session !== null,\n );\n if (matches.length > 1) throw new Error('Factory session exists in multiple source-control providers.');\n return matches[0] ?? null;\n };\n\n return {\n getBySessionId: async sessionId => (await resolve(sessionId))?.session ?? null,\n getSourceControlBySessionId: async sessionId => (await resolve(sessionId))?.sourceControl ?? null,\n listByOrigin: async args =>\n (await Promise.all(sourceControls.map(sourceControl => sourceControl.sessions.listByOrigin(args)))).flat(),\n rename: async args => (await resolve(args.sessionId))?.sourceControl.sessions.rename(args),\n setOriginMuted: async args => (await resolve(args.sessionId))?.sourceControl.sessions.setOriginMuted(args),\n markFirstMessage: async args => (await resolve(args.sessionId))?.sourceControl.sessions.markFirstMessage(args),\n markFirstMeaningfulExec: async args =>\n (await resolve(args.sessionId))?.sourceControl.sessions.markFirstMeaningfulExec(args),\n };\n}\n\n/**\n * Resolve the source-control provider from durable Factory repository links,\n * never from the issue tracker that happened to create the work item.\n */\nexport async function resolveFactorySourceControl(args: {\n sourceControls: readonly SourceControlStorageHandle[];\n orgId: string;\n factoryProjectId: string;\n sessionId?: string;\n}): Promise<SourceControlStorageHandle | undefined> {\n if (args.sessionId) {\n const sessionMatches = (\n await Promise.all(\n args.sourceControls.map(async sourceControl => ({\n sourceControl,\n session: await sourceControl.sessions.getBySessionId(args.sessionId!),\n })),\n )\n ).filter(match => match.session !== null);\n if (sessionMatches.length > 1) throw new Error('Factory session exists in multiple source-control providers.');\n if (sessionMatches[0]) return sessionMatches[0].sourceControl;\n }\n\n const linked = [];\n for (const sourceControl of args.sourceControls) {\n const connections = await sourceControl.connections.list({\n orgId: args.orgId,\n factoryProjectId: args.factoryProjectId,\n });\n let hasLinkedRepository = false;\n for (const connection of connections) {\n try {\n if (\n (await sourceControl.projectRepositories.list({ orgId: args.orgId, connectionId: connection.id })).length > 0\n ) {\n hasLinkedRepository = true;\n break;\n }\n } catch (error) {\n if (!(error instanceof SourceControlConnectionNotFoundError)) throw error;\n }\n }\n if (hasLinkedRepository) linked.push(sourceControl);\n }\n if (linked.length > 1)\n throw new FactorySourceControlConflictError(\n 'Factory project has repositories linked through multiple source-control providers.',\n );\n return linked[0];\n}\n\nexport interface EnsureFactorySourceSessionArgs {\n /**\n * Storage handle of the integration that owns source control. Nothing here is\n * provider-specific: the connection is matched by the handle's own\n * `integrationId`, so GitHub, Slack-on-behalf-of-GitHub, or any future owner\n * all resolve through the same traversal.\n */\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n branch: string;\n /**\n * The repository link the session is filed under: the one a work item\n * targets. Defaults to the factory's position-1 environment link (D1), for\n * callers where nothing names a repository (chat threads, user sessions).\n */\n projectRepositoryId?: string;\n /**\n * Attribute the run to this user instead of the repo connector. Set when the\n * run has an interactive user — e.g. the person who approved a proposed run.\n */\n attributeToUserId?: string;\n /** A pre-generated session id, so a caller can name the branch after it. Defaults to a fresh UUID. */\n sessionId?: string;\n /** Defaults to 'org'. A side session copies its parent's visibility. */\n visibility?: SourceControlSessionVisibility;\n /** The session and thread that started this one as a side session. */\n origin?: { sessionId: string; threadId: string };\n}\n\nexport interface EnsuredFactorySourceSession {\n sessionId: string;\n userId: string;\n projectRepositoryId: string;\n branch: string;\n baseBranch: string;\n}\n\nexport class FactorySourceSessionResolutionError extends Error {\n constructor(readonly reason: 'connection' | 'repository') {\n super(\n reason === 'connection'\n ? 'Factory source-control connection not found.'\n : 'Factory source-control repository not found.',\n );\n this.name = 'FactorySourceSessionResolutionError';\n }\n}\n\nexport interface ResolvedFactorySourceRepository {\n projectRepositoryId: string;\n /** The repository's pinned branch, else its default branch. */\n baseBranch: string;\n /** Who connected the repository. The attribution for runs with no interactive user. */\n connectedByUserId: string;\n}\n\n/**\n * Outcome of {@link resolvePrimaryEnvironmentRepository}. A miss carries which\n * step failed: callers differ on whether that is an error (an autonomous run\n * cannot proceed) or a routine fallback (a chat integration drops to a\n * chat-only session), and the two steps fail for different reasons worth\n * reporting apart.\n */\nexport type FactorySourceRepositoryResult =\n | ({ found: true } & ResolvedFactorySourceRepository)\n | { found: false; reason: 'connection' | 'repository' };\n\n/**\n * The repository link a new session is filed under. By default the position-1\n * `inEnvironment` link of the factory (decision D1); a work item that targets\n * a repository names its link through `projectRepositoryId`, which must be an\n * environment link of the same factory. Session start no longer picks a\n * repository to work in, the sandbox holds every environment repository. The\n * PR tools default to this link, and subscriptions, audit and the work item's\n * repository check still read it; moving them to the per-repository\n * `sessionRepositories` rows is a follow-up.\n *\n * The owner is whichever integration owns source control, matched by the\n * handle's own `integrationId` — nothing here is provider-specific.\n */\nexport async function resolvePrimaryEnvironmentRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n projectRepositoryId?: string;\n}): Promise<FactorySourceRepositoryResult> {\n const { sourceControl, orgId, factoryProjectId, projectRepositoryId } = args;\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n if (!connections.some(candidate => candidate.integrationId === sourceControl.integrationId)) {\n return { found: false, reason: 'connection' };\n }\n const repositories = await resolveEnvironmentRepositories({ sourceControl, orgId, factoryProjectId });\n const primary = repositories.find(\n candidate => projectRepositoryId === undefined || candidate.link.id === projectRepositoryId,\n );\n if (!primary) return { found: false, reason: 'repository' };\n return {\n found: true,\n projectRepositoryId: primary.link.id,\n baseBranch: primary.link.branch ?? primary.repository.defaultBranch,\n connectedByUserId: primary.connection.createdByUserId,\n };\n}\n\n/**\n * Create the source-control session a repo-backed factory run needs.\n *\n * `FactoryStartCoordinator.prepare` requires this record to already exist —\n * `resolveSourceSession` throws `Factory session not found` otherwise — so every\n * autonomous entry point has to produce one before it can start a run. This is\n * that step, in one place: the owner's connection on the factory project, the\n * work item's repository link (else the position-1 environment link, D1) as\n * the session's link, and a session on the requested branch with that\n * repository's pinned or default branch as the base. The sandbox itself boots\n * every environment repository.\n *\n * The run is attributed to `attributeToUserId` when the caller names a person\n * for it, and only otherwise falls back to whoever connected the repository\n * (`connection.createdByUserId`).\n */\nexport async function ensureFactorySourceSession(\n args: EnsureFactorySourceSessionArgs,\n): Promise<EnsuredFactorySourceSession> {\n const { sourceControl, orgId, factoryProjectId, branch, projectRepositoryId } = args;\n\n const resolved = await resolvePrimaryEnvironmentRepository({\n sourceControl,\n orgId,\n factoryProjectId,\n projectRepositoryId,\n });\n if (!resolved.found) throw new FactorySourceSessionResolutionError(resolved.reason);\n\n const userId = args.attributeToUserId ?? resolved.connectedByUserId;\n // Prefer an existing current branch, then the legacy branch on this exact\n // repository and owner. Never reuse another repository's same-number card.\n const legacyBranch = legacyGithubWorkItemBranch(branch);\n const lookup = { projectRepositoryId: resolved.projectRepositoryId, userId };\n const existing = legacyBranch\n ? ((await sourceControl.sessions.getForBranch({ ...lookup, branch })) ??\n (await sourceControl.sessions.getForBranch({ ...lookup, branch: legacyBranch })))\n : null;\n const session = await sourceControl.sessions.create({\n sessionId: args.sessionId ?? globalThis.crypto.randomUUID(),\n projectRepositoryId: resolved.projectRepositoryId,\n factoryProjectId,\n orgId,\n userId,\n branch: existing?.branch ?? branch,\n baseBranch: resolved.baseBranch,\n visibility: args.visibility ?? 'org',\n ...(args.origin ? { origin: args.origin } : {}),\n });\n return {\n sessionId: session.sessionId,\n userId,\n projectRepositoryId: resolved.projectRepositoryId,\n branch: session.branch,\n baseBranch: resolved.baseBranch,\n };\n}\n\nexport interface HydrateFactorySessionArgs {\n orgId: string;\n modelScope: EffectiveModelScope;\n ownerUserId: string;\n /**\n * The model selected by the Factory scope. Without it the provider default of a connected\n * provider is applied when the SDK mode default has no credential, else the mode default.\n */\n defaultModelId?: string;\n}\n\n/**\n * Apply a factory project's main model to a session on every run.\n *\n * The model switch is best-effort. A retired model id must not sink a run that\n * is otherwise ready, and the reason is logged. Observational-memory settings are resolved from the\n * authoritative row per invocation before memory processors run.\n */\nexport async function hydrateFactorySession(\n session: FactorySession,\n args: HydrateFactorySessionArgs,\n): Promise<string | undefined> {\n // The org rung knowledge curation scopes on. Seeded first so it lands even if\n // a later best-effort step fails; an empty org marks the session unresolved.\n await seedSessionOrg(session, args.orgId);\n await session.state.set({\n factoryModelScope: args.modelScope,\n factoryOwnerUserId: args.ownerUserId,\n });\n\n let selectedModelId = args.defaultModelId;\n if (!selectedModelId) {\n const modeModelId = session.mode.resolve().defaultModelId;\n const providerModelId = await resolveTenantProviderDefaultModel(\n { orgId: args.orgId, userId: args.ownerUserId, credentialScope: args.modelScope },\n modeModelId,\n ).catch(error => {\n console.warn('[Factory Start] Failed to resolve a provider default model', {\n error: error instanceof Error ? error.message : String(error),\n });\n return undefined;\n });\n selectedModelId = providerModelId ?? modeModelId;\n }\n if (!selectedModelId) return undefined;\n\n let switched = true;\n try {\n await session.model.switch(selectedModelId);\n } catch (error) {\n switched = false;\n console.warn('[Factory Start] Failed to apply scoped default model', {\n modelId: selectedModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n // Subagents otherwise keep the server-wide settings (or the SDK's built-in\n // default), which may name a provider this factory has no credentials for.\n // Each role is independent, so one failure doesn't strand the others.\n for (const agentType of ['explore', 'plan', 'execute']) {\n try {\n await session.subagents.model.set({ modelId: selectedModelId, agentType });\n } catch (error) {\n console.warn('[Factory Start] Failed to apply scoped default subagent model', {\n agentType,\n modelId: selectedModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n // Callers pin this id to the thread, so only report a model the session actually runs on.\n return switched ? selectedModelId : undefined;\n}\n\n/** Where a Factory-owned run can find a model to call. */\nexport interface OrganizationModelSources {\n modelCredentials?: Pick<ModelCredentialsStorage, 'listCredentials'>;\n /** OpenAI-compatible providers the organization configured, each with its own key. */\n customProviders?: Pick<CustomProvidersStorage, 'ensureReady' | 'list'>;\n /** Providers that run on the server process's own credentials, so need no stored key. */\n deploymentModelProviders?: ReadonlySet<string>;\n}\n\n/**\n * A run owned by the Factory reaches models through the organization alone: its stored\n * keys and the providers it configured. With neither it cannot run however often it is\n * retried, so say what to add instead of starting a run that dies on its first model call.\n */\nexport async function requireOrganizationModelKey(\n sources: OrganizationModelSources | undefined,\n project: Pick<FactoryProject, 'id' | 'orgId'>,\n): Promise<void> {\n if (!sources?.modelCredentials || sources.deploymentModelProviders?.size) return;\n const credentials = await sources.modelCredentials.listCredentials(project.orgId, factoryPrincipalId(project.id));\n if (credentials.some(credential => credential.scope === 'org')) return;\n if (sources.customProviders) {\n await sources.customProviders.ensureReady();\n if ((await sources.customProviders.list({ orgId: project.orgId })).length) return;\n }\n throw new FactoryDispatchError(\n 'factory_org_key_missing',\n \"This Factory runs its cards on the organization's model keys, and none is set. Add an organization key or provider under Settings → Models, then retry.\",\n );\n}\n"],"mappings":";;;;;;;;AAsBA,IAAa,oCAAb,cAAuD,MAAM,CAAC;;AAG9D,eAAsB,2BAA2B,MAQkB;CACjE,IAAI,CAAC,KAAK,YAAY,CAAC,KAAK,kBAAkB,MAAM,IAAI,MAAM,sCAAsC;CAEpG,MAAM,UAAU,MAAM,KAAK,SAA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AI;GAAE,SAAS;GAAiB;EAAU,CAAC;CAC3E,SAAS,OAAO;EACd,QAAQ,KAAK,iEAAiE;GAC5E;GACA,SAAS;GACT,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;CACH;CAGF,OAAO,WAAW,kBAAkB,KAAA;AACtC;;;;;;AAgBA,eAAsB,4BACpB,SACA,SACe;CACf,IAAI,CAAC,SAAS,oBAAoB,QAAQ,0BAA0B,MAAM;CAE1E,KAAI,MADsB,QAAQ,iBAAiB,gBAAgB,QAAQ,OAAO,mBAAmB,QAAQ,EAAE,CAAC,EAAA,CAChG,MAAK,eAAc,WAAW,UAAU,KAAK,GAAG;CAChE,IAAI,QAAQ,iBAAiB;EAC3B,MAAM,QAAQ,gBAAgB,YAAY;EAC1C,KAAK,MAAM,QAAQ,gBAAgB,KAAK,EAAE,OAAO,QAAQ,MAAM,CAAC,EAAA,CAAG,QAAQ;CAC7E;CACA,MAAM,IAAI,qBACR,2BACA,yJACF;AACF"}
1
+ {"version":3,"file":"factory-session.js","names":[],"sources":["../../src/session/factory-session.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\n\nimport { customEndpointUrlProblem } from '../routes/custom-endpoint-url.js';\nimport { resolveTenantProviderDefaultModel } from '../routes/tenant-credentials.js';\nimport { FactoryDispatchError } from '../rules/dispatch-errors.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope, factoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { EffectiveModelScope, FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport { SourceControlConnectionNotFoundError } from '../storage/domains/source-control/base.js';\nimport type {\n SourceControlSession,\n SourceControlSessionVisibility,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport { legacyGithubWorkItemBranch } from '../work-item-branch.js';\nimport { resolveEnvironmentRepositories } from './environment-repositories.js';\nimport { seedSessionOrg } from './org-seed.js';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\nexport class FactorySourceControlConflictError extends Error {}\n\n/** Resolve the model and exclusive credential scope for a Factory session. */\nexport async function resolveFactorySessionModel(args: {\n projects: FactoryProjectsStorage | undefined;\n modelDefaults: ModelDefaultsStorage | undefined;\n factoryProjectId: string | undefined;\n orgId: string;\n ownerUserId: string;\n /** A work-item run or an interactive session; a hybrid Factory resolves a different scope for each. */\n context: 'run' | 'session';\n}): Promise<{ modelScope: EffectiveModelScope; modelId?: string }> {\n if (!args.projects || !args.factoryProjectId) throw new Error('Factory model policy is unavailable.');\n\n const project = await args.projects.getById({ id: args.factoryProjectId });\n if (!project || project.orgId !== args.orgId) throw new Error('Factory model policy is unavailable.');\n if (effectiveModelScope(project.modelScope, args.context) === 'factory') {\n return { modelScope: 'factory', ...(project.defaultModelId ? { modelId: project.defaultModelId } : {}) };\n }\n\n try {\n const userDefault = await args.modelDefaults?.get({ orgId: args.orgId, userId: args.ownerUserId });\n return { modelScope: 'user', ...(userDefault?.modelId ? { modelId: userDefault.modelId } : {}) };\n } catch (error) {\n console.warn('[Factory] Owner default model lookup failed; using the mode default model', {\n orgId: args.orgId,\n ownerUserId: args.ownerUserId,\n error: error instanceof Error ? error.message : String(error),\n });\n return { modelScope: 'user' };\n }\n}\n\nexport interface SourceControlSessionLookup {\n getBySessionId(sessionId: string): Promise<SourceControlSession | null>;\n getSourceControlBySessionId(sessionId: string): Promise<SourceControlStorageHandle | null>;\n /** Side sessions started by `originSessionId`, across every provider. */\n listByOrigin(args: { orgId: string; originSessionId: string }): Promise<SourceControlSession[]>;\n rename(args: { sessionId: string; title: string }): Promise<void>;\n setOriginMuted(args: { sessionId: string; muted: boolean }): Promise<void>;\n markFirstMessage(args: { sessionId: string }): Promise<void>;\n markFirstMeaningfulExec(args: { sessionId: string }): Promise<void>;\n}\n\n/**\n * Read or update a session across every registered source-control partition.\n * Session ids are globally generated, so more than one match is invalid and\n * fails closed instead of mutating an arbitrary provider.\n */\nexport function createSourceControlSessionLookup(\n sourceControls: readonly SourceControlStorageHandle[],\n): SourceControlSessionLookup {\n const resolve = async (\n sessionId: string,\n ): Promise<{ sourceControl: SourceControlStorageHandle; session: SourceControlSession } | null> => {\n const matches = (\n await Promise.all(\n sourceControls.map(async sourceControl => ({\n sourceControl,\n session: await sourceControl.sessions.getBySessionId(sessionId),\n })),\n )\n ).filter(\n (match): match is { sourceControl: SourceControlStorageHandle; session: SourceControlSession } =>\n match.session !== null,\n );\n if (matches.length > 1) throw new Error('Factory session exists in multiple source-control providers.');\n return matches[0] ?? null;\n };\n\n return {\n getBySessionId: async sessionId => (await resolve(sessionId))?.session ?? null,\n getSourceControlBySessionId: async sessionId => (await resolve(sessionId))?.sourceControl ?? null,\n listByOrigin: async args =>\n (await Promise.all(sourceControls.map(sourceControl => sourceControl.sessions.listByOrigin(args)))).flat(),\n rename: async args => (await resolve(args.sessionId))?.sourceControl.sessions.rename(args),\n setOriginMuted: async args => (await resolve(args.sessionId))?.sourceControl.sessions.setOriginMuted(args),\n markFirstMessage: async args => (await resolve(args.sessionId))?.sourceControl.sessions.markFirstMessage(args),\n markFirstMeaningfulExec: async args =>\n (await resolve(args.sessionId))?.sourceControl.sessions.markFirstMeaningfulExec(args),\n };\n}\n\n/**\n * Resolve the source-control provider from durable Factory repository links,\n * never from the issue tracker that happened to create the work item.\n */\nexport async function resolveFactorySourceControl(args: {\n sourceControls: readonly SourceControlStorageHandle[];\n orgId: string;\n factoryProjectId: string;\n sessionId?: string;\n}): Promise<SourceControlStorageHandle | undefined> {\n if (args.sessionId) {\n const sessionMatches = (\n await Promise.all(\n args.sourceControls.map(async sourceControl => ({\n sourceControl,\n session: await sourceControl.sessions.getBySessionId(args.sessionId!),\n })),\n )\n ).filter(match => match.session !== null);\n if (sessionMatches.length > 1) throw new Error('Factory session exists in multiple source-control providers.');\n if (sessionMatches[0]) return sessionMatches[0].sourceControl;\n }\n\n const linked = [];\n for (const sourceControl of args.sourceControls) {\n const connections = await sourceControl.connections.list({\n orgId: args.orgId,\n factoryProjectId: args.factoryProjectId,\n });\n let hasLinkedRepository = false;\n for (const connection of connections) {\n try {\n if (\n (await sourceControl.projectRepositories.list({ orgId: args.orgId, connectionId: connection.id })).length > 0\n ) {\n hasLinkedRepository = true;\n break;\n }\n } catch (error) {\n if (!(error instanceof SourceControlConnectionNotFoundError)) throw error;\n }\n }\n if (hasLinkedRepository) linked.push(sourceControl);\n }\n if (linked.length > 1)\n throw new FactorySourceControlConflictError(\n 'Factory project has repositories linked through multiple source-control providers.',\n );\n return linked[0];\n}\n\nexport interface EnsureFactorySourceSessionArgs {\n /**\n * Storage handle of the integration that owns source control. Nothing here is\n * provider-specific: the connection is matched by the handle's own\n * `integrationId`, so GitHub, Slack-on-behalf-of-GitHub, or any future owner\n * all resolve through the same traversal.\n */\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n branch: string;\n /**\n * The repository link the session is filed under: the one a work item\n * targets. Defaults to the factory's position-1 environment link (D1), for\n * callers where nothing names a repository (chat threads, user sessions).\n */\n projectRepositoryId?: string;\n /**\n * Attribute the run to this user instead of the repo connector. Set when the\n * run has an interactive user — e.g. the person who approved a proposed run.\n */\n attributeToUserId?: string;\n /** A pre-generated session id, so a caller can name the branch after it. Defaults to a fresh UUID. */\n sessionId?: string;\n /** Defaults to 'org'. A side session copies its parent's visibility. */\n visibility?: SourceControlSessionVisibility;\n /** The session and thread that started this one as a side session. */\n origin?: { sessionId: string; threadId: string };\n}\n\nexport interface EnsuredFactorySourceSession {\n sessionId: string;\n userId: string;\n projectRepositoryId: string;\n branch: string;\n baseBranch: string;\n}\n\nexport class FactorySourceSessionResolutionError extends Error {\n constructor(readonly reason: 'connection' | 'repository') {\n super(\n reason === 'connection'\n ? 'Factory source-control connection not found.'\n : 'Factory source-control repository not found.',\n );\n this.name = 'FactorySourceSessionResolutionError';\n }\n}\n\nexport interface ResolvedFactorySourceRepository {\n projectRepositoryId: string;\n /** The repository's pinned branch, else its default branch. */\n baseBranch: string;\n /** Who connected the repository. The attribution for runs with no interactive user. */\n connectedByUserId: string;\n}\n\n/**\n * Outcome of {@link resolvePrimaryEnvironmentRepository}. A miss carries which\n * step failed: callers differ on whether that is an error (an autonomous run\n * cannot proceed) or a routine fallback (a chat integration drops to a\n * chat-only session), and the two steps fail for different reasons worth\n * reporting apart.\n */\nexport type FactorySourceRepositoryResult =\n | ({ found: true } & ResolvedFactorySourceRepository)\n | { found: false; reason: 'connection' | 'repository' };\n\n/**\n * The repository link a new session is filed under. By default the position-1\n * `inEnvironment` link of the factory (decision D1); a work item that targets\n * a repository names its link through `projectRepositoryId`, which must be an\n * environment link of the same factory. Session start no longer picks a\n * repository to work in, the sandbox holds every environment repository. The\n * PR tools default to this link, and subscriptions, audit and the work item's\n * repository check still read it; moving them to the per-repository\n * `sessionRepositories` rows is a follow-up.\n *\n * The owner is whichever integration owns source control, matched by the\n * handle's own `integrationId` — nothing here is provider-specific.\n */\nexport async function resolvePrimaryEnvironmentRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n projectRepositoryId?: string;\n}): Promise<FactorySourceRepositoryResult> {\n const { sourceControl, orgId, factoryProjectId, projectRepositoryId } = args;\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n if (!connections.some(candidate => candidate.integrationId === sourceControl.integrationId)) {\n return { found: false, reason: 'connection' };\n }\n const repositories = await resolveEnvironmentRepositories({ sourceControl, orgId, factoryProjectId });\n const primary = repositories.find(\n candidate => projectRepositoryId === undefined || candidate.link.id === projectRepositoryId,\n );\n if (!primary) return { found: false, reason: 'repository' };\n return {\n found: true,\n projectRepositoryId: primary.link.id,\n baseBranch: primary.link.branch ?? primary.repository.defaultBranch,\n connectedByUserId: primary.connection.createdByUserId,\n };\n}\n\n/**\n * Create the source-control session a repo-backed factory run needs.\n *\n * `FactoryStartCoordinator.prepare` requires this record to already exist —\n * `resolveSourceSession` throws `Factory session not found` otherwise — so every\n * autonomous entry point has to produce one before it can start a run. This is\n * that step, in one place: the owner's connection on the factory project, the\n * work item's repository link (else the position-1 environment link, D1) as\n * the session's link, and a session on the requested branch with that\n * repository's pinned or default branch as the base. The sandbox itself boots\n * every environment repository.\n *\n * The run is attributed to `attributeToUserId` when the caller names a person\n * for it, and only otherwise falls back to whoever connected the repository\n * (`connection.createdByUserId`).\n */\nexport async function ensureFactorySourceSession(\n args: EnsureFactorySourceSessionArgs,\n): Promise<EnsuredFactorySourceSession> {\n const { sourceControl, orgId, factoryProjectId, branch, projectRepositoryId } = args;\n\n const resolved = await resolvePrimaryEnvironmentRepository({\n sourceControl,\n orgId,\n factoryProjectId,\n projectRepositoryId,\n });\n if (!resolved.found) throw new FactorySourceSessionResolutionError(resolved.reason);\n\n const userId = args.attributeToUserId ?? resolved.connectedByUserId;\n // Prefer an existing current branch, then the legacy branch on this exact\n // repository and owner. Never reuse another repository's same-number card.\n const legacyBranch = legacyGithubWorkItemBranch(branch);\n const lookup = { projectRepositoryId: resolved.projectRepositoryId, userId };\n const existing = legacyBranch\n ? ((await sourceControl.sessions.getForBranch({ ...lookup, branch })) ??\n (await sourceControl.sessions.getForBranch({ ...lookup, branch: legacyBranch })))\n : null;\n const session = await sourceControl.sessions.create({\n sessionId: args.sessionId ?? globalThis.crypto.randomUUID(),\n projectRepositoryId: resolved.projectRepositoryId,\n factoryProjectId,\n orgId,\n userId,\n branch: existing?.branch ?? branch,\n baseBranch: resolved.baseBranch,\n visibility: args.visibility ?? 'org',\n ...(args.origin ? { origin: args.origin } : {}),\n });\n return {\n sessionId: session.sessionId,\n userId,\n projectRepositoryId: resolved.projectRepositoryId,\n branch: session.branch,\n baseBranch: resolved.baseBranch,\n };\n}\n\nexport interface HydrateFactorySessionArgs {\n orgId: string;\n modelScope: EffectiveModelScope;\n ownerUserId: string;\n /**\n * The model selected by the Factory scope. Without it the provider default of a connected\n * provider is applied when the SDK mode default has no credential, else the mode default.\n */\n defaultModelId?: string;\n}\n\n/**\n * Apply a factory project's main model to a session on every run.\n *\n * The model switch is best-effort. A retired model id must not sink a run that\n * is otherwise ready, and the reason is logged. Observational-memory settings are resolved from the\n * authoritative row per invocation before memory processors run.\n */\nexport async function hydrateFactorySession(\n session: FactorySession,\n args: HydrateFactorySessionArgs,\n): Promise<string | undefined> {\n // The org rung knowledge curation scopes on. Seeded first so it lands even if\n // a later best-effort step fails; an empty org marks the session unresolved.\n await seedSessionOrg(session, args.orgId);\n await session.state.set({\n factoryModelScope: args.modelScope,\n factoryOwnerUserId: args.ownerUserId,\n });\n\n let selectedModelId = args.defaultModelId;\n if (!selectedModelId) {\n const modeModelId = session.mode.resolve().defaultModelId;\n const providerModelId = await resolveTenantProviderDefaultModel(\n { orgId: args.orgId, userId: args.ownerUserId, credentialScope: args.modelScope },\n modeModelId,\n ).catch(error => {\n console.warn('[Factory Start] Failed to resolve a provider default model', {\n error: error instanceof Error ? error.message : String(error),\n });\n return undefined;\n });\n selectedModelId = providerModelId ?? modeModelId;\n }\n if (!selectedModelId) return undefined;\n\n let switched = true;\n try {\n await session.model.switch(selectedModelId);\n } catch (error) {\n switched = false;\n console.warn('[Factory Start] Failed to apply scoped default model', {\n modelId: selectedModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n // Subagents otherwise keep the server-wide settings (or the SDK's built-in\n // default), which may name a provider this factory has no credentials for.\n // Each role is independent, so one failure doesn't strand the others.\n for (const agentType of ['explore', 'plan', 'execute']) {\n try {\n await session.subagents.model.set({ modelId: selectedModelId, agentType });\n } catch (error) {\n console.warn('[Factory Start] Failed to apply scoped default subagent model', {\n agentType,\n modelId: selectedModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n // Callers pin this id to the thread, so only report a model the session actually runs on.\n return switched ? selectedModelId : undefined;\n}\n\n/** Where a Factory-owned run can find a model to call. */\nexport interface OrganizationModelSources {\n modelCredentials?: Pick<ModelCredentialsStorage, 'listCredentials'>;\n /** OpenAI-compatible providers the organization configured, each with its own key. */\n customProviders?: Pick<CustomProvidersStorage, 'ensureReady' | 'list'>;\n /** Providers that run on the server process's own credentials, so need no stored key. */\n deploymentModelProviders?: ReadonlySet<string>;\n}\n\n/**\n * A run owned by the Factory reaches models through the organization alone: its stored\n * keys and the providers it configured. With neither it cannot run however often it is\n * retried, so say what to add instead of starting a run that dies on its first model call.\n */\nexport async function requireOrganizationModelKey(\n sources: OrganizationModelSources | undefined,\n project: Pick<FactoryProject, 'id' | 'orgId'>,\n): Promise<void> {\n if (!sources?.modelCredentials || sources.deploymentModelProviders?.size) return;\n const credentials = await sources.modelCredentials.listCredentials(project.orgId, factoryPrincipalId(project.id));\n if (credentials.some(credential => credential.scope === 'org')) return;\n if (sources.customProviders) {\n await sources.customProviders.ensureReady();\n const organizationProviders = await sources.customProviders.list({ orgId: project.orgId });\n if (organizationProviders.some(provider => !customEndpointUrlProblem(provider.url))) return;\n }\n throw new FactoryDispatchError(\n 'factory_org_key_missing',\n \"This Factory runs its cards on the organization's model keys, and none is set. Add an organization key or provider under Settings → Models, then retry.\",\n );\n}\n"],"mappings":";;;;;;;;;AAuBA,IAAa,oCAAb,cAAuD,MAAM,CAAC;;AAG9D,eAAsB,2BAA2B,MAQkB;CACjE,IAAI,CAAC,KAAK,YAAY,CAAC,KAAK,kBAAkB,MAAM,IAAI,MAAM,sCAAsC;CAEpG,MAAM,UAAU,MAAM,KAAK,SAAS,QAAQ,EAAE,IAAI,KAAK,iBAAiB,CAAC;CACzE,IAAI,CAAC,WAAW,QAAQ,UAAU,KAAK,OAAO,MAAM,IAAI,MAAM,sCAAsC;CACpG,IAAI,oBAAoB,QAAQ,YAAY,KAAK,OAAO,MAAM,WAC5D,OAAO;EAAE,YAAY;EAAW,GAAI,QAAQ,iBAAiB,EAAE,SAAS,QAAQ,eAAe,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IAAI,CAAC,SAAS,oBAAoB,QAAQ,0BAA0B,MAAM;CAE1E,KAAI,MADsB,QAAQ,iBAAiB,gBAAgB,QAAQ,OAAO,mBAAmB,QAAQ,EAAE,CAAC,EAAA,CAChG,MAAK,eAAc,WAAW,UAAU,KAAK,GAAG;CAChE,IAAI,QAAQ,iBAAiB;EAC3B,MAAM,QAAQ,gBAAgB,YAAY;EAE1C,KAAI,MADgC,QAAQ,gBAAgB,KAAK,EAAE,OAAO,QAAQ,MAAM,CAAC,EAAA,CAC/D,MAAK,aAAY,CAAC,yBAAyB,SAAS,GAAG,CAAC,GAAG;CACvF;CACA,MAAM,IAAI,qBACR,2BACA,yJACF;AACF"}
@@ -1,11 +1,14 @@
1
1
  import type { AgentControllerEvent } from '@mastra/core/agent-controller';
2
2
  import type { PubSub } from '@mastra/core/events';
3
3
  import type { SourceControlSession } from '../storage/domains/source-control/base.js';
4
- /** The slice of a live session this registry needs: its id, its run, its parked tools, and who it works for. */
4
+ /** The slice of a live session this registry needs: its id, its thread, its run, its parked tools, and who it works for. */
5
5
  export interface LiveSession {
6
6
  readonly identity: {
7
7
  getId(): string;
8
8
  };
9
+ readonly thread: {
10
+ getId(): string | null;
11
+ };
9
12
  readonly run: {
10
13
  isRunning(): boolean;
11
14
  };
@@ -55,6 +58,8 @@ export declare class LiveSessions {
55
58
  constructor(controller: SessionNotifier);
56
59
  /** Whether the session has an agent run in flight right now. */
57
60
  isRunning(sessionId: string): boolean;
61
+ /** The session on this thread now: a run always lies on its session's current thread. */
62
+ sessionOnThread(threadId: string): string | undefined;
58
63
  /** The tool the session is parked on, oldest first, or nothing when no answer is owed. */
59
64
  parked(sessionId: string): ParkedRun | undefined;
60
65
  /** Every parked session of a project, so the inbox reads no card when nothing waits. */
@@ -1 +1 @@
1
- {"version":3,"file":"live-sessions.d.ts","sourceRoot":"","sources":["../../src/session/live-sessions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B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CAAC,gBAAgB,EAAE,MAAM,GAAG,KAAK,CAAC;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,SAAS,CAAA;KAAE,CAAC,CAQ/E;IAED,iIAAiI;IACjI,YAAY,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,GAAG,MAAM,IAAI,CAGjE;CACF;AAED,4HAA4H;AAC5H,wBAAgB,2BAA2B,CACzC,UAAU,EAAE,eAAe,EAC3B,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,WAAW,GAChB,YAAY,CAiBd"}
@@ -61,6 +61,10 @@ var LiveSessions = class {
61
61
  isRunning(sessionId) {
62
62
  return this.#byId.get(sessionId)?.session.run.isRunning() ?? false;
63
63
  }
64
+ /** The session on this thread now: a run always lies on its session's current thread. */
65
+ sessionOnThread(threadId) {
66
+ for (const [sessionId, { session }] of this.#byId) if (session.thread.getId() === threadId) return sessionId;
67
+ }
64
68
  /** The tool the session is parked on, oldest first, or nothing when no answer is owed. */
65
69
  parked(sessionId) {
66
70
  const tracked = this.#byId.get(sessionId);