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

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 +7 -7
  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":"surface.js","names":[],"sources":["../../src/routes/surface.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { ApiRoute, IUserProvider } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { InlineSkill } from '@mastra/core/skills';\nimport type { FactoryStorage } from '@mastra/core/storage';\nimport type { FactorySandbox } from '@mastra/core/workspace';\n\nimport {\n boardFlow,\n boardForWorkItem,\n hasPullRequest,\n isPullRequestReviewPhase,\n REVIEW_CONTEXT,\n reviewedChangeRequest,\n} from '../boards/index.js';\nimport type { BoardRegistry, InstalledBoard } from '../boards/index.js';\nimport type { ForcedIntakeEvaluator } from '../boards/intake-routing.js';\nimport { legacyPlanRoleFor, workLaneForRole } from '../boards/legacy-plan-role.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardCache, ProjectBoardSource } from '../boards/project-boards.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationHooks } from '../integrations/base.js';\nimport { getGithubFeatureDiagnostics } from '../integrations/github/config.js';\nimport type { GithubIntegration } from '../integrations/github/integration.js';\nimport { MaterializeError } from '../integrations/github/sandbox.js';\nimport type { CardSource } from '../integrations/kept-cards.js';\nimport { FactoryDispatchError } from '../rules/dispatch-errors.js';\nimport type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';\nimport type { NotRoutedLookup } from '../rules/event-rules.js';\nimport { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { FactoryTransitionService } from '../rules/transition-service.js';\nimport { workItemSource } from '../rules/types.js';\nimport type { FactoryRuleActor } from '../rules/types.js';\nimport { secretKeyMismatchHint, secretKeyProblem } from '../secret-encryption.js';\nimport {\n createSourceControlSessionLookup,\n ensureFactorySourceSession,\n FactorySourceSessionResolutionError,\n resolveFactorySourceControl,\n requireOrganizationModelKey,\n} from '../session/factory-session.js';\nimport type { EnsuredFactorySourceSession, OrganizationModelSources } from '../session/factory-session.js';\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport { repositoryChosenByRun, resolveRunRepository } from '../session/work-item-repository.js';\nimport type { StateSigner } from '../state-signing.js';\nimport { isHumanActorId } from '../storage/domains/audit/actors.js';\nimport type { AuditEmitter, AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { IntakeEvaluator, StoredBoardsStorage } from '../storage/domains/boards/base.js';\nimport type { ChannelIdentityStorage } from '../storage/domains/channel-identity/base.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { IntegrationStorage } from '../storage/domains/integrations/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope, factoryPrincipalId, isFactoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport type { SkillOverridesStorage } from '../storage/domains/skill-overrides/base.js';\nimport {\n SessionBranchHeldError,\n SessionOwnershipMismatchError,\n SourceControlConnectionNotFoundError,\n} from '../storage/domains/source-control/base.js';\nimport type { SourceControlStorage, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { VoiceSettingsStorage } from '../storage/domains/voice-settings/base.js';\nimport type { FactoryDispatchFailureCode, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport {\n legacyGithubWorkItemBranch,\n pullRequestBranch,\n workItemBranch,\n workItemBranchSource,\n workItemThreadTitle,\n} from '../work-item-branch.js';\nimport type { WorkItemBranchSource } from '../work-item-branch.js';\nimport { buildAutomationRunRoutes } from './automation-runs.js';\nimport { BoardRoutes } from './boards.js';\nimport { ConfigRoutes } from './config.js';\nimport { invalidateCustomProvidersSnapshots } from './custom-provider-source.js';\nimport { buildFsRoutes } from './fs.js';\nimport { IntakeRouteRoutes } from './intake-routes.js';\nimport { IntakeRoutes } from './intake.js';\nimport { KnowledgeRoutes } from './knowledge.js';\nimport { OAuthRoutes } from './oauth.js';\nimport { createProjectSessionsReader } from './project-sessions.js';\nimport type { RouteAuth } from './route.js';\nimport { SkillRoutes } from './skills.js';\nimport { buildSourceControlSessionRoutes } from './source-control-sessions.js';\nimport { buildSourceControlSettingsRoutes } from './source-control-settings.js';\nimport { invalidateTenantCredentialSnapshots } from './tenant-credentials.js';\nimport { VoiceRoutes } from './voice.js';\nimport { WorkItemRoutes } from './work-items.js';\n\nconst MATERIALIZE_FAILURE_CODE = {\n 'git-missing': 'repository_git_missing',\n 'sandbox-unresponsive': 'repository_sandbox_unresponsive',\n 'egress-blocked': 'repository_egress_blocked',\n 'clone-failed': 'repository_clone_failed',\n 'pull-failed': 'repository_pull_failed',\n 'push-failed': 'repository_push_failed',\n 'commit-failed': 'repository_commit_failed',\n 'gh-missing': 'repository_cli_missing',\n 'pr-failed': 'repository_pr_failed',\n} satisfies Record<MaterializeError['code'], FactoryDispatchFailureCode>;\nexport interface IntegrationRegistration {\n integration: FactoryIntegration;\n ready: boolean;\n ensureReady: () => Promise<void>;\n}\n\nexport interface FactoryApiRoutesDeps {\n controllerId: string;\n controller: AgentController<MastraCodeState>;\n /** Registry of the sessions this process holds, owned by the host so it can watch them too. */\n liveSessions: LiveSessions;\n /** Request-auth seam threaded from the host (no service locator). */\n auth: RouteAuth;\n /** Optional user directory for resolving persisted owners to display profiles. */\n users?: Pick<IUserProvider, 'getUser' | 'getUsers'>;\n authStorage: AuthStorage;\n audit: AuditEmitter & AuditRecorder;\n fsRoot?: string;\n publicOrigin: string;\n stateSigner?: StateSigner;\n /** Sandbox surface (enablement, provider label, create callback). */\n sandbox?: FactorySandbox;\n /** Push hand-off for environment builds, present when the sandbox can build templates. */\n onRepositoryPush?: IntegrationHooks['onRepositoryPush'];\n /** Saved-environment hand-off for environment builds, present when the sandbox can build templates. */\n onEnvironmentSaved?: (projectId: string) => void;\n /** Root factory storage backend (distributed locks, app-db diagnostics). */\n factoryStorage?: FactoryStorage;\n integrationStorage: IntegrationStorage;\n sourceControlStorage: SourceControlStorage;\n /** App-table domain handles, registered and owned by `MastraFactory.prepare()`. */\n domains: {\n intake: IntakeStorage;\n modelCredentials: ModelCredentialsStorage;\n memorySettings: MemorySettingsStorage;\n customProviders: CustomProvidersStorage;\n modelDefaults: ModelDefaultsStorage;\n projects: FactoryProjectsStorage;\n queueHealth: QueueHealthStorage;\n workItems: WorkItemsStorage;\n channelIdentity: ChannelIdentityStorage;\n skillOverrides: SkillOverridesStorage;\n voiceSettings: VoiceSettingsStorage;\n };\n integrations?: IntegrationRegistration[];\n intakeReady: boolean;\n factoryReady: boolean;\n knowledgeEnabled: boolean;\n /** The Factory MCP endpoint is mounted; surfaced so the UI can show its URL. */\n mcpEnabled: boolean;\n /** Providers the operator opted in to run on the server process's own credentials. */\n deploymentModelProviders?: ReadonlySet<string>;\n /** App skills from `MastraFactory({ skills })`. */\n skills?: readonly InlineSkill[];\n knowledgeKey?: string;\n /** Resolved Factory rule set, threaded from the host (no service locator). */\n configVersion: string;\n /** Each project's boards; integrations use the code boards (`codeRegistry`). */\n boardRegistry: BoardRegistry | ProjectBoardSource;\n /** Forces an evaluator on every project; without it each project uses its own setting. */\n intakeEvaluator?: IntakeEvaluator;\n /** What forced `intakeEvaluator`. */\n intakeEvaluatorSource?: ForcedIntakeEvaluator['source'];\n /** Stored boards and their cache; mounts the board management routes when present. */\n storedBoards?: {\n storage: StoredBoardsStorage;\n cache: ProjectBoardCache;\n };\n factoryTransitionService?: FactoryTransitionService;\n sessionRetirement?: import('../sandbox/session-retirement.js').SessionRetirementCoordinator;\n /** Moves a thread with its observation vectors onto another memory resource. */\n moveThread?: (input: { threadId: string; resourceId: string }) => Promise<unknown>;\n /** This process's dispatcher run slots, for the run queue; `undefined` until the dispatcher exists. */\n runSlots?: () => { inUse: number; cap: number; interactive: { inUse: number; cap: number } } | undefined;\n onFactoryRuntime?: (runtime: {\n transitionService: FactoryTransitionService;\n startCoordinator: FactoryStartCoordinator;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n }) => void;\n}\n\nconst REPEAT_UNAVAILABLE_LOG_MS = 5 * 60_000;\n\nfunction guardIntegrationRoutes({\n integration,\n ready,\n ensureReady,\n routes,\n}: IntegrationRegistration & { routes: ApiRoute[] }): ApiRoute[] {\n if (ready) return routes;\n // Each retry throws a fresh error, so dedupe by message and repeat it periodically.\n let lastReported: { message: string; at: number } | undefined;\n const checkReady = async () => {\n try {\n await ensureReady();\n return undefined;\n } catch (error) {\n // The response only names a key mismatch, so this log is the only trace of any other cause.\n const message = String(error);\n const now = Date.now();\n if (lastReported?.message !== message || now - lastReported.at >= REPEAT_UNAVAILABLE_LOG_MS) {\n lastReported = { message, at: now };\n console.error(\n `[factory] ${integration.id} integration is unavailable: its storage failed to initialize:`,\n error,\n );\n }\n const cause =\n secretKeyMismatchHint(error) ??\n `Its storage failed to start. The server log line \"[factory] ${integration.id} integration is unavailable\" has the cause.`;\n return { error: 'integration_unavailable', message: `${integration.id} integration is unavailable. ${cause}` };\n }\n };\n return routes.map(route => {\n if ('handler' in route) {\n const handler = route.handler;\n return {\n ...route,\n handler: async (context: Parameters<typeof handler>[0]) => {\n const unavailable = await checkReady();\n if (unavailable) return context.json(unavailable, 503);\n return handler(context, async () => {});\n },\n };\n }\n\n const createHandler = route.createHandler;\n return {\n ...route,\n createHandler: async (args: Parameters<typeof createHandler>[0]) => {\n const handler = await createHandler(args);\n return async (context: Parameters<typeof handler>[0]) => {\n const unavailable = await checkReady();\n if (unavailable) return context.json(unavailable, 503);\n return handler(context);\n };\n },\n };\n });\n}\n\n/**\n * Resolve the source-control session the work item already holds for this role,\n * when it still resolves to the item's org and factory project. Returns\n * `undefined` when there is no ref or the ref no longer resolves, so the caller\n * falls back to minting one.\n */\nasync function reuseBoundSession(\n sourceControl: SourceControlStorageHandle,\n input: FactoryBindingPreparationInput,\n role: string = input.role,\n): Promise<EnsuredFactorySourceSession | undefined> {\n const ref = input.item.sessions[role];\n if (!ref) return undefined;\n // At least as strict as the coordinator's resolveSourceSession: a ref it\n // would reject must fall through to minting, not hard-fail the run.\n const session = await sourceControl.sessions.getBySessionId(ref.sessionId);\n if (\n !session?.projectRepositoryId ||\n session.orgId !== input.record.orgId ||\n session.factoryProjectId !== input.record.factoryProjectId\n ) {\n return undefined;\n }\n return {\n sessionId: session.sessionId,\n userId: session.userId,\n projectRepositoryId: session.projectRepositoryId,\n branch: session.branch,\n baseBranch: session.baseBranch,\n };\n}\n\n/**\n * Work cards planned before Planning moved into the `work` context hold the\n * plan's session under `plan`. Building continues in it, on the same branch and\n * repository a fresh session would use, so those cards keep the plan's context.\n */\nasync function legacyPlanSession(\n sourceControl: SourceControlStorageHandle,\n input: FactoryBindingPreparationInput,\n boardId: string,\n branch: string,\n projectRepositoryId: string,\n): Promise<EnsuredFactorySourceSession | undefined> {\n const legacyRole = legacyPlanRoleFor(boardId, input.role);\n if (!legacyRole) return undefined;\n const session = await reuseBoundSession(sourceControl, input, legacyRole);\n if (\n session &&\n (session.branch === branch || session.branch === legacyGithubWorkItemBranch(branch)) &&\n session.projectRepositoryId === projectRepositoryId\n ) {\n return session;\n }\n return undefined;\n}\n\nfunction sameBranch(held: string, branch: string): boolean {\n return held === branch || held === legacyGithubWorkItemBranch(branch);\n}\n\n/** The branch a binding's session works on: the reviewed pull request's for PR review of an attached one. */\nfunction reviewBranch(\n input: FactoryBindingPreparationInput,\n board: InstalledBoard | undefined,\n stage: string,\n source: WorkItemBranchSource,\n): string {\n const metadata = input.item.workItem.metadata;\n if (input.role === REVIEW_CONTEXT && isPullRequestReviewPhase(board, stage)) {\n const change = reviewedChangeRequest({ ...input.item, source });\n if (change && !change.standalone && change.number !== undefined) {\n return pullRequestBranch({ id: input.item.id, provider: change.provider, number: change.number });\n }\n }\n return workItemBranch({ id: input.item.id, source, metadata });\n}\n\n/**\n * The lane a run started on a resting card moves it to: a review of a card with a pull request\n * goes to the board's pull request review; otherwise the first phase that runs in the role's\n * context. Work's phases share contexts, so its roles keep their own lanes: `work` builds and\n * the old `plan` role plans.\n */\nfunction restingExitLane(board: InstalledBoard | undefined, role: string, hasPullRequest: boolean): string | undefined {\n const pullRequestReview = boardFlow(board).pullRequestReview;\n if (hasPullRequest && role === REVIEW_CONTEXT && pullRequestReview) return pullRequestReview;\n return workLaneForRole(board, role) ?? board?.phaseForRole(role);\n}\n\n/** What the autonomous start reads to decide who a phase session runs as. */\nexport interface PhaseSessionOwnerSources extends OrganizationModelSources {\n workItems?: Pick<WorkItemsStorage, 'findRunBindingById'>;\n}\n\n/**\n * Who a newly minted phase session runs as. Wherever runs use the Factory's credentials\n * that is the Factory itself, whoever moved the card: the mover is the actor on the move,\n * not the owner of the run. A Factory whose runs use personal credentials has no keys of\n * its own, so there a person owns the run: whoever moved or approved the card, or the user\n * of the session whose agent moved it, else whoever created the Factory. `undefined`\n * leaves the last resort to the caller: whoever connected the repository.\n */\nasync function phaseSessionOwner(args: {\n sourceControl: SourceControlStorageHandle;\n workItems: Pick<WorkItemsStorage, 'findRunBindingById'> | undefined;\n project: FactoryProject;\n approver: string | undefined;\n}): Promise<string | undefined> {\n const { sourceControl, workItems, project, approver } = args;\n if (effectiveModelScope(project.modelScope, 'run') === 'factory') return factoryPrincipalId(project.id);\n if (approver?.startsWith('agent:')) {\n // `agent:session:<sessionId>` is a person's own session; `agent:<bindingId>` a phase run.\n const ref = approver.slice('agent:'.length);\n const sessionId = ref.startsWith('session:')\n ? ref.slice('session:'.length)\n : (await workItems?.findRunBindingById({ orgId: project.orgId, factoryProjectId: project.id, id: ref }))\n ?.sessionId;\n const session = sessionId ? await sourceControl.sessions.getBySessionId(sessionId) : null;\n if (session && session.orgId === project.orgId && isHumanActorId(session.userId)) return session.userId;\n } else if (isHumanActorId(approver)) {\n return approver;\n }\n return isHumanActorId(project.createdBy) ? project.createdBy : undefined;\n}\n\n/**\n * Who started the work, as the move that starts the run records them. An agent stays an\n * agent: recorded as a person, its move would count as a person accepting the work.\n */\nasync function starterOf(\n workItems: Pick<WorkItemsStorage, 'findRunBindingById'> | undefined,\n project: Pick<FactoryProject, 'id' | 'orgId'>,\n approver: string,\n): Promise<FactoryRuleActor> {\n if (!approver.startsWith('agent:')) return { type: 'human', id: approver };\n const bindingId = approver.slice('agent:'.length);\n if (bindingId.startsWith('session:')) return { type: 'agent', bindingId, role: 'session' };\n const binding = await workItems?.findRunBindingById({\n orgId: project.orgId,\n factoryProjectId: project.id,\n id: bindingId,\n });\n return { type: 'agent', bindingId, role: binding?.role ?? 'agent' };\n}\n\n/**\n * Start a factory run for a rule binding: ensure the source-control session the\n * coordinator requires, then hand it to `prepare` along with the factory's\n * default model. Exported for tests — this is the autonomous entry point with no\n * browser and no interactive user, so nothing else would catch a regression in\n * what it forwards.\n */\nexport async function prepareFactoryRuleBinding(\n sourceControlProvider: SourceControlStorageHandle | Pick<GithubIntegration, 'sourceControlStorage'>,\n coordinator: Pick<FactoryStartCoordinator, 'prepare'>,\n projects: FactoryProjectsStorage,\n boards: BoardRegistry | ProjectBoardSource,\n input: FactoryBindingPreparationInput,\n intake?: Pick<IntakeStorage, 'getConfig'>,\n owner?: PhaseSessionOwnerSources,\n): Promise<void> {\n try {\n const sourceControl =\n 'sourceControlStorage' in sourceControlProvider\n ? sourceControlProvider.sourceControlStorage\n : sourceControlProvider;\n const source = workItemBranchSource(input.item.externalSource);\n // Only leaving a resting phase derives a lane from the role: roles don't own lanes,\n // and the Done close-out running in the triage seat must not drag the card back.\n // Both the current phase and the role's lane come from the installed board; an\n // unknown board or phase yields no destination rather than a guessed one.\n const boardId = boardForWorkItem(input.item);\n const board = (await toBoardSource(boards).load(input.record)).get(boardId);\n const currentStage = input.item.stages.length === 1 ? input.item.stages[0] : undefined;\n const currentKind = currentStage === undefined ? undefined : board?.phaseKind(currentStage);\n const destinationStage =\n currentKind === undefined\n ? undefined\n : currentKind === 'resting'\n ? restingExitLane(board, input.role, hasPullRequest({ ...input.item, source }))\n : currentStage;\n if (!destinationStage) {\n throw new FactoryDispatchError(\n 'unsupported_provider_item',\n `Factory skill invocation has no destination lane (role \"${input.role}\", stages [${input.item.stages.join(', ')}]).`,\n );\n }\n // A PR review on an issue card checks the pull request out on its own branch, apart from\n // the builder's issue branch; every other seat works on the card's own branch.\n const branch = reviewBranch(input, board, destinationStage, source);\n const connections = await sourceControl.connections.list({\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n });\n if (!connections.some(connection => connection.integrationId === sourceControl.integrationId)) {\n throw new FactoryDispatchError('source_control_missing', 'Factory source-control connection not found.');\n }\n const project = await projects.getById({ id: input.record.factoryProjectId });\n if (!project || project.orgId !== input.record.orgId) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n `Factory model policy is unavailable for project ${input.record.factoryProjectId}.`,\n );\n }\n // A retry may already own a role session; a card that names no repository stays in it.\n const reusable = await reuseBoundSession(sourceControl, input);\n // The review seat moves between branches on one card (self-review on the builder's branch,\n // PR review on each pull request's), so its session is reused only on the branch it holds.\n const boundSession =\n reusable && input.role === REVIEW_CONTEXT && !sameBranch(reusable.branch, branch) ? undefined : reusable;\n const intakeConfig = await intake?.getConfig({ orgId: input.record.orgId, integrationIds: ['linear'] });\n // A card that names no repository keeps a retry in its role session's\n // repository, else starts in the environment's first one; its agent\n // determines which repository the card belongs to. An explicit signal is\n // never overridden.\n const repository = await resolveRunRepository({\n sourceControl,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n item: input.item,\n linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject,\n ...(boundSession ? { boundProjectRepositoryId: boundSession.projectRepositoryId } : {}),\n });\n if (repository.status !== 'resolved') {\n throw new FactoryDispatchError('source_repository_ambiguous', repository.hint);\n }\n // Re-preparing a binding (server restart, retired controller session) must\n // land in the role's existing session: minting a replacement would repoint\n // the work item, flip the session's owner to the approver, and orphan the\n // previous sandbox. A session may work on a card outside its own repository\n // only when a run recorded that repository on a card that named none.\n const approver = input.record.approvedBy ?? undefined;\n if (\n boundSession &&\n boundSession.projectRepositoryId !== repository.projectRepositoryId &&\n !repositoryChosenByRun(input.item, repository.slug)\n ) {\n throw new FactoryDispatchError(\n 'source_repository_ambiguous',\n `The existing session is bound to a different repository than ${repository.slug}. Set the card's repository back, or end that session and retry.`,\n );\n }\n // The session is filed under the card's repository, or the environment's\n // first one when the card names none: the sandbox holds every environment\n // repository, but the coordinator, the PR tools and the subscriptions\n // follow the session's link.\n const existingSession =\n boundSession ?? (await legacyPlanSession(sourceControl, input, boardId, branch, repository.projectRepositoryId));\n const ownerUserId =\n existingSession?.userId ??\n (await phaseSessionOwner({ sourceControl, workItems: owner?.workItems, project, approver }));\n if (isFactoryPrincipalId(ownerUserId)) await requireOrganizationModelKey(owner, project);\n const preparedSession =\n existingSession ??\n (await ensureFactorySourceSession({\n sourceControl,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n projectRepositoryId: repository.projectRepositoryId,\n branch,\n attributeToUserId: ownerUserId,\n }).catch(error => {\n if (error instanceof FactorySourceSessionResolutionError && error.reason === 'repository') {\n // The card resolved to a linked repository the sandbox will not check out.\n throw new FactoryDispatchError(\n 'source_repository_missing',\n `Repository ${repository.slug} is linked but not pre-cloned for this Factory. Turn on Pre-clone under Settings → Repositories, then retry.`,\n { cause: error },\n );\n }\n if (error instanceof SessionBranchHeldError) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n `${error.message} The run cannot start until branch ${branch} is free for this repository.`,\n { cause: error },\n );\n }\n if (!(error instanceof SessionOwnershipMismatchError)) throw error;\n throw new FactoryDispatchError(\n 'session_unavailable',\n `Session ${error.sessionId} on branch ${branch} predates factory ownership and cannot be reused. Delete that session, then retry.`,\n { cause: error },\n );\n }));\n\n const modelScope = effectiveModelScope(project.modelScope, 'run');\n await coordinator.prepare({\n orgId: input.record.orgId,\n userId: preparedSession.userId,\n ...(approver ? { startedBy: await starterOf(owner?.workItems, project, approver) } : {}),\n factoryProjectId: input.record.factoryProjectId,\n sessionId: preparedSession.sessionId,\n expectedBindingId: input.expectedBindingId,\n modelScope,\n defaultModelId: modelScope === 'factory' ? (project.defaultModelId ?? undefined) : undefined,\n threadTitle: workItemThreadTitle({ source, title: input.item.title, metadata: input.item.workItem.metadata }),\n kickoffKey: input.record.id,\n destinationStage,\n workItem: {\n id: input.item.id,\n role: input.role,\n input: {\n externalSource: input.item.externalSource,\n parentWorkItemId: input.item.parentWorkItemId,\n title: input.item.title,\n stages: [...input.item.stages],\n sessions: input.item.sessions,\n metadata: input.item.metadata,\n },\n },\n });\n } catch (error) {\n if (error instanceof FactoryDispatchError) throw error;\n if (error instanceof FactorySourceSessionResolutionError) {\n const code = error.reason === 'connection' ? 'source_control_missing' : 'source_repository_missing';\n throw new FactoryDispatchError(code, error.message, { cause: error });\n }\n if (error instanceof SourceControlConnectionNotFoundError) {\n throw new FactoryDispatchError('source_control_missing', error.message, { cause: error });\n }\n if (error instanceof MaterializeError) {\n throw new FactoryDispatchError(MATERIALIZE_FAILURE_CODE[error.code], error.message, { cause: error });\n }\n throw error;\n }\n}\n\n/**\n * Build the {@link IntegrationContext} handed to an integration when the\n * factory collects its capabilities (routes, workers). One shape everywhere:\n * `assembleFactoryApiRoutes` uses it per registration, and `MastraFactory` uses it\n * when collecting integration workers at finalize.\n */\nexport function buildIntegrationContext(\n deps: Pick<\n FactoryApiRoutesDeps,\n | 'controller'\n | 'publicOrigin'\n | 'auth'\n | 'sandbox'\n | 'users'\n | 'factoryStorage'\n | 'integrationStorage'\n | 'sourceControlStorage'\n | 'integrations'\n > & {\n stateSigner: StateSigner;\n emitAudit?: AuditEmitter['emit'];\n onRepositoryPush?: IntegrationHooks['onRepositoryPush'];\n configVersion: string;\n boardRegistry: BoardRegistry | ProjectBoardSource;\n /** Passed for the workers' context only: routes do not sweep. */\n keptCards?: CardSource;\n /** Which items intake turned away, so integrations run intake again when one changes. */\n notRouted?: NotRoutedLookup;\n factoryReady: boolean;\n domains: Pick<\n FactoryApiRoutesDeps['domains'],\n | 'projects'\n | 'intake'\n | 'workItems'\n | 'channelIdentity'\n | 'memorySettings'\n | 'modelDefaults'\n | 'modelCredentials'\n | 'voiceSettings'\n >;\n /**\n * Stable id of the registered source-control-owning integration (today:\n * `'github'` when registered). Every call site must derive and pass it so\n * `routes()`, `channels()`, and `workers()` all see the same context shape.\n */\n sourceControlOwnerId?: string;\n },\n integrationId: string,\n): IntegrationContext {\n return {\n auth: deps.auth,\n sandbox: deps.sandbox,\n ...(deps.users ? { users: deps.users } : {}),\n factoryStorage: deps.factoryStorage,\n baseUrl: deps.publicOrigin,\n controller: deps.controller,\n stateSigner: deps.stateSigner,\n storage: {\n generic: deps.integrationStorage.forIntegration(integrationId),\n sourceControl: deps.sourceControlStorage.forIntegration(integrationId),\n ...(deps.sourceControlOwnerId\n ? { sourceControlOwner: deps.sourceControlStorage.forIntegration(deps.sourceControlOwnerId) }\n : {}),\n sourceControls: (deps.integrations ?? [])\n .filter(({ integration }) => integration.versionControl)\n .map(({ integration }) => deps.sourceControlStorage.forIntegration(integration.id)),\n projects: deps.domains.projects,\n intake: deps.domains.intake,\n channelIdentity: deps.domains.channelIdentity,\n memorySettings: deps.domains.memorySettings,\n modelDefaults: deps.domains.modelDefaults,\n modelCredentials: deps.domains.modelCredentials,\n voiceSettings: deps.domains.voiceSettings,\n },\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n ...(deps.factoryReady\n ? {\n runtime: {\n configVersion: deps.configVersion,\n workItems: deps.domains.workItems,\n boards: deps.boardRegistry,\n ...(deps.keptCards ? { keptCards: deps.keptCards } : {}),\n ...(deps.notRouted ? { notRouted: deps.notRouted } : {}),\n },\n }\n : {}),\n ...(deps.emitAudit || deps.onRepositoryPush\n ? {\n hooks: {\n ...(deps.emitAudit ? { emitAudit: deps.emitAudit } : {}),\n ...(deps.onRepositoryPush ? { onRepositoryPush: deps.onRepositoryPush } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * Disabled-status stub for the well-known integration ids. The SPA polls\n * `/web/github/status`, `/web/linear/status`, and `/web/jira/status`\n * unconditionally, so when an integration is absent (or not ready) the status\n * contract must still hold. Unknown custom ids get no stub — the SPA doesn't\n * poll them.\n */\nfunction disabledIntegrationStatusRoutes(deps: FactoryApiRoutesDeps, id: string, configured = false): ApiRoute[] {\n if (id === 'github') {\n return [\n registerApiRoute('/web/github/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n installations: [],\n reason: 'missing_config',\n diagnostics: getGithubFeatureDiagnostics({\n github: undefined,\n auth: deps.auth,\n appDbConfigured: deps.factoryStorage !== undefined,\n stateSigner: deps.stateSigner,\n sandbox: deps.sandbox,\n }),\n }),\n }),\n ];\n }\n if (id === 'linear') {\n return [\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n workspace: null,\n reason: 'missing_config',\n diagnostics: {\n linearAppConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: true,\n },\n }),\n }),\n ];\n }\n if (id === 'jira') {\n return [\n registerApiRoute('/web/jira/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n configured,\n site: null,\n reason: 'missing_config',\n diagnostics: {\n jiraConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: deps.factoryStorage !== undefined,\n },\n }),\n }),\n ];\n }\n return [];\n}\n\n/**\n * Stub for `GET /web/channel-accounts` when NO Slack integration is\n * registered. The SPA's Connections section polls the path unconditionally;\n * without a stub the SPA fallback serves HTML, which the UI can only read as\n * \"old server / unknown\". The machine-readable reason lets it say the truth:\n * the integration isn't registered.\n *\n * Mounted only for ABSENT slack — a registered integration owns the path via\n * its connect routes (or, when the state signer is unstable, gets no routes\n * at all and the UI falls back to the generic copy). Static payload, leaks\n * nothing → no auth needed, same posture as the github/linear stubs.\n */\nfunction absentSlackChannelAccountsRoutes(): ApiRoute[] {\n return [\n registerApiRoute('/web/channel-accounts', {\n method: 'GET',\n requiresAuth: false,\n handler: c => c.json({ accounts: [], canConnect: false, reason: 'not_registered' }),\n }),\n ];\n}\n\nexport interface FactoryStatusProblem {\n code: 'secret_key_mismatch';\n title: string;\n message: string;\n /** The one step that fixes it. Env var names are wrapped in backticks. */\n fix: string;\n /** Where an operator reads more, such as how to rotate keys. */\n docsUrl: string;\n}\n\n/** Domains that hold encrypted secrets; Factory can't run if they can't be read. */\nconst SECRET_DOMAINS = ['integrations', 'model-credentials', 'custom-providers'];\n\n/**\n * `GET /web/status`: problems that stop the whole Factory from working, so the\n * UI shows one alert banner instead of every page failing on its own. Only a\n * key problem counts, since only a redeploy with the right key clears it. Read\n * from the latest storage init result, so a key failure found by a later init\n * retry shows up too. Only client-safe copy goes out.\n */\nfunction factoryStatusRoutes(storage: FactoryStorage | undefined): ApiRoute[] {\n return [\n registerApiRoute('/web/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c => {\n const problem = SECRET_DOMAINS.map(domain => secretKeyProblem(storage?.domainInitError(domain))).find(Boolean);\n const problems: FactoryStatusProblem[] = problem\n ? [\n {\n code: 'secret_key_mismatch',\n ...problem,\n docsUrl: 'https://factory.mastra.ai/troubleshooting#stored-credentials-stop-working',\n },\n ]\n : [];\n return c.json({ problems });\n },\n }),\n ];\n}\n\n/**\n * Assemble the custom `/web/*` API routes as Mastra `server.apiRoutes`:\n * - fs browser routes (project picker), confined to `fsRoot`\n * - config routes (provider/API-key/default-model/OM management)\n * - every registered integration's `routes()` surface (full set when ready,\n * disabled-status stub otherwise), plus stubs for absent known ids\n */\nexport function assembleFactoryApiRoutes(deps: FactoryApiRoutesDeps): ApiRoute[] {\n const emitAudit: AuditEmitter['emit'] = args => deps.audit.emit(args);\n const registrations = deps.integrations ?? [];\n const githubRegistration = registrations.find(({ integration }) => integration.id === 'github');\n const githubStorage = githubRegistration ? deps.sourceControlStorage.forIntegration('github') : undefined;\n const githubIntegration = githubRegistration?.integration as GithubIntegration | undefined;\n const sourceControlRegistrations = registrations.filter(({ integration }) => integration.versionControl);\n const sourceControlIntegrationIds = [\n ...new Set(['github', ...sourceControlRegistrations.map(({ integration }) => integration.id)]),\n ];\n const sourceControls = sourceControlIntegrationIds.map(id => deps.sourceControlStorage.forIntegration(id));\n const sourceControlSessions = createSourceControlSessionLookup(sourceControls);\n const projectSessions = createProjectSessionsReader({\n sourceControls,\n ...(deps.users ? { users: deps.users } : {}),\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n });\n\n const integrationRoutes = registrations.flatMap(registration => {\n const { integration } = registration;\n if (!deps.stateSigner) return disabledIntegrationStatusRoutes(deps, integration.id, true);\n const context = buildIntegrationContext(\n {\n ...deps,\n // Integrations evaluate code behaviors and place new cards with the code boards.\n boardRegistry: toBoardSource(deps.boardRegistry).codeRegistry,\n ...(deps.storedBoards ? { notRouted: deps.storedBoards.storage } : {}),\n stateSigner: deps.stateSigner,\n emitAudit,\n ...(githubRegistration ? { sourceControlOwnerId: 'github' } : {}),\n },\n integration.id,\n );\n return guardIntegrationRoutes({ ...registration, routes: integration.routes(context) });\n });\n const sourceControlSessionRoutes =\n sourceControls.length === 0\n ? []\n : buildSourceControlSessionRoutes({\n auth: deps.auth,\n sourceControls,\n projects: deps.domains.projects,\n ...(deps.users ? { users: deps.users } : {}),\n projectSessions,\n controller: deps.controller,\n audit: deps.audit,\n memorySettings: deps.domains.memorySettings,\n sessionRetirement: deps.sessionRetirement,\n // A local sandbox's destroy keeps the session directory, so recreate\n // couldn't deliver the fresh checkout it promises there.\n sandboxRecreateSupported: deps.sandbox !== undefined && deps.sandbox.provider !== 'local',\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n ...(deps.moveThread ? { moveThread: deps.moveThread } : {}),\n ...(githubStorage ? { githubRepositories: githubStorage.repositories } : {}),\n });\n // Absent known integrations still get their disabled-status stub.\n const absentStubs = ['github', 'linear', 'jira']\n .filter(id => !registrations.some(({ integration }) => integration.id === id))\n .flatMap(id => disabledIntegrationStatusRoutes(deps, id));\n // Absent slack gets the channel-accounts not-registered stub (registered\n // slack owns the path via its own connect routes).\n const slackAbsentStubs = registrations.some(({ integration }) => integration.id === 'slack')\n ? []\n : absentSlackChannelAccountsRoutes();\n\n const transitionService = deps.factoryReady\n ? (deps.factoryTransitionService ??\n new FactoryTransitionService({\n configVersion: deps.configVersion,\n boards: deps.boardRegistry,\n storage: deps.domains.workItems,\n audit: deps.audit,\n }))\n : undefined;\n const startCoordinator = transitionService\n ? new FactoryStartCoordinator(\n deps.controller,\n deps.domains.workItems,\n transitionService,\n request =>\n resolveFactorySourceControl({\n sourceControls,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n sessionId: request.sessionId,\n }),\n deps.domains.intake,\n { projects: deps.domains.projects, modelDefaults: deps.domains.modelDefaults },\n deps.boardRegistry,\n )\n : undefined;\n if (transitionService && startCoordinator) {\n deps.onFactoryRuntime?.({\n transitionService,\n startCoordinator,\n ...(sourceControlRegistrations.length > 0\n ? {\n prepareBinding: async (input: FactoryBindingPreparationInput) => {\n const sourceControl = await resolveFactorySourceControl({\n sourceControls,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n });\n if (!sourceControl) {\n throw new FactoryDispatchError(\n 'source_control_missing',\n 'Factory project has no linked source-control repository.',\n );\n }\n return prepareFactoryRuleBinding(\n sourceControl,\n startCoordinator,\n deps.domains.projects,\n deps.boardRegistry,\n input,\n deps.domains.intake,\n {\n workItems: deps.domains.workItems,\n modelCredentials: deps.domains.modelCredentials,\n customProviders: deps.domains.customProviders,\n deploymentModelProviders: deps.deploymentModelProviders,\n },\n );\n },\n }\n : {}),\n });\n }\n\n return [\n ...factoryStatusRoutes(deps.factoryStorage),\n ...buildFsRoutes({\n root: deps.fsRoot,\n sessionFs: {\n auth: deps.auth,\n sessions: sourceControlSessions,\n controller: deps.controller,\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n },\n }),\n ...new ConfigRoutes({\n auth: deps.auth,\n controller: deps.controller,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n modelDefaults: deps.domains.modelDefaults,\n sourceControlSessions,\n sourceControls,\n workItems: deps.domains.workItems,\n memorySettings: deps.domains.memorySettings,\n factoryProjects: deps.domains.projects,\n customProviders: deps.domains.customProviders,\n features: { knowledge: deps.knowledgeEnabled, mcp: deps.mcpEnabled },\n deploymentProviders: deps.deploymentModelProviders,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n onCustomProvidersChanged: invalidateCustomProvidersSnapshots,\n }).routes(),\n ...new OAuthRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n }).routes(),\n ...new VoiceRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n voiceSettings: deps.domains.voiceSettings,\n factoryProjects: deps.domains.projects,\n }).routes(),\n ...new SkillRoutes({\n auth: deps.auth,\n controllerId: deps.controllerId,\n controller: deps.controller,\n sourceControlStorage: githubStorage,\n ensureSourceControlReady: githubRegistration?.ensureReady,\n ...(deps.skills ? { skills: deps.skills } : {}),\n overrides: { projects: deps.domains.projects, storage: deps.domains.skillOverrides, audit: deps.audit },\n }).routes(),\n ...sourceControlSessionRoutes,\n ...(sourceControls.length === 0\n ? []\n : buildSourceControlSettingsRoutes({\n auth: deps.auth,\n sourceControls,\n ...(deps.onEnvironmentSaved ? { onEnvironmentSaved: deps.onEnvironmentSaved } : {}),\n })),\n ...integrationRoutes,\n ...absentStubs,\n ...slackAbsentStubs,\n ...(deps.intakeReady\n ? new IntakeRoutes({\n auth: deps.auth,\n audit: deps.audit,\n intake: deps.domains.intake,\n projects: deps.domains.projects,\n integrations: (deps.integrations ?? []).flatMap(({ integration }) => [\n ...(integration.intake ? [{ id: integration.id, intake: integration.intake }] : []),\n ...(integration.additionalIntakes ?? []),\n ]),\n }).routes()\n : []),\n ...(deps.factoryReady && deps.knowledgeEnabled\n ? new KnowledgeRoutes({\n auth: deps.auth,\n projects: deps.domains.projects,\n knowledge: async key => deps.controller.getMastra()?.getKnowledge(key),\n defaultKnowledgeKey: deps.knowledgeKey,\n }).routes()\n : []),\n ...(deps.factoryReady\n ? new WorkItemRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n boardRegistry: deps.boardRegistry,\n intakeRoutes: deps.storedBoards?.storage,\n intakeEvaluator: deps.intakeEvaluator,\n queueHealth: deps.domains.queueHealth,\n transitionService,\n startCoordinator,\n liveSessions: deps.liveSessions,\n runSlots: deps.runSlots,\n projectSessions,\n activeRuns: () => deps.controller.listActiveThreadRuns(),\n }).routes()\n : []),\n ...(deps.factoryReady && deps.storedBoards\n ? new BoardRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n storage: deps.storedBoards.storage,\n boards: deps.storedBoards.cache,\n }).routes()\n : []),\n ...(deps.factoryReady && deps.storedBoards\n ? new IntakeRouteRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n storage: deps.storedBoards.storage,\n boards: deps.storedBoards.cache,\n intakeEvaluator: deps.intakeEvaluator,\n intakeEvaluatorSource: deps.intakeEvaluatorSource,\n intakeLookups: (deps.integrations ?? []).flatMap(({ integration, ready }) =>\n ready && integration.intakeLookup ? [integration.intakeLookup] : [],\n ),\n }).routes()\n : []),\n ...(deps.factoryReady\n ? buildAutomationRunRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n boards: deps.boardRegistry,\n })\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,MAAM,2BAA2B;CAC/B,eAAe;CACf,wBAAwB;CACxB,kBAAkB;CAClB,gBAAgB;CAChB,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AAK,eACL,yBAAyB;GACvB,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,QAAQ,KAAK;EACf,CAAC,IACD,CAAC;CACP;AACF"}
1
+ {"version":3,"file":"surface.js","names":[],"sources":["../../src/routes/surface.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { ApiRoute, IUserProvider } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { InlineSkill } from '@mastra/core/skills';\nimport type { FactoryStorage } from '@mastra/core/storage';\nimport type { FactorySandbox } from '@mastra/core/workspace';\n\nimport {\n boardFlow,\n boardForWorkItem,\n hasPullRequest,\n isPullRequestReviewPhase,\n REVIEW_CONTEXT,\n reviewedChangeRequest,\n} from '../boards/index.js';\nimport type { BoardRegistry, InstalledBoard } from '../boards/index.js';\nimport type { ForcedIntakeEvaluator } from '../boards/intake-routing.js';\nimport { legacyPlanRoleFor, workLaneForRole } from '../boards/legacy-plan-role.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardCache, ProjectBoardSource } from '../boards/project-boards.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationHooks } from '../integrations/base.js';\nimport { getGithubFeatureDiagnostics } from '../integrations/github/config.js';\nimport type { GithubIntegration } from '../integrations/github/integration.js';\nimport { MaterializeError } from '../integrations/github/sandbox.js';\nimport type { CardSource } from '../integrations/kept-cards.js';\nimport { FactoryDispatchError } from '../rules/dispatch-errors.js';\nimport type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';\nimport type { NotRoutedLookup } from '../rules/event-rules.js';\nimport { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { FactoryTransitionService } from '../rules/transition-service.js';\nimport { workItemSource } from '../rules/types.js';\nimport type { FactoryRuleActor } from '../rules/types.js';\nimport { secretKeyMismatchHint, secretKeyProblem } from '../secret-encryption.js';\nimport {\n createSourceControlSessionLookup,\n ensureFactorySourceSession,\n FactorySourceSessionResolutionError,\n resolveFactorySourceControl,\n requireOrganizationModelKey,\n} from '../session/factory-session.js';\nimport type { EnsuredFactorySourceSession, OrganizationModelSources } from '../session/factory-session.js';\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport { repositoryChosenByRun, resolveRunRepositoryFromIntake } from '../session/work-item-repository.js';\nimport type { StateSigner } from '../state-signing.js';\nimport { isHumanActorId } from '../storage/domains/audit/actors.js';\nimport type { AuditEmitter, AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { IntakeEvaluator, StoredBoardsStorage } from '../storage/domains/boards/base.js';\nimport type { ChannelIdentityStorage } from '../storage/domains/channel-identity/base.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { IntegrationStorage } from '../storage/domains/integrations/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope, factoryPrincipalId, isFactoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport type { SkillOverridesStorage } from '../storage/domains/skill-overrides/base.js';\nimport {\n SessionBranchHeldError,\n SessionOwnershipMismatchError,\n SourceControlConnectionNotFoundError,\n} from '../storage/domains/source-control/base.js';\nimport type { SourceControlStorage, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { VoiceSettingsStorage } from '../storage/domains/voice-settings/base.js';\nimport type { FactoryDispatchFailureCode, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport {\n legacyGithubWorkItemBranch,\n pullRequestBranch,\n workItemBranch,\n workItemBranchSource,\n workItemThreadTitle,\n} from '../work-item-branch.js';\nimport type { WorkItemBranchSource } from '../work-item-branch.js';\nimport { buildAutomationRunRoutes } from './automation-runs.js';\nimport { BoardRoutes } from './boards.js';\nimport { ConfigRoutes } from './config.js';\nimport { invalidateCustomProvidersSnapshots } from './custom-provider-source.js';\nimport { buildFsRoutes } from './fs.js';\nimport { IntakeRouteRoutes } from './intake-routes.js';\nimport { IntakeRoutes } from './intake.js';\nimport type { IntakeRoutesDeps } from './intake.js';\nimport { KnowledgeRoutes } from './knowledge.js';\nimport { OAuthRoutes } from './oauth.js';\nimport { createProjectSessionsReader } from './project-sessions.js';\nimport type { RouteAuth } from './route.js';\nimport { SkillRoutes } from './skills.js';\nimport { buildSourceControlSessionRoutes } from './source-control-sessions.js';\nimport { buildSourceControlSettingsRoutes } from './source-control-settings.js';\nimport { invalidateTenantCredentialSnapshots } from './tenant-credentials.js';\nimport { VoiceRoutes } from './voice.js';\nimport { WorkItemRoutes } from './work-items.js';\n\nconst MATERIALIZE_FAILURE_CODE = {\n 'git-missing': 'repository_git_missing',\n 'sandbox-unresponsive': 'repository_sandbox_unresponsive',\n 'egress-blocked': 'repository_egress_blocked',\n 'clone-failed': 'repository_clone_failed',\n 'pull-failed': 'repository_pull_failed',\n 'push-failed': 'repository_push_failed',\n 'commit-failed': 'repository_commit_failed',\n 'gh-missing': 'repository_cli_missing',\n 'pr-failed': 'repository_pr_failed',\n} satisfies Record<MaterializeError['code'], FactoryDispatchFailureCode>;\nexport interface IntegrationRegistration {\n integration: FactoryIntegration;\n ready: boolean;\n ensureReady: () => Promise<void>;\n}\n\nexport interface FactoryApiRoutesDeps {\n controllerId: string;\n controller: AgentController<MastraCodeState>;\n /** Registry of the sessions this process holds, owned by the host so it can watch them too. */\n liveSessions: LiveSessions;\n /** Request-auth seam threaded from the host (no service locator). */\n auth: RouteAuth;\n /** Optional user directory for resolving persisted owners to display profiles. */\n users?: Pick<IUserProvider, 'getUser' | 'getUsers'>;\n authStorage: AuthStorage;\n audit: AuditEmitter & AuditRecorder;\n fsRoot?: string;\n publicOrigin: string;\n stateSigner?: StateSigner;\n /** Sandbox surface (enablement, provider label, create callback). */\n sandbox?: FactorySandbox;\n /** Push hand-off for environment builds, present when the sandbox can build templates. */\n onRepositoryPush?: IntegrationHooks['onRepositoryPush'];\n /** Saved-environment hand-off for environment builds, present when the sandbox can build templates. */\n onEnvironmentSaved?: (projectId: string) => void;\n /** Sources newly selected in Work Intake, so their existing items can be brought in. */\n onIntakeSourcesSelected?: IntakeRoutesDeps['onSourcesSelected'];\n /** Root factory storage backend (distributed locks, app-db diagnostics). */\n factoryStorage?: FactoryStorage;\n integrationStorage: IntegrationStorage;\n sourceControlStorage: SourceControlStorage;\n /** App-table domain handles, registered and owned by `MastraFactory.prepare()`. */\n domains: {\n intake: IntakeStorage;\n modelCredentials: ModelCredentialsStorage;\n memorySettings: MemorySettingsStorage;\n customProviders: CustomProvidersStorage;\n modelDefaults: ModelDefaultsStorage;\n projects: FactoryProjectsStorage;\n queueHealth: QueueHealthStorage;\n workItems: WorkItemsStorage;\n channelIdentity: ChannelIdentityStorage;\n skillOverrides: SkillOverridesStorage;\n voiceSettings: VoiceSettingsStorage;\n };\n integrations?: IntegrationRegistration[];\n intakeReady: boolean;\n factoryReady: boolean;\n knowledgeEnabled: boolean;\n /** The Factory MCP endpoint is mounted; surfaced so the UI can show its URL. */\n mcpEnabled: boolean;\n /** Providers the operator opted in to run on the server process's own credentials. */\n deploymentModelProviders?: ReadonlySet<string>;\n /** App skills from `MastraFactory({ skills })`. */\n skills?: readonly InlineSkill[];\n knowledgeKey?: string;\n /** Resolved Factory rule set, threaded from the host (no service locator). */\n configVersion: string;\n /** Each project's boards; integrations use the code boards (`codeRegistry`). */\n boardRegistry: BoardRegistry | ProjectBoardSource;\n /** Forces an evaluator on every project; without it each project uses its own setting. */\n intakeEvaluator?: IntakeEvaluator;\n /** What forced `intakeEvaluator`. */\n intakeEvaluatorSource?: ForcedIntakeEvaluator['source'];\n /** Stored boards and their cache; mounts the board management routes when present. */\n storedBoards?: {\n storage: StoredBoardsStorage;\n cache: ProjectBoardCache;\n };\n factoryTransitionService?: FactoryTransitionService;\n sessionRetirement?: import('../sandbox/session-retirement.js').SessionRetirementCoordinator;\n /** Moves a thread with its observation vectors onto another memory resource. */\n moveThread?: (input: { threadId: string; resourceId: string }) => Promise<unknown>;\n /** This process's dispatcher run slots, for the run queue; `undefined` until the dispatcher exists. */\n runSlots?: () => { inUse: number; cap: number; interactive: { inUse: number; cap: number } } | undefined;\n onFactoryRuntime?: (runtime: {\n transitionService: FactoryTransitionService;\n startCoordinator: FactoryStartCoordinator;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n }) => void;\n}\n\nconst REPEAT_UNAVAILABLE_LOG_MS = 5 * 60_000;\n\nfunction guardIntegrationRoutes({\n integration,\n ready,\n ensureReady,\n routes,\n}: IntegrationRegistration & { routes: ApiRoute[] }): ApiRoute[] {\n if (ready) return routes;\n // Each retry throws a fresh error, so dedupe by message and repeat it periodically.\n let lastReported: { message: string; at: number } | undefined;\n const checkReady = async () => {\n try {\n await ensureReady();\n return undefined;\n } catch (error) {\n // The response only names a key mismatch, so this log is the only trace of any other cause.\n const message = String(error);\n const now = Date.now();\n if (lastReported?.message !== message || now - lastReported.at >= REPEAT_UNAVAILABLE_LOG_MS) {\n lastReported = { message, at: now };\n console.error(\n `[factory] ${integration.id} integration is unavailable: its storage failed to initialize:`,\n error,\n );\n }\n const cause =\n secretKeyMismatchHint(error) ??\n `Its storage failed to start. The server log line \"[factory] ${integration.id} integration is unavailable\" has the cause.`;\n return { error: 'integration_unavailable', message: `${integration.id} integration is unavailable. ${cause}` };\n }\n };\n return routes.map(route => {\n if ('handler' in route) {\n const handler = route.handler;\n return {\n ...route,\n handler: async (context: Parameters<typeof handler>[0]) => {\n const unavailable = await checkReady();\n if (unavailable) return context.json(unavailable, 503);\n return handler(context, async () => {});\n },\n };\n }\n\n const createHandler = route.createHandler;\n return {\n ...route,\n createHandler: async (args: Parameters<typeof createHandler>[0]) => {\n const handler = await createHandler(args);\n return async (context: Parameters<typeof handler>[0]) => {\n const unavailable = await checkReady();\n if (unavailable) return context.json(unavailable, 503);\n return handler(context);\n };\n },\n };\n });\n}\n\n/**\n * Resolve the source-control session the work item already holds for this role,\n * when it still resolves to the item's org and factory project. Returns\n * `undefined` when there is no ref or the ref no longer resolves, so the caller\n * falls back to minting one.\n */\nasync function reuseBoundSession(\n sourceControl: SourceControlStorageHandle,\n input: FactoryBindingPreparationInput,\n role: string = input.role,\n): Promise<EnsuredFactorySourceSession | undefined> {\n const ref = input.item.sessions[role];\n if (!ref) return undefined;\n // At least as strict as the coordinator's resolveSourceSession: a ref it\n // would reject must fall through to minting, not hard-fail the run.\n const session = await sourceControl.sessions.getBySessionId(ref.sessionId);\n if (\n !session?.projectRepositoryId ||\n session.orgId !== input.record.orgId ||\n session.factoryProjectId !== input.record.factoryProjectId\n ) {\n return undefined;\n }\n return {\n sessionId: session.sessionId,\n userId: session.userId,\n projectRepositoryId: session.projectRepositoryId,\n branch: session.branch,\n baseBranch: session.baseBranch,\n };\n}\n\n/**\n * Work cards planned before Planning moved into the `work` context hold the\n * plan's session under `plan`. Building continues in it, on the same branch and\n * repository a fresh session would use, so those cards keep the plan's context.\n */\nasync function legacyPlanSession(\n sourceControl: SourceControlStorageHandle,\n input: FactoryBindingPreparationInput,\n boardId: string,\n branch: string,\n projectRepositoryId: string,\n): Promise<EnsuredFactorySourceSession | undefined> {\n const legacyRole = legacyPlanRoleFor(boardId, input.role);\n if (!legacyRole) return undefined;\n const session = await reuseBoundSession(sourceControl, input, legacyRole);\n if (\n session &&\n (session.branch === branch || session.branch === legacyGithubWorkItemBranch(branch)) &&\n session.projectRepositoryId === projectRepositoryId\n ) {\n return session;\n }\n return undefined;\n}\n\nfunction sameBranch(held: string, branch: string): boolean {\n return held === branch || held === legacyGithubWorkItemBranch(branch);\n}\n\n/** The branch a binding's session works on: the reviewed pull request's for PR review of an attached one. */\nfunction reviewBranch(\n input: FactoryBindingPreparationInput,\n board: InstalledBoard | undefined,\n stage: string,\n source: WorkItemBranchSource,\n): string {\n const metadata = input.item.workItem.metadata;\n if (input.role === REVIEW_CONTEXT && isPullRequestReviewPhase(board, stage)) {\n const change = reviewedChangeRequest({ ...input.item, source });\n if (change && !change.standalone && change.number !== undefined) {\n return pullRequestBranch({ id: input.item.id, provider: change.provider, number: change.number });\n }\n }\n return workItemBranch({ id: input.item.id, source, metadata });\n}\n\n/**\n * The lane a run started on a resting card moves it to: a review of a card with a pull request\n * goes to the board's pull request review; otherwise the first phase that runs in the role's\n * context. Work's phases share contexts, so its roles keep their own lanes: `work` builds and\n * the old `plan` role plans.\n */\nfunction restingExitLane(board: InstalledBoard | undefined, role: string, hasPullRequest: boolean): string | undefined {\n const pullRequestReview = boardFlow(board).pullRequestReview;\n if (hasPullRequest && role === REVIEW_CONTEXT && pullRequestReview) return pullRequestReview;\n return workLaneForRole(board, role) ?? board?.phaseForRole(role);\n}\n\n/** What the autonomous start reads to decide who a phase session runs as. */\nexport interface PhaseSessionOwnerSources extends OrganizationModelSources {\n workItems?: Pick<WorkItemsStorage, 'findRunBindingById'>;\n}\n\n/**\n * Who a newly minted phase session runs as. Wherever runs use the Factory's credentials\n * that is the Factory itself, whoever moved the card: the mover is the actor on the move,\n * not the owner of the run. A Factory whose runs use personal credentials has no keys of\n * its own, so there a person owns the run: whoever moved or approved the card, or the user\n * of the session whose agent moved it, else whoever created the Factory. `undefined`\n * leaves the last resort to the caller: whoever connected the repository.\n */\nasync function phaseSessionOwner(args: {\n sourceControl: SourceControlStorageHandle;\n workItems: Pick<WorkItemsStorage, 'findRunBindingById'> | undefined;\n project: FactoryProject;\n approver: string | undefined;\n}): Promise<string | undefined> {\n const { sourceControl, workItems, project, approver } = args;\n if (effectiveModelScope(project.modelScope, 'run') === 'factory') return factoryPrincipalId(project.id);\n if (approver?.startsWith('agent:')) {\n // `agent:session:<sessionId>` is a person's own session; `agent:<bindingId>` a phase run.\n const ref = approver.slice('agent:'.length);\n const sessionId = ref.startsWith('session:')\n ? ref.slice('session:'.length)\n : (await workItems?.findRunBindingById({ orgId: project.orgId, factoryProjectId: project.id, id: ref }))\n ?.sessionId;\n const session = sessionId ? await sourceControl.sessions.getBySessionId(sessionId) : null;\n if (session && session.orgId === project.orgId && isHumanActorId(session.userId)) return session.userId;\n } else if (isHumanActorId(approver)) {\n return approver;\n }\n return isHumanActorId(project.createdBy) ? project.createdBy : undefined;\n}\n\n/**\n * Who started the work, as the move that starts the run records them. An agent stays an\n * agent: recorded as a person, its move would count as a person accepting the work.\n */\nasync function starterOf(\n workItems: Pick<WorkItemsStorage, 'findRunBindingById'> | undefined,\n project: Pick<FactoryProject, 'id' | 'orgId'>,\n approver: string,\n): Promise<FactoryRuleActor> {\n if (!approver.startsWith('agent:')) return { type: 'human', id: approver };\n const bindingId = approver.slice('agent:'.length);\n if (bindingId.startsWith('session:')) return { type: 'agent', bindingId, role: 'session' };\n const binding = await workItems?.findRunBindingById({\n orgId: project.orgId,\n factoryProjectId: project.id,\n id: bindingId,\n });\n return { type: 'agent', bindingId, role: binding?.role ?? 'agent' };\n}\n\n/**\n * Start a factory run for a rule binding: ensure the source-control session the\n * coordinator requires, then hand it to `prepare` along with the factory's\n * default model. Exported for tests — this is the autonomous entry point with no\n * browser and no interactive user, so nothing else would catch a regression in\n * what it forwards.\n */\nexport async function prepareFactoryRuleBinding(\n sourceControlProvider: SourceControlStorageHandle | Pick<GithubIntegration, 'sourceControlStorage'>,\n coordinator: Pick<FactoryStartCoordinator, 'prepare'>,\n projects: FactoryProjectsStorage,\n boards: BoardRegistry | ProjectBoardSource,\n input: FactoryBindingPreparationInput,\n intake?: Pick<IntakeStorage, 'getConfig'>,\n owner?: PhaseSessionOwnerSources,\n): Promise<void> {\n try {\n const sourceControl =\n 'sourceControlStorage' in sourceControlProvider\n ? sourceControlProvider.sourceControlStorage\n : sourceControlProvider;\n const source = workItemBranchSource(input.item.externalSource);\n // Only leaving a resting phase derives a lane from the role: roles don't own lanes,\n // and the Done close-out running in the triage seat must not drag the card back.\n // Both the current phase and the role's lane come from the installed board; an\n // unknown board or phase yields no destination rather than a guessed one.\n const boardId = boardForWorkItem(input.item);\n const board = (await toBoardSource(boards).load(input.record)).get(boardId);\n const currentStage = input.item.stages.length === 1 ? input.item.stages[0] : undefined;\n const currentKind = currentStage === undefined ? undefined : board?.phaseKind(currentStage);\n const destinationStage =\n currentKind === undefined\n ? undefined\n : currentKind === 'resting'\n ? restingExitLane(board, input.role, hasPullRequest({ ...input.item, source }))\n : currentStage;\n if (!destinationStage) {\n throw new FactoryDispatchError(\n 'unsupported_provider_item',\n `Factory skill invocation has no destination lane (role \"${input.role}\", stages [${input.item.stages.join(', ')}]).`,\n );\n }\n // A PR review on an issue card checks the pull request out on its own branch, apart from\n // the builder's issue branch; every other seat works on the card's own branch.\n const branch = reviewBranch(input, board, destinationStage, source);\n const connections = await sourceControl.connections.list({\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n });\n if (!connections.some(connection => connection.integrationId === sourceControl.integrationId)) {\n throw new FactoryDispatchError('source_control_missing', 'Factory source-control connection not found.');\n }\n const project = await projects.getById({ id: input.record.factoryProjectId });\n if (!project || project.orgId !== input.record.orgId) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n `Factory model policy is unavailable for project ${input.record.factoryProjectId}.`,\n );\n }\n // A retry may already own a role session; a card that names no repository stays in it.\n const reusable = await reuseBoundSession(sourceControl, input);\n // The review seat moves between branches on one card (self-review on the builder's branch,\n // PR review on each pull request's), so its session is reused only on the branch it holds.\n const boundSession =\n reusable && input.role === REVIEW_CONTEXT && !sameBranch(reusable.branch, branch) ? undefined : reusable;\n // A card that names no repository keeps a retry in its role session's\n // repository, else starts in the environment's first one; its agent\n // determines which repository the card belongs to. An explicit signal is\n // never overridden.\n const repository = await resolveRunRepositoryFromIntake(intake, {\n sourceControl,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n item: input.item,\n ...(boundSession ? { boundProjectRepositoryId: boundSession.projectRepositoryId } : {}),\n });\n if (repository.status !== 'resolved') {\n throw new FactoryDispatchError('source_repository_ambiguous', repository.hint);\n }\n // Re-preparing a binding (server restart, retired controller session) must\n // land in the role's existing session: minting a replacement would repoint\n // the work item, flip the session's owner to the approver, and orphan the\n // previous sandbox. A session may work on a card outside its own repository\n // only when a run recorded that repository on a card that named none.\n const approver = input.record.approvedBy ?? undefined;\n if (\n boundSession &&\n boundSession.projectRepositoryId !== repository.projectRepositoryId &&\n !repositoryChosenByRun(input.item, repository.slug)\n ) {\n throw new FactoryDispatchError(\n 'source_repository_ambiguous',\n `The existing session is bound to a different repository than ${repository.slug}. Set the card's repository back, or end that session and retry.`,\n );\n }\n // The session is filed under the card's repository, or the environment's\n // first one when the card names none: the sandbox holds every environment\n // repository, but the coordinator, the PR tools and the subscriptions\n // follow the session's link.\n const existingSession =\n boundSession ?? (await legacyPlanSession(sourceControl, input, boardId, branch, repository.projectRepositoryId));\n const ownerUserId =\n existingSession?.userId ??\n (await phaseSessionOwner({ sourceControl, workItems: owner?.workItems, project, approver }));\n if (isFactoryPrincipalId(ownerUserId)) await requireOrganizationModelKey(owner, project);\n const preparedSession =\n existingSession ??\n (await ensureFactorySourceSession({\n sourceControl,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n projectRepositoryId: repository.projectRepositoryId,\n branch,\n attributeToUserId: ownerUserId,\n }).catch(error => {\n if (error instanceof FactorySourceSessionResolutionError && error.reason === 'repository') {\n // The card resolved to a linked repository the sandbox will not check out.\n throw new FactoryDispatchError(\n 'source_repository_missing',\n `Repository ${repository.slug} is linked but not pre-cloned for this Factory. Turn on Pre-clone under Settings → Repositories, then retry.`,\n { cause: error },\n );\n }\n if (error instanceof SessionBranchHeldError) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n `${error.message} The run cannot start until branch ${branch} is free for this repository.`,\n { cause: error },\n );\n }\n if (!(error instanceof SessionOwnershipMismatchError)) throw error;\n throw new FactoryDispatchError(\n 'session_unavailable',\n `Session ${error.sessionId} on branch ${branch} predates factory ownership and cannot be reused. Delete that session, then retry.`,\n { cause: error },\n );\n }));\n\n const modelScope = effectiveModelScope(project.modelScope, 'run');\n await coordinator.prepare({\n orgId: input.record.orgId,\n userId: preparedSession.userId,\n ...(approver ? { startedBy: await starterOf(owner?.workItems, project, approver) } : {}),\n factoryProjectId: input.record.factoryProjectId,\n sessionId: preparedSession.sessionId,\n expectedBindingId: input.expectedBindingId,\n modelScope,\n defaultModelId: modelScope === 'factory' ? (project.defaultModelId ?? undefined) : undefined,\n threadTitle: workItemThreadTitle({ source, title: input.item.title, metadata: input.item.workItem.metadata }),\n kickoffKey: input.record.id,\n destinationStage,\n workItem: {\n id: input.item.id,\n role: input.role,\n input: {\n externalSource: input.item.externalSource,\n parentWorkItemId: input.item.parentWorkItemId,\n title: input.item.title,\n stages: [...input.item.stages],\n sessions: input.item.sessions,\n metadata: input.item.metadata,\n },\n },\n });\n } catch (error) {\n if (error instanceof FactoryDispatchError) throw error;\n if (error instanceof FactorySourceSessionResolutionError) {\n const code = error.reason === 'connection' ? 'source_control_missing' : 'source_repository_missing';\n throw new FactoryDispatchError(code, error.message, { cause: error });\n }\n if (error instanceof SourceControlConnectionNotFoundError) {\n throw new FactoryDispatchError('source_control_missing', error.message, { cause: error });\n }\n if (error instanceof MaterializeError) {\n throw new FactoryDispatchError(MATERIALIZE_FAILURE_CODE[error.code], error.message, { cause: error });\n }\n throw error;\n }\n}\n\n/**\n * Build the {@link IntegrationContext} handed to an integration when the\n * factory collects its capabilities (routes, workers). One shape everywhere:\n * `assembleFactoryApiRoutes` uses it per registration, and `MastraFactory` uses it\n * when collecting integration workers at finalize.\n */\nexport function buildIntegrationContext(\n deps: Pick<\n FactoryApiRoutesDeps,\n | 'controller'\n | 'publicOrigin'\n | 'auth'\n | 'sandbox'\n | 'users'\n | 'factoryStorage'\n | 'integrationStorage'\n | 'sourceControlStorage'\n | 'integrations'\n > & {\n stateSigner: StateSigner;\n emitAudit?: AuditEmitter['emit'];\n onRepositoryPush?: IntegrationHooks['onRepositoryPush'];\n configVersion: string;\n boardRegistry: BoardRegistry | ProjectBoardSource;\n /** Passed for the workers' context only: routes do not sweep. */\n keptCards?: CardSource;\n /** Which items intake turned away, so integrations run intake again when one changes. */\n notRouted?: NotRoutedLookup;\n factoryReady: boolean;\n domains: Pick<\n FactoryApiRoutesDeps['domains'],\n | 'projects'\n | 'intake'\n | 'workItems'\n | 'channelIdentity'\n | 'memorySettings'\n | 'modelDefaults'\n | 'modelCredentials'\n | 'voiceSettings'\n >;\n /**\n * Stable id of the registered source-control-owning integration (today:\n * `'github'` when registered). Every call site must derive and pass it so\n * `routes()`, `channels()`, and `workers()` all see the same context shape.\n */\n sourceControlOwnerId?: string;\n },\n integrationId: string,\n): IntegrationContext {\n return {\n auth: deps.auth,\n sandbox: deps.sandbox,\n ...(deps.users ? { users: deps.users } : {}),\n factoryStorage: deps.factoryStorage,\n baseUrl: deps.publicOrigin,\n controller: deps.controller,\n stateSigner: deps.stateSigner,\n storage: {\n generic: deps.integrationStorage.forIntegration(integrationId),\n sourceControl: deps.sourceControlStorage.forIntegration(integrationId),\n ...(deps.sourceControlOwnerId\n ? { sourceControlOwner: deps.sourceControlStorage.forIntegration(deps.sourceControlOwnerId) }\n : {}),\n sourceControls: (deps.integrations ?? [])\n .filter(({ integration }) => integration.versionControl)\n .map(({ integration }) => deps.sourceControlStorage.forIntegration(integration.id)),\n projects: deps.domains.projects,\n intake: deps.domains.intake,\n channelIdentity: deps.domains.channelIdentity,\n memorySettings: deps.domains.memorySettings,\n modelDefaults: deps.domains.modelDefaults,\n modelCredentials: deps.domains.modelCredentials,\n voiceSettings: deps.domains.voiceSettings,\n },\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n ...(deps.factoryReady\n ? {\n runtime: {\n configVersion: deps.configVersion,\n workItems: deps.domains.workItems,\n boards: deps.boardRegistry,\n ...(deps.keptCards ? { keptCards: deps.keptCards } : {}),\n ...(deps.notRouted ? { notRouted: deps.notRouted } : {}),\n },\n }\n : {}),\n ...(deps.emitAudit || deps.onRepositoryPush\n ? {\n hooks: {\n ...(deps.emitAudit ? { emitAudit: deps.emitAudit } : {}),\n ...(deps.onRepositoryPush ? { onRepositoryPush: deps.onRepositoryPush } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * Disabled-status stub for the well-known integration ids. The SPA polls\n * `/web/github/status`, `/web/linear/status`, and `/web/jira/status`\n * unconditionally, so when an integration is absent (or not ready) the status\n * contract must still hold. Unknown custom ids get no stub — the SPA doesn't\n * poll them.\n */\nfunction disabledIntegrationStatusRoutes(deps: FactoryApiRoutesDeps, id: string, configured = false): ApiRoute[] {\n if (id === 'github') {\n return [\n registerApiRoute('/web/github/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n installations: [],\n reason: 'missing_config',\n diagnostics: getGithubFeatureDiagnostics({\n github: undefined,\n auth: deps.auth,\n appDbConfigured: deps.factoryStorage !== undefined,\n stateSigner: deps.stateSigner,\n sandbox: deps.sandbox,\n }),\n }),\n }),\n ];\n }\n if (id === 'linear') {\n return [\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n workspace: null,\n reason: 'missing_config',\n diagnostics: {\n linearAppConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: true,\n },\n }),\n }),\n ];\n }\n if (id === 'jira') {\n return [\n registerApiRoute('/web/jira/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n configured,\n site: null,\n reason: 'missing_config',\n diagnostics: {\n jiraConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: deps.factoryStorage !== undefined,\n },\n }),\n }),\n ];\n }\n return [];\n}\n\n/**\n * Stub for `GET /web/channel-accounts` when NO Slack integration is\n * registered. The SPA's Connections section polls the path unconditionally;\n * without a stub the SPA fallback serves HTML, which the UI can only read as\n * \"old server / unknown\". The machine-readable reason lets it say the truth:\n * the integration isn't registered.\n *\n * Mounted only for ABSENT slack — a registered integration owns the path via\n * its connect routes (or, when the state signer is unstable, gets no routes\n * at all and the UI falls back to the generic copy). Static payload, leaks\n * nothing → no auth needed, same posture as the github/linear stubs.\n */\nfunction absentSlackChannelAccountsRoutes(): ApiRoute[] {\n return [\n registerApiRoute('/web/channel-accounts', {\n method: 'GET',\n requiresAuth: false,\n handler: c => c.json({ accounts: [], canConnect: false, reason: 'not_registered' }),\n }),\n ];\n}\n\nexport interface FactoryStatusProblem {\n code: 'secret_key_mismatch';\n title: string;\n message: string;\n /** The one step that fixes it. Env var names are wrapped in backticks. */\n fix: string;\n /** Where an operator reads more, such as how to rotate keys. */\n docsUrl: string;\n}\n\n/** Domains that hold encrypted secrets; Factory can't run if they can't be read. */\nconst SECRET_DOMAINS = ['integrations', 'model-credentials', 'custom-providers'];\n\n/**\n * `GET /web/status`: problems that stop the whole Factory from working, so the\n * UI shows one alert banner instead of every page failing on its own. Only a\n * key problem counts, since only a redeploy with the right key clears it. Read\n * from the latest storage init result, so a key failure found by a later init\n * retry shows up too. Only client-safe copy goes out.\n */\nfunction factoryStatusRoutes(storage: FactoryStorage | undefined): ApiRoute[] {\n return [\n registerApiRoute('/web/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c => {\n const problem = SECRET_DOMAINS.map(domain => secretKeyProblem(storage?.domainInitError(domain))).find(Boolean);\n const problems: FactoryStatusProblem[] = problem\n ? [\n {\n code: 'secret_key_mismatch',\n ...problem,\n docsUrl: 'https://factory.mastra.ai/troubleshooting#stored-credentials-stop-working',\n },\n ]\n : [];\n return c.json({ problems });\n },\n }),\n ];\n}\n\n/**\n * Assemble the custom `/web/*` API routes as Mastra `server.apiRoutes`:\n * - fs browser routes (project picker), confined to `fsRoot`\n * - config routes (provider/API-key/default-model/OM management)\n * - every registered integration's `routes()` surface (full set when ready,\n * disabled-status stub otherwise), plus stubs for absent known ids\n */\nexport function assembleFactoryApiRoutes(deps: FactoryApiRoutesDeps): ApiRoute[] {\n const emitAudit: AuditEmitter['emit'] = args => deps.audit.emit(args);\n const registrations = deps.integrations ?? [];\n const githubRegistration = registrations.find(({ integration }) => integration.id === 'github');\n const githubStorage = githubRegistration ? deps.sourceControlStorage.forIntegration('github') : undefined;\n const githubIntegration = githubRegistration?.integration as GithubIntegration | undefined;\n const sourceControlRegistrations = registrations.filter(({ integration }) => integration.versionControl);\n const sourceControlIntegrationIds = [\n ...new Set(['github', ...sourceControlRegistrations.map(({ integration }) => integration.id)]),\n ];\n const sourceControls = sourceControlIntegrationIds.map(id => deps.sourceControlStorage.forIntegration(id));\n const sourceControlSessions = createSourceControlSessionLookup(sourceControls);\n const projectSessions = createProjectSessionsReader({\n sourceControls,\n ...(deps.users ? { users: deps.users } : {}),\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n });\n\n const integrationRoutes = registrations.flatMap(registration => {\n const { integration } = registration;\n if (!deps.stateSigner) return disabledIntegrationStatusRoutes(deps, integration.id, true);\n const context = buildIntegrationContext(\n {\n ...deps,\n // Integrations evaluate code behaviors and place new cards with the code boards.\n boardRegistry: toBoardSource(deps.boardRegistry).codeRegistry,\n ...(deps.storedBoards ? { notRouted: deps.storedBoards.storage } : {}),\n stateSigner: deps.stateSigner,\n emitAudit,\n ...(githubRegistration ? { sourceControlOwnerId: 'github' } : {}),\n },\n integration.id,\n );\n return guardIntegrationRoutes({ ...registration, routes: integration.routes(context) });\n });\n const sourceControlSessionRoutes =\n sourceControls.length === 0\n ? []\n : buildSourceControlSessionRoutes({\n auth: deps.auth,\n sourceControls,\n projects: deps.domains.projects,\n ...(deps.users ? { users: deps.users } : {}),\n projectSessions,\n controller: deps.controller,\n audit: deps.audit,\n memorySettings: deps.domains.memorySettings,\n sessionRetirement: deps.sessionRetirement,\n // A local sandbox's destroy keeps the session directory, so recreate\n // couldn't deliver the fresh checkout it promises there.\n sandboxRecreateSupported: deps.sandbox !== undefined && deps.sandbox.provider !== 'local',\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n ...(deps.moveThread ? { moveThread: deps.moveThread } : {}),\n ...(githubStorage ? { githubRepositories: githubStorage.repositories } : {}),\n });\n // Absent known integrations still get their disabled-status stub.\n const absentStubs = ['github', 'linear', 'jira']\n .filter(id => !registrations.some(({ integration }) => integration.id === id))\n .flatMap(id => disabledIntegrationStatusRoutes(deps, id));\n // Absent slack gets the channel-accounts not-registered stub (registered\n // slack owns the path via its own connect routes).\n const slackAbsentStubs = registrations.some(({ integration }) => integration.id === 'slack')\n ? []\n : absentSlackChannelAccountsRoutes();\n\n const transitionService = deps.factoryReady\n ? (deps.factoryTransitionService ??\n new FactoryTransitionService({\n configVersion: deps.configVersion,\n boards: deps.boardRegistry,\n storage: deps.domains.workItems,\n audit: deps.audit,\n }))\n : undefined;\n const startCoordinator = transitionService\n ? new FactoryStartCoordinator(\n deps.controller,\n deps.domains.workItems,\n transitionService,\n request =>\n resolveFactorySourceControl({\n sourceControls,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n sessionId: request.sessionId,\n }),\n deps.domains.intake,\n { projects: deps.domains.projects, modelDefaults: deps.domains.modelDefaults },\n deps.boardRegistry,\n )\n : undefined;\n if (transitionService && startCoordinator) {\n deps.onFactoryRuntime?.({\n transitionService,\n startCoordinator,\n ...(sourceControlRegistrations.length > 0\n ? {\n prepareBinding: async (input: FactoryBindingPreparationInput) => {\n const sourceControl = await resolveFactorySourceControl({\n sourceControls,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n });\n if (!sourceControl) {\n throw new FactoryDispatchError(\n 'source_control_missing',\n 'Factory project has no linked source-control repository.',\n );\n }\n return prepareFactoryRuleBinding(\n sourceControl,\n startCoordinator,\n deps.domains.projects,\n deps.boardRegistry,\n input,\n deps.domains.intake,\n {\n workItems: deps.domains.workItems,\n modelCredentials: deps.domains.modelCredentials,\n customProviders: deps.domains.customProviders,\n deploymentModelProviders: deps.deploymentModelProviders,\n },\n );\n },\n }\n : {}),\n });\n }\n\n return [\n ...factoryStatusRoutes(deps.factoryStorage),\n ...buildFsRoutes({\n root: deps.fsRoot,\n sessionFs: {\n auth: deps.auth,\n sessions: sourceControlSessions,\n controller: deps.controller,\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n },\n }),\n ...new ConfigRoutes({\n auth: deps.auth,\n controller: deps.controller,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n modelDefaults: deps.domains.modelDefaults,\n sourceControlSessions,\n sourceControls,\n workItems: deps.domains.workItems,\n memorySettings: deps.domains.memorySettings,\n factoryProjects: deps.domains.projects,\n customProviders: deps.domains.customProviders,\n features: { knowledge: deps.knowledgeEnabled, mcp: deps.mcpEnabled },\n deploymentProviders: deps.deploymentModelProviders,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n onCustomProvidersChanged: invalidateCustomProvidersSnapshots,\n }).routes(),\n ...new OAuthRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n }).routes(),\n ...new VoiceRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n voiceSettings: deps.domains.voiceSettings,\n factoryProjects: deps.domains.projects,\n }).routes(),\n ...new SkillRoutes({\n auth: deps.auth,\n controllerId: deps.controllerId,\n controller: deps.controller,\n sourceControlStorage: githubStorage,\n ensureSourceControlReady: githubRegistration?.ensureReady,\n ...(deps.skills ? { skills: deps.skills } : {}),\n overrides: { projects: deps.domains.projects, storage: deps.domains.skillOverrides, audit: deps.audit },\n }).routes(),\n ...sourceControlSessionRoutes,\n ...(sourceControls.length === 0\n ? []\n : buildSourceControlSettingsRoutes({\n auth: deps.auth,\n sourceControls,\n ...(deps.onEnvironmentSaved ? { onEnvironmentSaved: deps.onEnvironmentSaved } : {}),\n })),\n ...integrationRoutes,\n ...absentStubs,\n ...slackAbsentStubs,\n ...(deps.intakeReady\n ? new IntakeRoutes({\n auth: deps.auth,\n audit: deps.audit,\n intake: deps.domains.intake,\n projects: deps.domains.projects,\n ...(deps.onIntakeSourcesSelected ? { onSourcesSelected: deps.onIntakeSourcesSelected } : {}),\n integrations: (deps.integrations ?? []).flatMap(({ integration }) => [\n ...(integration.intake ? [{ id: integration.id, intake: integration.intake }] : []),\n ...(integration.additionalIntakes ?? []),\n ]),\n }).routes()\n : []),\n ...(deps.factoryReady && deps.knowledgeEnabled\n ? new KnowledgeRoutes({\n auth: deps.auth,\n projects: deps.domains.projects,\n knowledge: async key => deps.controller.getMastra()?.getKnowledge(key),\n defaultKnowledgeKey: deps.knowledgeKey,\n }).routes()\n : []),\n ...(deps.factoryReady\n ? new WorkItemRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n boardRegistry: deps.boardRegistry,\n intakeRoutes: deps.storedBoards?.storage,\n intakeEvaluator: deps.intakeEvaluator,\n queueHealth: deps.domains.queueHealth,\n transitionService,\n startCoordinator,\n ...(sourceControlRegistrations.length > 0\n ? {\n sessionRepository: async ({ orgId, factoryProjectId, item }) => {\n const sourceControl = await resolveFactorySourceControl({ sourceControls, orgId, factoryProjectId });\n if (!sourceControl) {\n return { status: 'unlinked', hint: 'Factory project has no linked source-control repository.' };\n }\n return resolveRunRepositoryFromIntake(deps.domains.intake, {\n sourceControl,\n orgId,\n factoryProjectId,\n item,\n });\n },\n }\n : {}),\n liveSessions: deps.liveSessions,\n runSlots: deps.runSlots,\n projectSessions,\n activeRuns: () => deps.controller.listActiveThreadRuns(),\n }).routes()\n : []),\n ...(deps.factoryReady && deps.storedBoards\n ? new BoardRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n storage: deps.storedBoards.storage,\n boards: deps.storedBoards.cache,\n }).routes()\n : []),\n ...(deps.factoryReady && deps.storedBoards\n ? new IntakeRouteRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n storage: deps.storedBoards.storage,\n boards: deps.storedBoards.cache,\n intakeEvaluator: deps.intakeEvaluator,\n intakeEvaluatorSource: deps.intakeEvaluatorSource,\n intakeLookups: (deps.integrations ?? []).flatMap(({ integration, ready }) =>\n ready && integration.intakeLookup ? [integration.intakeLookup] : [],\n ),\n }).routes()\n : []),\n ...(deps.factoryReady\n ? buildAutomationRunRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n boards: deps.boardRegistry,\n })\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+FA,MAAM,2BAA2B;CAC/B,eAAe;CACf,wBAAwB;CACxB,kBAAkB;CAClB,gBAAgB;CAChB,eAAe;CACf,eAAe;CACf,iBAAiB;CACjB,cAAc;CACd,aAAa;AACf;AAoFA,MAAM,4BAA4B;AAElC,SAAS,uBAAuB,EAC9B,aACA,OACA,aACA,UAC+D;CAC/D,IAAI,OAAO,OAAO;CAElB,IAAI;CACJ,MAAM,aAAa,YAAY;EAC7B,IAAI;GACF,MAAM,YAAY;GAClB;EACF,SAAS,OAAO;GAEd,MAAM,UAAU,OAAO,KAAK;GAC5B,MAAM,MAAM,KAAK,IAAI;GACrB,IAAI,cAAc,YAAY,WAAW,MAAM,aAAa,MAAM,2BAA2B;IAC3F,eAAe;KAAE;KAAS,IAAI;IAAI;IAClC,QAAQ,MACN,aAAa,YAAY,GAAG,iEAC5B,KACF;GACF;GACA,MAAM,QACJ,sBAAsB,KAAK,KAC3B,+DAA+D,YAAY,GAAG;GAChF,OAAO;IAAE,OAAO;IAA2B,SAAS,GAAG,YAAY,GAAG,+BAA+B;GAAQ;EAC/G;C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ACH,OAAO;KAAE,QAAQ;KAAY,MAAM;IAA2D;IAEhG,OAAO,+BAA+B,KAAK,QAAQ,QAAQ;KACzD;KACA;KACA;KACA;IACF,CAAC;GACH,EACF,IACA,CAAC;GACL,cAAc,KAAK;GACnB,UAAU,KAAK;GACf;GACA,kBAAkB,KAAK,WAAW,qBAAqB;EACzD,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;EACL,GAAI,KAAK,gBAAgB,KAAK,eAC1B,IAAI,YAAY;GACd,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,SAAS,KAAK,aAAa;GAC3B,QAAQ,KAAK,aAAa;EAC5B,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;EACL,GAAI,KAAK,gBAAgB,KAAK,eAC1B,IAAI,kBAAkB;GACpB,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,SAAS,KAAK,aAAa;GAC3B,QAAQ,KAAK,aAAa;GAC1B,iBAAiB,KAAK;GACtB,uBAAuB,KAAK;GAC5B,gBAAgB,KAAK,gBAAgB,CAAC,EAAA,CAAG,SAAS,EAAE,aAAa,YAC/D,SAAS,YAAY,eAAe,CAAC,YAAY,YAAY,IAAI,CAAC,CACpE;EACF,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;EACL,GAAI,KAAK,eACL,yBAAyB;GACvB,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,QAAQ,KAAK;EACf,CAAC,IACD,CAAC;CACP;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"tenant-credentials.d.ts","sourceRoot":"","sources":["../../src/routes/tenant-credentials.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EACV,gBAAgB,IAAI,mBAAmB,EACvC,wBAAwB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BAAmB,GAAE,WAAW,CAAC,MAAM,CAAa,EACpD,aAAa,CAAC,EAAE,wBAAwB,GACvC,IAAI,CAcN;AAED;;;;;GAKG;AACH,wBAAsB,uCAAuC,CAAC,cAAc,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAM3G;AAED,uFAAuF;AACvF,wBAAsB,+BAA+B,CAAC,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAYhG;AAED;;;;;GAKG;AACH,wBAAsB,iCAAiC,CACrD,MAAM,EAAE,mBAAmB,EAC3B,cAAc,EAAE,MAAM,GAAG,SAAS,GACjC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAc7B;AAED,iEAAiE;AACjE,wBAAgB,qCAAqC,IAAI,IAAI,CAK5D;AAED;;;;;GAKG;AACH,wBAAgB,mCAAmC,CAAC,MAAM,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CASpG;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAAC,EAC3C,MAAM,EACN,WAAW,GACZ,EAAE;IACD,MAAM,EAAE,IAAI,CAAC,mBAAmB,EAAE,OAAO,GAAG,QAAQ,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,iBAAiB,CAAC,CAAC,CAAC;IAC9G,WAAW,EAAE,uBAAuB,CAAC;CACtC,GAAG,OAAO,CAAC,IAAI,CAAC,CAKhB;AAED,wBAAgB,4BAA4B,CAAC,EAC3C,IAAI,EACJ,WAAW,GACZ,EAAE;IACD,IAAI,EAAE,SAAS,CAAC;IAChB,WAAW,EAAE,uBAAuB,CAAC;CACtC,GAAG,iBAAiB,CAgBpB"}
@@ -1,5 +1,5 @@
1
1
  import { isOAuthCredentialExpired } from "../storage/domains/credentials/base.js";
2
- import { getAuthProviderId, getTenantCredentialsStorage, tenantOrgId } from "./provider-credentials.js";
2
+ import { getAuthProviderId, getTenantCredentialsStorage, storedScopeFor, tenantOrgId } from "./provider-credentials.js";
3
3
  import { prepareCredentialTenant, resolveTenantFromRequestContext, setCredentialStoreProvider } from "@mastra/code-sdk/agents/credential-resolver";
4
4
  import { PROVIDER_DEFAULT_MODELS, getOAuthProvider } from "@mastra/code-sdk/auth/storage";
5
5
  import { MASTRA_GATEWAY_PROVIDER } from "@mastra/code-sdk/onboarding/settings";
@@ -43,7 +43,7 @@ var TenantCredentialStore = class {
43
43
  if (!storage) return;
44
44
  const records = await storage.listCredentials(this.#orgId, this.#userId);
45
45
  const next = /* @__PURE__ */ new Map();
46
- const storageScope = this.#scope === "factory" ? "org" : "user";
46
+ const storageScope = storedScopeFor(this.#scope);
47
47
  for (const record of records.filter((r) => r.scope === storageScope)) next.set(record.provider, record.credential);
48
48
  this.#snapshot = next;
49
49
  this.#fetchedAt = Date.now();
@@ -73,7 +73,7 @@ var TenantCredentialStore = class {
73
73
  if (cred?.type === "oauth" && !isOAuthCredentialExpired(cred)) return getOAuthProvider(provider)?.getApiKey(cred);
74
74
  return;
75
75
  }
76
- const resolved = await storage.resolveCredential(this.#orgId, this.#userId, provider, this.#scope === "factory" ? "org" : "user");
76
+ const resolved = await storage.resolveCredential(this.#orgId, this.#userId, provider, storedScopeFor(this.#scope));
77
77
  if (!resolved) {
78
78
  this.#snapshot.delete(provider);
79
79
  return;
@@ -97,7 +97,7 @@ var TenantCredentialStore = class {
97
97
  const storage = await getTenantCredentialsStorage(this.#credentials);
98
98
  if (!storage) return void 0;
99
99
  const served = this.#snapshot.get(provider);
100
- const resolved = await storage.resolveCredential(this.#orgId, this.#userId, provider, this.#scope === "factory" ? "org" : "user");
100
+ const resolved = await storage.resolveCredential(this.#orgId, this.#userId, provider, storedScopeFor(this.#scope));
101
101
  if (resolved?.credential.type !== "oauth") return void 0;
102
102
  const rejectedAccess = served?.type === "oauth" ? served.access : resolved.credential.access;
103
103
  return this.#refreshOAuth(storage, resolved.scope, provider, (current) => isOAuthCredentialExpired(current) || current.access === rejectedAccess);
@@ -1 +1 @@
1
- {"version":3,"file":"tenant-credentials.js","names":[],"sources":["../../src/routes/tenant-credentials.ts"],"sourcesContent":["/**\n * Per-tenant credential store for model resolution (deployed mode).\n *\n * The SDK's `resolveModel` asks the registered `CredentialStoreProvider` for a\n * store synchronously, so this module keeps a small per-tenant **snapshot** of\n * credentials from one exclusive scope hydrated from the `model-credentials`\n * domain. The snapshot serves the gateway's synchronous\n * path-selection reads (`get` / `getStoredApiKey`); the fetch-time\n * `getApiKey` is authoritative — it re-resolves against the domain and\n * refreshes expired OAuth tokens under the domain's row lock, so a slightly\n * stale snapshot can never send an expired token upstream.\n *\n * Snapshots are primed per request by `createTenantCredentialPrimer` (mounted\n * after the web auth gate) so the first model call of a request already sees\n * the caller's credentials. This store explicitly disables the SDK's\n * environment fallback so server-shell credentials never leak into tenants.\n */\n\nimport type {\n CredentialTenant as SdkCredentialTenant,\n CredentialTenantResolver,\n} from '@mastra/code-sdk/agents/credential-resolver';\nimport {\n prepareCredentialTenant,\n resolveTenantFromRequestContext,\n setCredentialStoreProvider,\n} from '@mastra/code-sdk/agents/credential-resolver';\nimport { getOAuthProvider, PROVIDER_DEFAULT_MODELS } from '@mastra/code-sdk/auth/storage';\nimport type { AuthCredential, CredentialStore, OAuthCredential } from '@mastra/code-sdk/auth/types';\nimport { MASTRA_GATEWAY_PROVIDER } from '@mastra/code-sdk/onboarding/settings';\nimport { MASTRA_GATEWAY_PREFIX } from '@mastra/code-sdk/providers/model-ids';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MiddlewareHandler } from 'hono';\n\nimport { isOAuthCredentialExpired } from '../storage/domains/credentials/base.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport { getAuthProviderId, getTenantCredentialsStorage, tenantOrgId } from './provider-credentials.js';\nimport type { RouteAuth } from './route.js';\n\n/** How long a hydrated snapshot is considered fresh. */\nconst SNAPSHOT_TTL_MS = 15_000;\n\n/** Cap on cached tenant stores; oldest-inserted evicted beyond this. */\nconst MAX_CACHED_TENANTS = 1000;\n\nexport class TenantCredentialStore implements CredentialStore {\n readonly allowEnvironmentFallback = false;\n readonly #orgId: string;\n readonly #userId: string;\n readonly #scope: SdkCredentialTenant['credentialScope'];\n readonly #credentials: ModelCredentialsStorage | undefined;\n readonly #deploymentProviders: ReadonlySet<string>;\n #snapshot = new Map<string, AuthCredential>();\n #fetchedAt = 0;\n #hydrating: Promise<void> | undefined;\n\n constructor(\n orgId: string,\n userId: string,\n credentials: ModelCredentialsStorage | undefined,\n scope: SdkCredentialTenant['credentialScope'],\n deploymentProviders: ReadonlySet<string> = new Set(),\n ) {\n this.#orgId = orgId;\n this.#userId = userId;\n this.#credentials = credentials;\n this.#scope = scope;\n this.#deploymentProviders = deploymentProviders;\n }\n\n /** Providers the operator opted in to run on the server process's own credentials. */\n allowsDeploymentCredentials(provider: string): boolean {\n return this.#deploymentProviders.has(provider);\n }\n\n /** Hydrate the snapshot when stale; coalesces concurrent callers. */\n async ensureFresh(now = Date.now()): Promise<void> {\n if (now - this.#fetchedAt < SNAPSHOT_TTL_MS) return;\n this.#hydrating ??= this.#hydrate().finally(() => {\n this.#hydrating = undefined;\n });\n await this.#hydrating;\n }\n\n async #hydrate(): Promise<void> {\n const storage = await getTenantCredentialsStorage(this.#credentials);\n if (!storage) return; // Keep the last tenant-scoped snapshot.\n const records = await storage.listCredentials(this.#orgId, this.#userId);\n const next = new Map<string, AuthCredential>();\n const storageScope = this.#scope === 'factory' ? 'org' : 'user';\n for (const record of records.filter(r => r.scope === storageScope)) {\n next.set(record.provider, record.credential);\n }\n this.#snapshot = next;\n this.#fetchedAt = Date.now();\n }\n\n /** Sync by contract; kicks a background re-hydrate when the snapshot is stale. */\n reload(): void {\n if (Date.now() - this.#fetchedAt >= SNAPSHOT_TTL_MS) {\n void this.ensureFresh().catch(() => {});\n }\n }\n\n get(provider: string): AuthCredential | undefined {\n return this.#snapshot.get(provider);\n }\n\n getStoredApiKey(provider: string): string | undefined {\n const cred = this.#snapshot.get(provider);\n return cred?.type === 'api_key' ? cred.key : undefined;\n }\n\n /**\n * Authoritative fetch-time resolution: re-reads only the selected scope and\n * refreshes expired OAuth tokens under the domain's row lock. Mirrors\n * `AuthStorage.getApiKey` semantics: `undefined` on missing credential or\n * failed refresh (caller surfaces a re-login error).\n */\n async getApiKey(provider: string): Promise<string | undefined> {\n const storage = await getTenantCredentialsStorage(this.#credentials);\n if (!storage) {\n // Domain unavailable: best effort from the snapshot; expired OAuth\n // tokens cannot be refreshed without the domain's lock.\n const cred = this.#snapshot.get(provider);\n if (cred?.type === 'api_key') return cred.key;\n if (cred?.type === 'oauth' && !isOAuthCredentialExpired(cred)) {\n return getOAuthProvider(provider)?.getApiKey(cred);\n }\n return undefined;\n }\n\n const resolved = await storage.resolveCredential(\n this.#orgId,\n this.#userId,\n provider,\n this.#scope === 'factory' ? 'org' : 'user',\n );\n if (!resolved) {\n this.#snapshot.delete(provider);\n return undefined;\n }\n this.#snapshot.set(provider, resolved.credential);\n\n if (resolved.credential.type === 'api_key') {\n return resolved.credential.key;\n }\n\n const oauthProvider = getOAuthProvider(provider);\n if (!oauthProvider) return undefined;\n\n if (!isOAuthCredentialExpired(resolved.credential)) {\n return oauthProvider.getApiKey(resolved.credential);\n }\n\n return this.#refreshOAuth(storage, resolved.scope, provider, isOAuthCredentialExpired);\n }\n\n /**\n * Refresh the OAuth credential even though it hasn't expired. The\n * account-rotation processor calls this once when the provider rejects the\n * token (401/403): providers can revoke an access token before the expiry\n * recorded at sign-in. Only the token this store last served is replaced, so\n * when another session or replica already refreshed it the newer token is\n * reused instead of rotating the refresh token again.\n */\n async forceRefreshActiveAccount(provider: string): Promise<string | undefined> {\n const storage = await getTenantCredentialsStorage(this.#credentials);\n if (!storage) return undefined;\n const served = this.#snapshot.get(provider);\n const resolved = await storage.resolveCredential(\n this.#orgId,\n this.#userId,\n provider,\n this.#scope === 'factory' ? 'org' : 'user',\n );\n if (resolved?.credential.type !== 'oauth') return undefined;\n const rejectedAccess = served?.type === 'oauth' ? served.access : resolved.credential.access;\n return this.#refreshOAuth(\n storage,\n resolved.scope,\n provider,\n current => isOAuthCredentialExpired(current) || current.access === rejectedAccess,\n );\n }\n\n async #refreshOAuth(\n storage: ModelCredentialsStorage,\n scope: 'user' | 'org',\n provider: string,\n needsRefresh: (current: OAuthCredential) => boolean,\n ): Promise<string | undefined> {\n const oauthProvider = getOAuthProvider(provider);\n if (!oauthProvider) return undefined;\n // Refresh at the scope the credential actually lives at (OAuth rows are\n // user-scoped by policy, but resolve defensively from the record).\n const rowTenant = scope === 'user' ? { orgId: this.#orgId, userId: this.#userId } : { orgId: this.#orgId };\n try {\n const refreshed = await storage.refreshOAuth(\n rowTenant,\n provider,\n async current => ({\n type: 'oauth' as const,\n ...(await oauthProvider.refreshToken(current)),\n }),\n needsRefresh,\n );\n if (!refreshed) return undefined;\n this.#snapshot.set(provider, refreshed);\n return oauthProvider.getApiKey(refreshed);\n } catch {\n // Refresh failed — user needs to re-login (same posture as AuthStorage).\n return undefined;\n }\n }\n}\n\nconst tenantStores = new Map<string, TenantCredentialStore>();\nlet registeredCredentials: ModelCredentialsStorage | undefined;\nlet registeredDeploymentProviders: ReadonlySet<string> = new Set();\n\nfunction storeFor(tenant: SdkCredentialTenant, credentials: ModelCredentialsStorage): TenantCredentialStore {\n const orgId = tenantOrgId(tenant);\n const key = `${orgId}\\u0000${tenant.userId}\\u0000${tenant.credentialScope}`;\n let store = tenantStores.get(key);\n if (!store) {\n if (tenantStores.size >= MAX_CACHED_TENANTS) {\n const oldest = tenantStores.keys().next().value;\n if (oldest !== undefined) tenantStores.delete(oldest);\n }\n store = new TenantCredentialStore(\n orgId,\n tenant.userId,\n credentials,\n tenant.credentialScope,\n registeredDeploymentProviders,\n );\n tenantStores.set(key, store);\n }\n return store;\n}\n\n/**\n * Register the web tenant credential store provider with the SDK. Called by\n * the factory after storage init with the `model-credentials` domain handle;\n * from then on `resolveModel` uses per-tenant credentials and the SDK skips\n * the `loadStoredApiKeysIntoEnv` env side-channel. `deploymentProviders` are\n * the providers the operator opted in to authenticate with the server\n * process's own credentials (see `MastraFactoryConfig.deploymentModelProviders`).\n */\nexport function registerTenantCredentialResolver(\n credentials: ModelCredentialsStorage,\n deploymentProviders: ReadonlySet<string> = new Set(),\n resolveTenant?: CredentialTenantResolver,\n): void {\n registeredCredentials = credentials;\n registeredDeploymentProviders = deploymentProviders;\n tenantStores.clear();\n setCredentialStoreProvider(\n tenant => storeFor(tenant, credentials),\n resolveTenant\n ? async requestContext => {\n const tenant = await resolveTenant(requestContext);\n if (tenant) await storeFor(tenant, credentials).ensureFresh();\n return tenant;\n }\n : undefined,\n );\n}\n\n/**\n * Prime the tenant stores for a request context built outside the web layer,\n * such as a webhook-triggered session run. The auth middleware does this for\n * HTTP requests; a run that starts without one would otherwise resolve its\n * model against an empty snapshot and fail closed. No-op before registration.\n */\nexport async function primeTenantCredentialsForRequestContext(requestContext: RequestContext): Promise<void> {\n if (!registeredCredentials) return;\n await prepareCredentialTenant(requestContext);\n const tenant = resolveTenantFromRequestContext(requestContext);\n if (!tenant) return;\n await storeFor(tenant, registeredCredentials).ensureFresh();\n}\n\n/** Prime one already-resolved Factory session tenant before entering the agent run. */\nexport async function primeTenantCredentialsForTenant(tenant: SdkCredentialTenant): Promise<void> {\n if (!registeredCredentials) return;\n try {\n await storeFor(tenant, registeredCredentials).ensureFresh();\n } catch (error) {\n console.warn('[factory] Failed to prime scoped tenant model credentials', {\n orgId: tenant.orgId,\n userId: tenant.userId,\n credentialScope: tenant.credentialScope,\n error,\n });\n }\n}\n\n/**\n * The model a session should fall back to when its scope has no chosen default:\n * the provider default (`PROVIDER_DEFAULT_MODELS`) of the first provider the\n * tenant is connected to. Returns `undefined` when `currentModelId` is already\n * usable, when no connected provider has a default, or before registration.\n */\nexport async function resolveTenantProviderDefaultModel(\n tenant: SdkCredentialTenant,\n currentModelId: string | undefined,\n): Promise<string | undefined> {\n if (!registeredCredentials) return undefined;\n const store = storeFor(tenant, registeredCredentials);\n await store.ensureFresh();\n const usable = (modelId: string) => {\n const provider = modelId.split('/')[0] ?? '';\n return store.get(getAuthProviderId(provider)) !== undefined || store.allowsDeploymentCredentials(provider);\n };\n if (currentModelId && usable(currentModelId)) return undefined;\n const providerDefault = Object.entries(PROVIDER_DEFAULT_MODELS).find(\n ([provider]) => store.get(provider) !== undefined,\n )?.[1];\n if (providerDefault) return providerDefault;\n return store.get(MASTRA_GATEWAY_PROVIDER) ? `${MASTRA_GATEWAY_PREFIX}anthropic/claude-opus-5.5` : undefined;\n}\n\n/** Test hook: clear registration and cached tenant snapshots. */\nexport function resetTenantCredentialResolverForTests(): void {\n setCredentialStoreProvider(undefined);\n registeredCredentials = undefined;\n registeredDeploymentProviders = new Set();\n tenantStores.clear();\n}\n\n/**\n * Drop cached snapshots after a credential write so the change is visible to\n * the next model call immediately instead of after the snapshot TTL. An org\n * write affects every member's resolved view, so all stores under the org are\n * invalidated; a user write only drops that user's store.\n */\nexport function invalidateTenantCredentialSnapshots(tenant: { orgId: string; userId?: string }): void {\n if (tenant.userId) {\n tenantStores.delete(`${tenant.orgId}\\u0000${tenant.userId}\\u0000user`);\n tenantStores.delete(`${tenant.orgId}\\u0000${tenant.userId}\\u0000factory`);\n return;\n }\n for (const key of tenantStores.keys()) {\n if (key.startsWith(`${tenant.orgId}\\u0000`)) tenantStores.delete(key);\n }\n}\n\n/**\n * Middleware mounted after the web auth gate: primes both exclusive credential\n * scopes because the HTTP principal is known before the controller session is.\n * Cheap when fresh because each store has a TTL.\n */\nexport async function primeTenantCredentials({\n tenant,\n credentials,\n}: {\n tenant: Pick<SdkCredentialTenant, 'orgId' | 'userId'> & Partial<Pick<SdkCredentialTenant, 'credentialScope'>>;\n credentials: ModelCredentialsStorage;\n}): Promise<void> {\n await Promise.all([\n storeFor({ ...tenant, credentialScope: 'user' }, credentials).ensureFresh(),\n storeFor({ ...tenant, credentialScope: 'factory' }, credentials).ensureFresh(),\n ]);\n}\n\nexport function createTenantCredentialPrimer({\n auth,\n credentials,\n}: {\n auth: RouteAuth;\n credentials: ModelCredentialsStorage;\n}): MiddlewareHandler {\n return async (c, next) => {\n const tenant = auth.tenant(c);\n if (tenant) {\n try {\n await primeTenantCredentials({ tenant, credentials });\n } catch (error) {\n console.warn('[factory] Failed to prime tenant model credentials', {\n orgId: tenant.orgId,\n userId: tenant.userId,\n error,\n });\n }\n }\n await next();\n };\n}\n"],"mappings":";;;;;;;;AAwCA,MAAM,kBAAkB;;AAGxB,MAAM,qBAAqB;AAE3B,IAAa,wBAAb,MAA8D;CAC5D,2BAAoC;CACpC;CACA;CACA;CACA;CACA;CACA,4BAAY,IAAI,IAA4B;CAC5C,aAAa;CACb;CAEA,YACE,OACA,QACA,aACA,OACA,sCAA2C,IAAI,IAAI,GACnD;EACA,KAAK,SAAS;EACd,KAAK,UAAU;EACf,KAAK,eAAe;EACpB,KAAK,SAAS;EACd,KAAK,uBAAuB;CAC9B;;CAGA,4BAA4B,UAA2B;EACrD,OAAO,KAAK,qBAAqB,IAAI,QAAQ;CAC/C;;CAGA,MAAM,YAAY,MAAM,KAAK,IAAI,GAAkB;EACjD,IAAI,MAAM,KAAK,aAAa,iBAAiB;EAC7C,KAAK,eAAe,KAAK,SAAS,CAAC,CAAC,cAAc;GAChD,KAAK,aAAa,KAAA;EACpB,CAAC;EACD,MAAM,KAAK;CACb;CAEA,MAAM,WAA0B;EAC9B,MAAM,UAAU,MAAM,4BAA4B,KAAK,YAAY;EACnE,IAAI,CAAC,SAAS;EACd,MAAM,UAAU,MAAM,QAAQ,gBAAgB,KAAK,QAAQ,KAAK,OAAO;EACvE,MAAM,uBAAO,IAAI,IAA4B;EAC7C,MAAM,eAAe,KAAK,WAAW,YAAY,QAAQ;EACzD,KAAK,MAAM,UAAU,QAAQ,QAAO,MAAK,EAAE,UAAU,YAAY,GAC/D,KAAK,IAAI,OAAO,UAAU,OAAO,UAAU;EAE7C,KAAK,YAAY;EACjB,KAAK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AACF"}
1
+ {"version":3,"file":"tenant-credentials.js","names":[],"sources":["../../src/routes/tenant-credentials.ts"],"sourcesContent":["/**\n * Per-tenant credential store for model resolution (deployed mode).\n *\n * The SDK's `resolveModel` asks the registered `CredentialStoreProvider` for a\n * store synchronously, so this module keeps a small per-tenant **snapshot** of\n * credentials from one exclusive scope hydrated from the `model-credentials`\n * domain. The snapshot serves the gateway's synchronous\n * path-selection reads (`get` / `getStoredApiKey`); the fetch-time\n * `getApiKey` is authoritative — it re-resolves against the domain and\n * refreshes expired OAuth tokens under the domain's row lock, so a slightly\n * stale snapshot can never send an expired token upstream.\n *\n * Snapshots are primed per request by `createTenantCredentialPrimer` (mounted\n * after the web auth gate) so the first model call of a request already sees\n * the caller's credentials. This store explicitly disables the SDK's\n * environment fallback so server-shell credentials never leak into tenants.\n */\n\nimport type {\n CredentialTenant as SdkCredentialTenant,\n CredentialTenantResolver,\n} from '@mastra/code-sdk/agents/credential-resolver';\nimport {\n prepareCredentialTenant,\n resolveTenantFromRequestContext,\n setCredentialStoreProvider,\n} from '@mastra/code-sdk/agents/credential-resolver';\nimport { getOAuthProvider, PROVIDER_DEFAULT_MODELS } from '@mastra/code-sdk/auth/storage';\nimport type { AuthCredential, CredentialStore, OAuthCredential } from '@mastra/code-sdk/auth/types';\nimport { MASTRA_GATEWAY_PROVIDER } from '@mastra/code-sdk/onboarding/settings';\nimport { MASTRA_GATEWAY_PREFIX } from '@mastra/code-sdk/providers/model-ids';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MiddlewareHandler } from 'hono';\n\nimport { isOAuthCredentialExpired } from '../storage/domains/credentials/base.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport { getAuthProviderId, getTenantCredentialsStorage, storedScopeFor, tenantOrgId } from './provider-credentials.js';\nimport type { RouteAuth } from './route.js';\n\n/** How long a hydrated snapshot is considered fresh. */\nconst SNAPSHOT_TTL_MS = 15_000;\n\n/** Cap on cached tenant stores; oldest-inserted evicted beyond this. */\nconst MAX_CACHED_TENANTS = 1000;\n\nexport class TenantCredentialStore implements CredentialStore {\n readonly allowEnvironmentFallback = false;\n readonly #orgId: string;\n readonly #userId: string;\n readonly #scope: SdkCredentialTenant['credentialScope'];\n readonly #credentials: ModelCredentialsStorage | undefined;\n readonly #deploymentProviders: ReadonlySet<string>;\n #snapshot = new Map<string, AuthCredential>();\n #fetchedAt = 0;\n #hydrating: Promise<void> | undefined;\n\n constructor(\n orgId: string,\n userId: string,\n credentials: ModelCredentialsStorage | undefined,\n scope: SdkCredentialTenant['credentialScope'],\n deploymentProviders: ReadonlySet<string> = new Set(),\n ) {\n this.#orgId = orgId;\n this.#userId = userId;\n this.#credentials = credentials;\n this.#scope = scope;\n this.#deploymentProviders = deploymentProviders;\n }\n\n /** Providers the operator opted in to run on the server process's own credentials. */\n allowsDeploymentCredentials(provider: string): boolean {\n return this.#deploymentProviders.has(provider);\n }\n\n /** Hydrate the snapshot when stale; coalesces concurrent callers. */\n async ensureFresh(now = Date.now()): Promise<void> {\n if (now - this.#fetchedAt < SNAPSHOT_TTL_MS) return;\n this.#hydrating ??= this.#hydrate().finally(() => {\n this.#hydrating = undefined;\n });\n await this.#hydrating;\n }\n\n async #hydrate(): Promise<void> {\n const storage = await getTenantCredentialsStorage(this.#credentials);\n if (!storage) return; // Keep the last tenant-scoped snapshot.\n const records = await storage.listCredentials(this.#orgId, this.#userId);\n const next = new Map<string, AuthCredential>();\n const storageScope = storedScopeFor(this.#scope);\n for (const record of records.filter(r => r.scope === storageScope)) {\n next.set(record.provider, record.credential);\n }\n this.#snapshot = next;\n this.#fetchedAt = Date.now();\n }\n\n /** Sync by contract; kicks a background re-hydrate when the snapshot is stale. */\n reload(): void {\n if (Date.now() - this.#fetchedAt >= SNAPSHOT_TTL_MS) {\n void this.ensureFresh().catch(() => {});\n }\n }\n\n get(provider: string): AuthCredential | undefined {\n return this.#snapshot.get(provider);\n }\n\n getStoredApiKey(provider: string): string | undefined {\n const cred = this.#snapshot.get(provider);\n return cred?.type === 'api_key' ? cred.key : undefined;\n }\n\n /**\n * Authoritative fetch-time resolution: re-reads only the selected scope and\n * refreshes expired OAuth tokens under the domain's row lock. Mirrors\n * `AuthStorage.getApiKey` semantics: `undefined` on missing credential or\n * failed refresh (caller surfaces a re-login error).\n */\n async getApiKey(provider: string): Promise<string | undefined> {\n const storage = await getTenantCredentialsStorage(this.#credentials);\n if (!storage) {\n // Domain unavailable: best effort from the snapshot; expired OAuth\n // tokens cannot be refreshed without the domain's lock.\n const cred = this.#snapshot.get(provider);\n if (cred?.type === 'api_key') return cred.key;\n if (cred?.type === 'oauth' && !isOAuthCredentialExpired(cred)) {\n return getOAuthProvider(provider)?.getApiKey(cred);\n }\n return undefined;\n }\n\n const resolved = await storage.resolveCredential(this.#orgId, this.#userId, provider, storedScopeFor(this.#scope));\n if (!resolved) {\n this.#snapshot.delete(provider);\n return undefined;\n }\n this.#snapshot.set(provider, resolved.credential);\n\n if (resolved.credential.type === 'api_key') {\n return resolved.credential.key;\n }\n\n const oauthProvider = getOAuthProvider(provider);\n if (!oauthProvider) return undefined;\n\n if (!isOAuthCredentialExpired(resolved.credential)) {\n return oauthProvider.getApiKey(resolved.credential);\n }\n\n return this.#refreshOAuth(storage, resolved.scope, provider, isOAuthCredentialExpired);\n }\n\n /**\n * Refresh the OAuth credential even though it hasn't expired. The\n * account-rotation processor calls this once when the provider rejects the\n * token (401/403): providers can revoke an access token before the expiry\n * recorded at sign-in. Only the token this store last served is replaced, so\n * when another session or replica already refreshed it the newer token is\n * reused instead of rotating the refresh token again.\n */\n async forceRefreshActiveAccount(provider: string): Promise<string | undefined> {\n const storage = await getTenantCredentialsStorage(this.#credentials);\n if (!storage) return undefined;\n const served = this.#snapshot.get(provider);\n const resolved = await storage.resolveCredential(this.#orgId, this.#userId, provider, storedScopeFor(this.#scope));\n if (resolved?.credential.type !== 'oauth') return undefined;\n const rejectedAccess = served?.type === 'oauth' ? served.access : resolved.credential.access;\n return this.#refreshOAuth(\n storage,\n resolved.scope,\n provider,\n current => isOAuthCredentialExpired(current) || current.access === rejectedAccess,\n );\n }\n\n async #refreshOAuth(\n storage: ModelCredentialsStorage,\n scope: 'user' | 'org',\n provider: string,\n needsRefresh: (current: OAuthCredential) => boolean,\n ): Promise<string | undefined> {\n const oauthProvider = getOAuthProvider(provider);\n if (!oauthProvider) return undefined;\n // Refresh at the scope the credential actually lives at (OAuth rows are\n // user-scoped by policy, but resolve defensively from the record).\n const rowTenant = scope === 'user' ? { orgId: this.#orgId, userId: this.#userId } : { orgId: this.#orgId };\n try {\n const refreshed = await storage.refreshOAuth(\n rowTenant,\n provider,\n async current => ({\n type: 'oauth' as const,\n ...(await oauthProvider.refreshToken(current)),\n }),\n needsRefresh,\n );\n if (!refreshed) return undefined;\n this.#snapshot.set(provider, refreshed);\n return oauthProvider.getApiKey(refreshed);\n } catch {\n // Refresh failed — user needs to re-login (same posture as AuthStorage).\n return undefined;\n }\n }\n}\n\nconst tenantStores = new Map<string, TenantCredentialStore>();\nlet registeredCredentials: ModelCredentialsStorage | undefined;\nlet registeredDeploymentProviders: ReadonlySet<string> = new Set();\n\nfunction storeFor(tenant: SdkCredentialTenant, credentials: ModelCredentialsStorage): TenantCredentialStore {\n const orgId = tenantOrgId(tenant);\n const key = `${orgId}\\u0000${tenant.userId}\\u0000${tenant.credentialScope}`;\n let store = tenantStores.get(key);\n if (!store) {\n if (tenantStores.size >= MAX_CACHED_TENANTS) {\n const oldest = tenantStores.keys().next().value;\n if (oldest !== undefined) tenantStores.delete(oldest);\n }\n store = new TenantCredentialStore(\n orgId,\n tenant.userId,\n credentials,\n tenant.credentialScope,\n registeredDeploymentProviders,\n );\n tenantStores.set(key, store);\n }\n return store;\n}\n\n/**\n * Register the web tenant credential store provider with the SDK. Called by\n * the factory after storage init with the `model-credentials` domain handle;\n * from then on `resolveModel` uses per-tenant credentials and the SDK skips\n * the `loadStoredApiKeysIntoEnv` env side-channel. `deploymentProviders` are\n * the providers the operator opted in to authenticate with the server\n * process's own credentials (see `MastraFactoryConfig.deploymentModelProviders`).\n */\nexport function registerTenantCredentialResolver(\n credentials: ModelCredentialsStorage,\n deploymentProviders: ReadonlySet<string> = new Set(),\n resolveTenant?: CredentialTenantResolver,\n): void {\n registeredCredentials = credentials;\n registeredDeploymentProviders = deploymentProviders;\n tenantStores.clear();\n setCredentialStoreProvider(\n tenant => storeFor(tenant, credentials),\n resolveTenant\n ? async requestContext => {\n const tenant = await resolveTenant(requestContext);\n if (tenant) await storeFor(tenant, credentials).ensureFresh();\n return tenant;\n }\n : undefined,\n );\n}\n\n/**\n * Prime the tenant stores for a request context built outside the web layer,\n * such as a webhook-triggered session run. The auth middleware does this for\n * HTTP requests; a run that starts without one would otherwise resolve its\n * model against an empty snapshot and fail closed. No-op before registration.\n */\nexport async function primeTenantCredentialsForRequestContext(requestContext: RequestContext): Promise<void> {\n if (!registeredCredentials) return;\n await prepareCredentialTenant(requestContext);\n const tenant = resolveTenantFromRequestContext(requestContext);\n if (!tenant) return;\n await storeFor(tenant, registeredCredentials).ensureFresh();\n}\n\n/** Prime one already-resolved Factory session tenant before entering the agent run. */\nexport async function primeTenantCredentialsForTenant(tenant: SdkCredentialTenant): Promise<void> {\n if (!registeredCredentials) return;\n try {\n await storeFor(tenant, registeredCredentials).ensureFresh();\n } catch (error) {\n console.warn('[factory] Failed to prime scoped tenant model credentials', {\n orgId: tenant.orgId,\n userId: tenant.userId,\n credentialScope: tenant.credentialScope,\n error,\n });\n }\n}\n\n/**\n * The model a session should fall back to when its scope has no chosen default:\n * the provider default (`PROVIDER_DEFAULT_MODELS`) of the first provider the\n * tenant is connected to. Returns `undefined` when `currentModelId` is already\n * usable, when no connected provider has a default, or before registration.\n */\nexport async function resolveTenantProviderDefaultModel(\n tenant: SdkCredentialTenant,\n currentModelId: string | undefined,\n): Promise<string | undefined> {\n if (!registeredCredentials) return undefined;\n const store = storeFor(tenant, registeredCredentials);\n await store.ensureFresh();\n const usable = (modelId: string) => {\n const provider = modelId.split('/')[0] ?? '';\n return store.get(getAuthProviderId(provider)) !== undefined || store.allowsDeploymentCredentials(provider);\n };\n if (currentModelId && usable(currentModelId)) return undefined;\n const providerDefault = Object.entries(PROVIDER_DEFAULT_MODELS).find(\n ([provider]) => store.get(provider) !== undefined,\n )?.[1];\n if (providerDefault) return providerDefault;\n return store.get(MASTRA_GATEWAY_PROVIDER) ? `${MASTRA_GATEWAY_PREFIX}anthropic/claude-opus-5.5` : undefined;\n}\n\n/** Test hook: clear registration and cached tenant snapshots. */\nexport function resetTenantCredentialResolverForTests(): void {\n setCredentialStoreProvider(undefined);\n registeredCredentials = undefined;\n registeredDeploymentProviders = new Set();\n tenantStores.clear();\n}\n\n/**\n * Drop cached snapshots after a credential write so the change is visible to\n * the next model call immediately instead of after the snapshot TTL. An org\n * write affects every member's resolved view, so all stores under the org are\n * invalidated; a user write only drops that user's store.\n */\nexport function invalidateTenantCredentialSnapshots(tenant: { orgId: string; userId?: string }): void {\n if (tenant.userId) {\n tenantStores.delete(`${tenant.orgId}\\u0000${tenant.userId}\\u0000user`);\n tenantStores.delete(`${tenant.orgId}\\u0000${tenant.userId}\\u0000factory`);\n return;\n }\n for (const key of tenantStores.keys()) {\n if (key.startsWith(`${tenant.orgId}\\u0000`)) tenantStores.delete(key);\n }\n}\n\n/**\n * Middleware mounted after the web auth gate: primes both exclusive credential\n * scopes because the HTTP principal is known before the controller session is.\n * Cheap when fresh because each store has a TTL.\n */\nexport async function primeTenantCredentials({\n tenant,\n credentials,\n}: {\n tenant: Pick<SdkCredentialTenant, 'orgId' | 'userId'> & Partial<Pick<SdkCredentialTenant, 'credentialScope'>>;\n credentials: ModelCredentialsStorage;\n}): Promise<void> {\n await Promise.all([\n storeFor({ ...tenant, credentialScope: 'user' }, credentials).ensureFresh(),\n storeFor({ ...tenant, credentialScope: 'factory' }, credentials).ensureFresh(),\n ]);\n}\n\nexport function createTenantCredentialPrimer({\n auth,\n credentials,\n}: {\n auth: RouteAuth;\n credentials: ModelCredentialsStorage;\n}): MiddlewareHandler {\n return async (c, next) => {\n const tenant = auth.tenant(c);\n if (tenant) {\n try {\n await primeTenantCredentials({ tenant, credentials });\n } catch (error) {\n console.warn('[factory] Failed to prime tenant model credentials', {\n orgId: tenant.orgId,\n userId: tenant.userId,\n error,\n });\n }\n }\n await next();\n };\n}\n"],"mappings":";;;;;;;;AAwCA,MAAM,kBAAkB;;AAGxB,MAAM,qBAAqB;AAE3B,IAAa,wBAAb,MAA8D;CAC5D,2BAAoC;CACpC;CACA;CACA;CACA;CACA;CACA,4BAAY,IAAI,IAA4B;CAC5C,aAAa;CACb;CAEA,YACE,OACA,QACA,aACA,OACA,sCAA2C,IAAI,IAAI,GACnD;EACA,KAAK,SAAS;EACd,KAAK,UAAU;EACf,KAAK,eAAe;EACpB,KAAK,SAAS;EACd,KAAK,uBAAuB;CAC9B;;CAGA,4BAA4B,UAA2B;EACrD,OAAO,KAAK,qBAAqB,IAAI,QAAQ;CAC/C;;CAGA,MAAM,YAAY,MAAM,KAAK,IAAI,GAAkB;EACjD,IAAI,MAAM,KAAK,aAAa,iBAAiB;EAC7C,KAAK,eAAe,KAAK,SAAS,CAAC,CAAC,cAAc;GAChD,KAAK,aAAa,KAAA;EACpB,CAAC;EACD,MAAM,KAAK;CACb;CAEA,MAAM,WAA0B;EAC9B,MAAM,UAAU,MAAM,4BAA4B,KAAK,YAAY;EACnE,IAAI,CAAC,SAAS;EACd,MAAM,UAAU,MAAM,QAAQ,gBAAgB,KAAK,QAAQ,KAAK,OAAO;EACvE,MAAM,uBAAO,IAAI,IAA4B;EAC7C,MAAM,eAAe,eAAe,KAAK,MAAM;EAC/C,KAAK,MAAM,UAAU,QAAQ,QAAO,MAAK,EAAE,UAAU,YAAY,GAC/D,KAAK,IAAI,OAAO,UAAU,OAAO,UAAU;EAE7C,KAAK,YAAY;EACjB,KAAK,aAAa,KAAK,IAAI;CAC7B;;CAGA,SAAe;EACb,IAAI,KAAK,IAAI,IAAI,KAAK,cAA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ator } from '../rules/start-coordinator.js';
14
14
  import type { FactoryTransitionService } from '../rules/transition-service.js';
15
15
  import type { LiveSessions } from '../session/live-sessions.js';
16
+ import type { RunRepositoryResolution } from '../session/work-item-repository.js';
16
17
  import type { AuditEmitter } from '../storage/domains/audit/domain.js';
17
18
  import type { IntakeEvaluator } from '../storage/domains/boards/base.js';
18
19
  import type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';
19
20
  import type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';
20
- import type { CreateWorkItemInput, UpdateWorkItemInput, WorkItemsStorage } from '../storage/domains/work-items/base.js';
21
+ import type { CreateWorkItemInput, UpdateWorkItemInput, Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';
21
22
  import type { ProjectSessionsReader } from './project-sessions.js';
22
23
  import type { RouteDependencies } from './route.js';
23
24
  import { Route } from './route.js';
@@ -40,8 +41,13 @@ export interface WorkItemRoutesDeps extends RouteDependencies {
40
41
  transitionService?: Pick<FactoryTransitionService, 'transition' | 'configVersion'>;
41
42
  /** Coordinator that binds a Factory run before dispatching its kickoff. */
42
43
  startCoordinator?: Pick<FactoryStartCoordinator, 'prepare'>;
43
- /** Materialized sessions, read to report which of the listed cards are being worked or wait on someone. */
44
- liveSessions: Pick<LiveSessions, 'isRunning' | 'parked' | 'parkedIn'>;
44
+ sessionRepository?: (input: {
45
+ orgId: string;
46
+ factoryProjectId: string;
47
+ item: Card;
48
+ }) => Promise<RunRepositoryResolution>;
49
+ /** Materialized sessions, read to report which sessions wait on someone and which session a run's thread is on. */
50
+ liveSessions: Pick<LiveSessions, 'parked' | 'parkedIn' | 'sessionOnThread'>;
45
51
  /** This process's dispatcher run slots; absent or `undefined` while it runs no dispatcher. */
46
52
  runSlots?: () => {
47
53
  inUse: number;
@@ -1 +1 @@
1
- {"version":3,"file":"work-items.d.ts","sourceRoot":"","sources":["../../src/routes/work-items.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,QAAQ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Item } from "../work-items/create-work-item.js";
19
19
  import { resolveFactoryProposal, retryFactoryDecision } from "../work-items/decision-actions.js";
20
20
  import { relatedCardsIn } from "../work-items/list-related-cards.js";
21
21
  import { buildAttentionRoutes } from "./attention.js";
22
- import { boardSnapshot, etagDigest, hashedBody, listCheck, matchesEtag, movedBody, namedBody, scopedSnapshot, sendJson, sendRevalidated, sessionIdsWhere } from "./board-snapshot.js";
22
+ import { boardSnapshot, etagDigest, hashedBody, listCheck, matchesEtag, movedBody, namedBody, scopedSnapshot, sendJson, sendRevalidated } from "./board-snapshot.js";
23
23
  import { FACTORY_ROUTE_CONTRACTS } from "./contracts.js";
24
24
  import { Route, loose } from "./route.js";
25
25
  import { readRunQueue } from "./run-queue.js";
@@ -361,9 +361,6 @@ var WorkItemRoutes = class extends Route {
361
361
  const board = list.items;
362
362
  const unstarted = started ? unstartedCards(board, q ?? "", limit) : void 0;
363
363
  const part = unstarted?.cards ?? (scope ? allSessionCards(board) : sessionIds ? sessionCards(board, sessionIds) : source ? cardsFiledFrom(board, source) : ids && cardsWithIds(board, ids));
364
- const items = part ?? board;
365
- const running = sessionIdsWhere(items, (sessionId) => liveSessions.isRunning(sessionId));
366
- const parked = sessionIdsWhere(items, (sessionId) => liveSessions.parked(sessionId) !== void 0);
367
364
  if (list.changed) {
368
365
  const moved = {
369
366
  workItems: list.changed.map(toWireWorkItem),
@@ -371,13 +368,9 @@ var WorkItemRoutes = class extends Route {
371
368
  check: listCheck(board),
372
369
  cursor: list.cursor
373
370
  };
374
- return sendJson(context, movedBody({
375
- ...moved,
376
- runningSessionIds: running,
377
- parkedSessionIds: parked
378
- }), { "Cache-Control": "no-store" });
371
+ return sendJson(context, movedBody(moved), { "Cache-Control": "no-store" });
379
372
  }
380
- const snapshot = part ? scopedSnapshot(part, ids ? toVersionedWireWorkItem : toWireWorkItem, running, parked, unstarted?.total) : boardSnapshot(board, toWireWorkItem, running, parked, list.cursor);
373
+ const snapshot = part ? scopedSnapshot(part, ids ? toVersionedWireWorkItem : toWireWorkItem, unstarted?.total) : boardSnapshot(board, toWireWorkItem, list.cursor);
381
374
  return sendRevalidated(context, snapshot);
382
375
  }
383
376
  }),
@@ -507,12 +500,7 @@ var WorkItemRoutes = class extends Route {
507
500
  id: path.data.boardKey,
508
501
  phases
509
502
  }, view, resolved.userId, wireVersion);
510
- const names = {
511
- ...body,
512
- runningSessionIds: sessionIdsWhere(named, (sessionId) => liveSessions.isRunning(sessionId)),
513
- parkedSessionIds: sessionIdsWhere(named, (sessionId) => liveSessions.parked(sessionId) !== void 0)
514
- };
515
- return sendRevalidated(context, namedBody(names, withBodies ? () => ({ workItems: named.map(toVersionedWireWorkItem) }) : void 0));
503
+ return sendRevalidated(context, namedBody(body, withBodies ? () => ({ workItems: named.map(toVersionedWireWorkItem) }) : void 0));
516
504
  }
517
505
  }),
518
506
  registerApiRoute(FACTORY_ROUTE_CONTRACTS.workItemFilterOptions.path, {
@@ -729,6 +717,41 @@ var WorkItemRoutes = class extends Route {
729
717
  return c.json({ result }, result.code === "stale" ? 409 : 422);
730
718
  }
731
719
  }),
720
+ registerApiRoute(FACTORY_ROUTE_CONTRACTS.workItemSessionRepository.path, {
721
+ method: FACTORY_ROUTE_CONTRACTS.workItemSessionRepository.method,
722
+ requiresAuth: false,
723
+ handler: async (c) => {
724
+ const context = loose(c);
725
+ const resolved = await this.#resolveProject(context);
726
+ if ("response" in resolved) return resolved.response;
727
+ const parsedPath = FACTORY_ROUTE_CONTRACTS.workItemSessionRepository.pathSchema.safeParse({
728
+ id: resolved.factoryProjectId,
729
+ workItemId: context.req.param("workItemId")
730
+ });
731
+ if (!parsedPath.success) return c.json({ error: "Work item not found" }, 404);
732
+ await workItems.ensureReady();
733
+ const item = await workItems.get({
734
+ orgId: resolved.orgId,
735
+ id: parsedPath.data.workItemId
736
+ });
737
+ if (!item || item.factoryProjectId !== resolved.factoryProjectId) return c.json({ error: "Work item not found" }, 404);
738
+ const { sessionRepository } = this.deps;
739
+ if (!sessionRepository) return c.json({ error: "factory_session_repository_unavailable" }, 503);
740
+ const resolution = await sessionRepository({
741
+ orgId: resolved.orgId,
742
+ factoryProjectId: resolved.factoryProjectId,
743
+ item
744
+ });
745
+ return c.json(resolution.status === "resolved" ? {
746
+ status: resolution.status,
747
+ projectRepositoryId: resolution.projectRepositoryId,
748
+ slug: resolution.slug
749
+ } : {
750
+ status: resolution.status,
751
+ hint: resolution.hint
752
+ });
753
+ }
754
+ }),
732
755
  registerApiRoute(FACTORY_ROUTE_CONTRACTS.workItemWorkingPullRequest.path, {
733
756
  method: FACTORY_ROUTE_CONTRACTS.workItemWorkingPullRequest.method,
734
757
  requiresAuth: false,