@mastra/factory 0.4.0 → 0.5.0-alpha.1

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 (34) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/factory.d.ts.map +1 -1
  3. package/dist/factory.js +7 -4
  4. package/dist/factory.js.map +1 -1
  5. package/dist/integrations/base.d.ts +43 -5
  6. package/dist/integrations/base.d.ts.map +1 -1
  7. package/dist/integrations/github/webhook.d.ts +25 -5
  8. package/dist/integrations/github/webhook.d.ts.map +1 -1
  9. package/dist/integrations/github/webhook.js +13 -4
  10. package/dist/integrations/github/webhook.js.map +1 -1
  11. package/dist/integrations/platform/github/event-worker.d.ts +2 -7
  12. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  13. package/dist/integrations/platform/github/event-worker.js +1 -0
  14. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  15. package/dist/integrations/slack/connect-route.d.ts +46 -0
  16. package/dist/integrations/slack/connect-route.d.ts.map +1 -0
  17. package/dist/integrations/slack/connect-route.js +186 -0
  18. package/dist/integrations/slack/connect-route.js.map +1 -0
  19. package/dist/integrations/slack/integration.d.ts +62 -0
  20. package/dist/integrations/slack/integration.d.ts.map +1 -0
  21. package/dist/integrations/slack/integration.js +67 -0
  22. package/dist/integrations/slack/integration.js.map +1 -0
  23. package/dist/integrations/slack/slack.d.ts +273 -0
  24. package/dist/integrations/slack/slack.d.ts.map +1 -0
  25. package/dist/integrations/slack/slack.js +406 -0
  26. package/dist/integrations/slack/slack.js.map +1 -0
  27. package/dist/routes/surface.d.ts +6 -0
  28. package/dist/routes/surface.d.ts.map +1 -1
  29. package/dist/routes/surface.js +28 -1
  30. package/dist/routes/surface.js.map +1 -1
  31. package/dist/workspace.d.ts.map +1 -1
  32. package/dist/workspace.js +2 -1
  33. package/dist/workspace.js.map +1 -1
  34. package/package.json +5 -3
@@ -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 } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { FactoryStorage } from '@mastra/core/storage';\n\nimport type { FactoryIntegration, IntegrationContext } from '../integrations/base.js';\nimport { getGithubFeatureDiagnostics } from '../integrations/github/config.js';\nimport { ensureFactoryRuleSession } from '../integrations/github/factory-session.js';\nimport type { GithubIntegration } from '../integrations/github/integration.js';\nimport type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';\nimport { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { FactoryTransitionService } from '../rules/transition-service.js';\nimport type { FactoryRules } from '../rules/types.js';\nimport type { SandboxFleet } from '../sandbox/fleet.js';\nimport type { StateSigner } from '../state-signing.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.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 { ModelPacksStorage } from '../storage/domains/model-packs/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport type { SourceControlStorage } from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { ConfigRoutes } from './config.js';\nimport { invalidateCustomProvidersSnapshots } from './custom-provider-source.js';\nimport { buildFsRoutes } from './fs.js';\nimport { IntakeRoutes } from './intake.js';\nimport { OAuthRoutes } from './oauth.js';\nimport type { RouteAuth } from './route.js';\nimport { SkillRoutes } from './skills.js';\nimport { invalidateTenantCredentialSnapshots } from './tenant-credentials.js';\nimport { WorkItemRoutes } from './work-items.js';\n\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 /** Request-auth seam threaded from the host (no service locator). */\n auth: RouteAuth;\n authStorage: AuthStorage;\n audit: AuditEmitter;\n fsRoot?: string;\n publicOrigin: string;\n stateSigner?: StateSigner;\n /** Sandbox fleet constructed by the factory (disabled when no machine). */\n fleet: SandboxFleet;\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 modelPacks: ModelPacksStorage;\n projects: FactoryProjectsStorage;\n queueHealth: QueueHealthStorage;\n workItems: WorkItemsStorage;\n channelIdentity: ChannelIdentityStorage;\n };\n integrations?: IntegrationRegistration[];\n intakeReady: boolean;\n factoryReady: boolean;\n /** Resolved Factory rule set, threaded from the host (no service locator). */\n rules: FactoryRules;\n factoryTransitionService?: FactoryTransitionService;\n onFactoryRuntime?: (runtime: {\n transitionService: FactoryTransitionService;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n }) => void;\n}\n\nfunction guardIntegrationRoutes({\n integration,\n ready,\n ensureReady,\n routes,\n}: IntegrationRegistration & { routes: ApiRoute[] }): ApiRoute[] {\n if (ready) return routes;\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 try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\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 try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context);\n };\n },\n };\n });\n}\n\nexport function factoryRuleBranch(item: FactoryBindingPreparationInput['item']): string {\n const metadata = item.metadata ?? {};\n const issueNumber = metadata.githubIssueNumber ?? metadata.number;\n if (\n item.externalSource?.integrationId === 'github' &&\n item.externalSource.type === 'issue' &&\n typeof issueNumber === 'number'\n ) {\n return `factory/issue-${issueNumber}`;\n }\n const pullRequestNumber = metadata.githubPullRequestNumber ?? metadata.number;\n if (\n item.externalSource?.integrationId === 'github' &&\n item.externalSource.type === 'pull-request' &&\n typeof pullRequestNumber === 'number'\n ) {\n return `factory/pr-${pullRequestNumber}`;\n }\n throw new Error('Factory skill invocation requires a GitHub issue or pull request number.');\n}\n\nasync function prepareFactoryRuleBinding(\n github: GithubIntegration,\n coordinator: FactoryStartCoordinator,\n input: FactoryBindingPreparationInput,\n): Promise<void> {\n const branch = factoryRuleBranch(input.item);\n const repositorySlug =\n typeof input.item.metadata?.repository === 'string' ? input.item.metadata.repository : undefined;\n const preparedSession = await ensureFactoryRuleSession({\n github,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n repositorySlug,\n branch,\n });\n const destinationStage = input.item.stages.length === 1 ? input.item.stages[0] : undefined;\n if (!destinationStage) throw new Error('Factory skill invocation requires one exclusive board stage.');\n\n await coordinator.prepare({\n orgId: input.record.orgId,\n userId: preparedSession.userId,\n factoryProjectId: input.record.factoryProjectId,\n sessionId: preparedSession.sessionId,\n threadTitle: `${input.role === 'review' ? 'PR' : 'Issue'}: ${input.item.title}`,\n kickoffKey: input.record.id,\n destinationStage: destinationStage as 'intake' | 'triage' | 'planning' | 'execute' | 'review' | 'done',\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: ['intake'],\n sessions: input.item.sessions,\n metadata: input.item.metadata,\n },\n },\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' | 'publicOrigin' | 'auth' | 'fleet' | 'factoryStorage' | 'integrationStorage' | 'sourceControlStorage'\n > & {\n stateSigner: StateSigner;\n emitAudit?: AuditEmitter['emit'];\n rules: FactoryRules;\n factoryReady: boolean;\n domains: Pick<FactoryApiRoutesDeps['domains'], 'projects' | 'intake' | 'workItems' | 'channelIdentity'>;\n },\n integrationId: string,\n): IntegrationContext {\n return {\n auth: deps.auth,\n fleet: deps.fleet,\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 projects: deps.domains.projects,\n intake: deps.domains.intake,\n channelIdentity: deps.domains.channelIdentity,\n },\n ...(deps.factoryReady ? { rules: { config: deps.rules, workItems: deps.domains.workItems } } : {}),\n ...(deps.emitAudit ? { hooks: { emitAudit: deps.emitAudit } } : {}),\n };\n}\n\n/**\n * Disabled-status stub for the well-known integration ids. The SPA polls\n * `/web/github/status` and `/web/linear/status` unconditionally, so when an\n * integration is absent (or not ready) the status contract must still hold.\n * Unknown custom ids get no stub — the SPA doesn't 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 fleet: deps.fleet,\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 return [];\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/model-pack/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\n const integrationRoutes = registrations.flatMap(registration => {\n const { integration } = registration;\n if (!deps.stateSigner) return disabledIntegrationStatusRoutes(deps, integration.id, true);\n const context = buildIntegrationContext({ ...deps, stateSigner: deps.stateSigner, emitAudit }, integration.id);\n return guardIntegrationRoutes({ ...registration, routes: integration.routes(context) });\n });\n // Absent known integrations still get their disabled-status stub.\n const absentStubs = ['github', 'linear']\n .filter(id => !registrations.some(({ integration }) => integration.id === id))\n .flatMap(id => disabledIntegrationStatusRoutes(deps, id));\n\n const transitionService = deps.factoryReady\n ? (deps.factoryTransitionService ??\n new FactoryTransitionService({ rules: deps.rules, storage: deps.domains.workItems }))\n : undefined;\n const startCoordinator = transitionService\n ? new FactoryStartCoordinator(\n deps.controller,\n deps.domains.workItems,\n transitionService,\n githubIntegration?.sourceControlStorage,\n deps.domains.memorySettings,\n )\n : undefined;\n if (transitionService && startCoordinator) {\n deps.onFactoryRuntime?.({\n transitionService,\n ...(githubIntegration\n ? {\n prepareBinding: (input: FactoryBindingPreparationInput) =>\n prepareFactoryRuleBinding(githubIntegration, startCoordinator, input),\n }\n : {}),\n });\n }\n\n return [\n ...buildFsRoutes({\n root: deps.fsRoot,\n sessionFs: {\n auth: deps.auth,\n fleet: deps.fleet,\n sessions: deps.sourceControlStorage.forIntegration('github').sessions,\n },\n }),\n ...new ConfigRoutes({\n auth: deps.auth,\n controller: deps.controller,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n modelPacks: deps.domains.modelPacks,\n memorySettings: deps.domains.memorySettings,\n customProviders: deps.domains.customProviders,\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 SkillRoutes({\n auth: deps.auth,\n controllerId: deps.controllerId,\n controller: deps.controller,\n sourceControlStorage: githubStorage,\n ensureSourceControlReady: githubRegistration?.ensureReady,\n }).routes(),\n ...integrationRoutes,\n ...absentStubs,\n ...(deps.intakeReady\n ? new IntakeRoutes({\n auth: deps.auth,\n audit: deps.audit,\n intake: deps.domains.intake,\n integrations: (deps.integrations ?? []).flatMap(({ integration }) =>\n integration.intake ? [{ id: integration.id, intake: integration.intake }] : [],\n ),\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 queueHealth: deps.domains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AAG,IAAI,YAAY;GACjB,MAAM,KAAK;GACX,cAAc,KAAK;GACnB,YAAY,KAAK;GACjB,sBAAsB;GACtB,0BAA0B,oBAAoB;EAChD,CAAC,CAAC,CAAC,OAAO;EACV,GAAG;EACH,GAAG;EACH,GAAI,KAAK,cACL,IAAI,aAAa;GACf,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,QAAQ,KAAK,QAAQ;GACrB,eAAe,KAAK,gBAAgB,CAAC,EAAA,CAAG,SAAS,EAAE,kBACjD,YAAY,SAAS,CAAC;IAAE,IAAI,YAAY;IAAI,QAAQ,YAAY;GAAO,CAAC,IAAI,CAAC,CAC/E;EACF,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;EACL,GAAI,KAAK,eACL,IAAI,eAAe;GACjB,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,aAAa,KAAK,QAAQ;GAC1B;GACA;EACF,CAAC,CAAC,CAAC,OAAO,IACV,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 } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { FactoryStorage } from '@mastra/core/storage';\n\nimport type { FactoryIntegration, IntegrationContext } from '../integrations/base.js';\nimport { getGithubFeatureDiagnostics } from '../integrations/github/config.js';\nimport { ensureFactoryRuleSession } from '../integrations/github/factory-session.js';\nimport type { GithubIntegration } from '../integrations/github/integration.js';\nimport type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';\nimport { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { FactoryTransitionService } from '../rules/transition-service.js';\nimport type { FactoryRules } from '../rules/types.js';\nimport type { SandboxFleet } from '../sandbox/fleet.js';\nimport type { StateSigner } from '../state-signing.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.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 { ModelPacksStorage } from '../storage/domains/model-packs/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport type { SourceControlStorage } from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { ConfigRoutes } from './config.js';\nimport { invalidateCustomProvidersSnapshots } from './custom-provider-source.js';\nimport { buildFsRoutes } from './fs.js';\nimport { IntakeRoutes } from './intake.js';\nimport { OAuthRoutes } from './oauth.js';\nimport type { RouteAuth } from './route.js';\nimport { SkillRoutes } from './skills.js';\nimport { invalidateTenantCredentialSnapshots } from './tenant-credentials.js';\nimport { WorkItemRoutes } from './work-items.js';\n\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 /** Request-auth seam threaded from the host (no service locator). */\n auth: RouteAuth;\n authStorage: AuthStorage;\n audit: AuditEmitter;\n fsRoot?: string;\n publicOrigin: string;\n stateSigner?: StateSigner;\n /** Sandbox fleet constructed by the factory (disabled when no machine). */\n fleet: SandboxFleet;\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 modelPacks: ModelPacksStorage;\n projects: FactoryProjectsStorage;\n queueHealth: QueueHealthStorage;\n workItems: WorkItemsStorage;\n channelIdentity: ChannelIdentityStorage;\n };\n integrations?: IntegrationRegistration[];\n intakeReady: boolean;\n factoryReady: boolean;\n /** Resolved Factory rule set, threaded from the host (no service locator). */\n rules: FactoryRules;\n factoryTransitionService?: FactoryTransitionService;\n onFactoryRuntime?: (runtime: {\n transitionService: FactoryTransitionService;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n }) => void;\n}\n\nfunction guardIntegrationRoutes({\n integration,\n ready,\n ensureReady,\n routes,\n}: IntegrationRegistration & { routes: ApiRoute[] }): ApiRoute[] {\n if (ready) return routes;\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 try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\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 try {\n await ensureReady();\n } catch {\n return context.json(\n { error: 'integration_unavailable', message: `${integration.id} integration is unavailable.` },\n 503,\n );\n }\n return handler(context);\n };\n },\n };\n });\n}\n\nexport function factoryRuleBranch(item: FactoryBindingPreparationInput['item']): string {\n const metadata = item.metadata ?? {};\n const issueNumber = metadata.githubIssueNumber ?? metadata.number;\n if (\n item.externalSource?.integrationId === 'github' &&\n item.externalSource.type === 'issue' &&\n typeof issueNumber === 'number'\n ) {\n return `factory/issue-${issueNumber}`;\n }\n const pullRequestNumber = metadata.githubPullRequestNumber ?? metadata.number;\n if (\n item.externalSource?.integrationId === 'github' &&\n item.externalSource.type === 'pull-request' &&\n typeof pullRequestNumber === 'number'\n ) {\n return `factory/pr-${pullRequestNumber}`;\n }\n throw new Error('Factory skill invocation requires a GitHub issue or pull request number.');\n}\n\nasync function prepareFactoryRuleBinding(\n github: GithubIntegration,\n coordinator: FactoryStartCoordinator,\n input: FactoryBindingPreparationInput,\n): Promise<void> {\n const branch = factoryRuleBranch(input.item);\n const repositorySlug =\n typeof input.item.metadata?.repository === 'string' ? input.item.metadata.repository : undefined;\n const preparedSession = await ensureFactoryRuleSession({\n github,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n repositorySlug,\n branch,\n });\n const destinationStage = input.item.stages.length === 1 ? input.item.stages[0] : undefined;\n if (!destinationStage) throw new Error('Factory skill invocation requires one exclusive board stage.');\n\n await coordinator.prepare({\n orgId: input.record.orgId,\n userId: preparedSession.userId,\n factoryProjectId: input.record.factoryProjectId,\n sessionId: preparedSession.sessionId,\n threadTitle: `${input.role === 'review' ? 'PR' : 'Issue'}: ${input.item.title}`,\n kickoffKey: input.record.id,\n destinationStage: destinationStage as 'intake' | 'triage' | 'planning' | 'execute' | 'review' | 'done',\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: ['intake'],\n sessions: input.item.sessions,\n metadata: input.item.metadata,\n },\n },\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' | 'publicOrigin' | 'auth' | 'fleet' | 'factoryStorage' | 'integrationStorage' | 'sourceControlStorage'\n > & {\n stateSigner: StateSigner;\n emitAudit?: AuditEmitter['emit'];\n rules: FactoryRules;\n factoryReady: boolean;\n domains: Pick<FactoryApiRoutesDeps['domains'], 'projects' | 'intake' | 'workItems' | 'channelIdentity'>;\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 fleet: deps.fleet,\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 projects: deps.domains.projects,\n intake: deps.domains.intake,\n channelIdentity: deps.domains.channelIdentity,\n },\n ...(deps.factoryReady ? { rules: { config: deps.rules, workItems: deps.domains.workItems } } : {}),\n ...(deps.emitAudit ? { hooks: { emitAudit: deps.emitAudit } } : {}),\n };\n}\n\n/**\n * Disabled-status stub for the well-known integration ids. The SPA polls\n * `/web/github/status` and `/web/linear/status` unconditionally, so when an\n * integration is absent (or not ready) the status contract must still hold.\n * Unknown custom ids get no stub — the SPA doesn't 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 fleet: deps.fleet,\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 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\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/model-pack/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\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 stateSigner: deps.stateSigner,\n emitAudit,\n ...(githubRegistration ? { sourceControlOwnerId: 'github' } : {}),\n },\n integration.id,\n );\n return guardIntegrationRoutes({ ...registration, routes: integration.routes(context) });\n });\n // Absent known integrations still get their disabled-status stub.\n const absentStubs = ['github', 'linear']\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({ rules: deps.rules, storage: deps.domains.workItems }))\n : undefined;\n const startCoordinator = transitionService\n ? new FactoryStartCoordinator(\n deps.controller,\n deps.domains.workItems,\n transitionService,\n githubIntegration?.sourceControlStorage,\n deps.domains.memorySettings,\n )\n : undefined;\n if (transitionService && startCoordinator) {\n deps.onFactoryRuntime?.({\n transitionService,\n ...(githubIntegration\n ? {\n prepareBinding: (input: FactoryBindingPreparationInput) =>\n prepareFactoryRuleBinding(githubIntegration, startCoordinator, input),\n }\n : {}),\n });\n }\n\n return [\n ...buildFsRoutes({\n root: deps.fsRoot,\n sessionFs: {\n auth: deps.auth,\n fleet: deps.fleet,\n sessions: deps.sourceControlStorage.forIntegration('github').sessions,\n },\n }),\n ...new ConfigRoutes({\n auth: deps.auth,\n controller: deps.controller,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n modelPacks: deps.domains.modelPacks,\n memorySettings: deps.domains.memorySettings,\n customProviders: deps.domains.customProviders,\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 SkillRoutes({\n auth: deps.auth,\n controllerId: deps.controllerId,\n controller: deps.controller,\n sourceControlStorage: githubStorage,\n ensureSourceControlReady: githubRegistration?.ensureReady,\n }).routes(),\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 integrations: (deps.integrations ?? []).flatMap(({ integration }) =>\n integration.intake ? [{ id: integration.id, intake: integration.intake }] : [],\n ),\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 queueHealth: deps.domains.queueHealth,\n transitionService,\n startCoordinator,\n }).routes()\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;AAqFA,SAAS,uBAAuB,EAC9B,aACA,OACA,aACA,UAC+D;CAC/D,IAAI,OAAO,OAAO;CAClB,OAAO,OAAO,KAAI,UAAS;EACzB,IAAI,aAAa,OAAO;GACtB,MAAM,UAAU,MAAM;GACtB,OAAO;IACL,GAAG;IACH,SAAS,OAAO,YAA2C;KACzD,IAAI;MACF,MAAM,YAAY;KACpB,QAAQ;MACN,OAAO,QAAQ,KACb;OAAE,OAAO;OAA2B,SAAS,GAAG,YAAY,GAAG;MAA8B,GAC7F,GACF;KACF;KACA,OAAO,QAAQ,SAAS,YAAY,CAAC,CAAC;IACxC;GACF;EACF;EAEA,MAAM,gBAAgB,MAAM;EAC5B,OAAO;GACL,GAAG;GACH,eAAe,OAAO,SAA8C;IAClE,MAAM,UAAU,MAAM,cAAc,IAAI;IACxC,OAAO,OAAO,YAA2C;KACvD,IAAI;MACF,MAAM,YAAY;KACpB,QAAQ;MACN,OAAO,QAAQ,KACb;OAAE,OAAO;OAA2B,SAAS,GAAG,YAAY,GAAG;MAA8B,GAC7F,GACF;KACF;KACA,OAAO,QAAQ,OAAO;IACxB;GACF;EACF;CACF,CAAC;AACH;AAEA,SAAgB,kBAAkB,MAAsD;CACtF,MAAM,WAAW,KAAK,YAAY,CAAC;CACnC,MAAM,cAAc,SAAS,qBAAqB,SAAS;CAC3D,IACE,KAAK,gBAAgB,kBAAkB,YACv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OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,aAAa,KAAK,QAAQ;GAC1B;GACA;EACF,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;CACP;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.d.ts","sourceRoot":"","sources":["../src/workspace.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAKxE,OAAO,EAAE,YAAY,EAAoB,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAInF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAC;AAY9E,OAAO,KAAK,EAAuB,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAK7E,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAElE;AA+ED,KAAK,uBAAuB,GAAG,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAAC;AAEzE,MAAM,WAAW,6BAA6B;IAC5C,wEAAwE;IACxE,OAAO,CAAC,EAAE,0BAA0B,CAAC;IACrC,gFAAgF;IAChF,MAAM,CAAC,EAAE,iBAAiB,CAAC;IAC3B,0EAA0E;IAC1E,KAAK,CAAC,EAAE,YAAY,CAAC;IACrB;;iEAE6D;IAC7D,SAAS,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,yBAAyB,CAAC,CAAC;CAC/D;AAED,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,6BAAkC,IAYlE,4CAA4C,uBAAuB,2PA8PlF;AAED,eAAO,MAAM,mBAAmB,+CAhQ4B,uBAAuB,0PAgQxB,CAAC"}
1
+ {"version":3,"file":"workspace.d.ts","sourceRoot":"","sources":["../src/workspace.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAKxE,OAAO,EAAE,YAAY,EAAoB,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAInF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAC;AAY9E,OAAO,KAAK,EAAuB,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAK7E,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAElE;AA+ED,KAAK,uBAAuB,GAAG,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAAC;AAEzE,MAAM,WAAW,6BAA6B;IAC5C,wEAAwE;IACxE,OAAO,CAAC,EAAE,0BAA0B,CAAC;IACrC,gFAAgF;IAChF,MAAM,CAAC,EAAE,iBAAiB,CAAC;IAC3B,0EAA0E;IAC1E,KAAK,CAAC,EAAE,YAAY,CAAC;IACrB;;iEAE6D;IAC7D,SAAS,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,yBAAyB,CAAC,CAAC;CAC/D;AAED,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,6BAAkC,IAYlE,4CAA4C,uBAAuB,2PAmQlF;AAED,eAAO,MAAM,mBAAmB,+CArQ4B,uBAAuB,0PAqQxB,CAAC"}
package/dist/workspace.js CHANGED
@@ -90,7 +90,8 @@ function createWorkspaceFactory(options = {}) {
90
90
  }
91
91
  const user = requestContext.get("user");
92
92
  const userId = getFactoryAuthUserId(user);
93
- if (!user?.organizationId || !userId || user.organizationId !== session.orgId || userId !== session.userId) throw new Error(`Factory session ${session.sessionId} is not available to the current user`);
93
+ if (!user?.organizationId || !userId) throw new Error(`Factory session ${session.sessionId} was resolved without a caller identity`);
94
+ if (user.organizationId !== session.orgId || userId !== session.userId) throw new Error(`Factory session ${session.sessionId} is not available to the current user`);
94
95
  if (!sandboxConfig || !github || !fleet) throw new Error("GitHub and sandbox providers are required to create a Factory session workspace");
95
96
  const storage = github.sourceControlStorage;
96
97
  const projectRepository = await storage.projectRepositories.get({
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.js","names":["#factorySource","#fallbackSkillRoots","#isFactoryPath","#factoryPath"],"sources":["../src/workspace.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { SandboxFilesystem } from '@mastra/code-sdk/agents/sandbox-filesystem';\nimport { MASTRACODE_WORKSPACE_TOOLS } from '@mastra/code-sdk/agents/tool-availability';\nimport { getDynamicWorkspace } from '@mastra/code-sdk/agents/workspace';\nimport type { WorkspaceSkillExtension } from '@mastra/code-sdk/agents/workspace';\nimport { DEFAULT_CONFIG_DIR } from '@mastra/code-sdk/constants';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { LocalSandbox, LocalSkillSource, Workspace } from '@mastra/core/workspace';\nimport type { SkillSource, SkillSourceEntry, SkillSourceStat } from '@mastra/core/workspace';\nimport { getFactoryAuthUserId } from './auth.js';\nimport type { FactoryAuthUser } from './auth.js';\nimport type { MastraFactorySandboxConfig } from './factory.js';\nimport type { GithubIntegration } from './integrations/github/integration.js';\nimport { getGithubPat } from './integrations/github/pat.js';\nimport type { GithubPatKind } from './integrations/github/pat.js';\nimport {\n checkoutSessionBranch,\n MaterializeError,\n materializeRepo,\n recycleClaimedWorkdir,\n runWorktreeSetup,\n} from './integrations/github/sandbox.js';\nimport { registerGithubPatKind, registerGithubTokenInjector } from './integrations/github/token-refresh.js';\nimport { getFactorySessionAddress } from './rules/binding-context.js';\nimport type { SandboxBindingStore, SandboxFleet } from './sandbox/fleet.js';\nimport type { WorkItemsStorage } from './storage/domains/work-items/base.js';\n\nconst WORKSPACE_ID_PREFIX = 'mfw';\nconst SESSION_CHECKPOINT_PREFIX = 'mastracode-session';\n\nexport function checkpointNameForSession(sessionId: string): string {\n return `${SESSION_CHECKPOINT_PREFIX}-${sessionId}`;\n}\n\nconst bundleDirectory = dirname(fileURLToPath(import.meta.url));\nconst bundledFactorySkillsPath = join(bundleDirectory, 'factory-skills');\nconst FACTORY_SKILLS_SOURCE_PATH =\n [\n // Deploy bundle: the consumer copies `factory-skills/` next to the built\n // server module (e.g. via its public/ dir).\n bundledFactorySkillsPath,\n // Package layout: `dist/../factory-skills` (also `src/../factory-skills`\n // when running tests against sources).\n join(bundleDirectory, '..', 'factory-skills'),\n // Consumer repo running from its package root before a build.\n join(process.cwd(), 'src', 'mastra', 'public', 'factory-skills'),\n ].find(existsSync) ?? bundledFactorySkillsPath;\nconst FACTORY_SKILLS_MOUNT = path.resolve(path.parse(process.cwd()).root, '__mastracode_factory_skills__');\nconst FACTORY_SKILL_NAMES = new Set(['configure-factory-rules', 'factory-plan', 'factory-review', 'factory-triage']);\n\nclass FactorySkillSource implements SkillSource {\n readonly #factorySource = new LocalSkillSource({ basePath: FACTORY_SKILLS_SOURCE_PATH });\n readonly #fallbackSkillRoots: Set<string>;\n\n constructor(\n readonly fallback: SkillSource,\n fallbackSkillRoots: string[],\n ) {\n this.#fallbackSkillRoots = new Set(fallbackSkillRoots.map(skillPath => path.normalize(skillPath)));\n }\n\n #isFactoryPath(skillPath: string): boolean {\n const normalized = path.normalize(skillPath);\n return normalized === FACTORY_SKILLS_MOUNT || normalized.startsWith(`${FACTORY_SKILLS_MOUNT}${path.sep}`);\n }\n\n #factoryPath(skillPath: string): string {\n return path.relative(FACTORY_SKILLS_MOUNT, path.normalize(skillPath));\n }\n\n exists(skillPath: string): Promise<boolean> {\n return this.#isFactoryPath(skillPath)\n ? this.#factorySource.exists(this.#factoryPath(skillPath))\n : this.fallback.exists(skillPath);\n }\n\n stat(skillPath: string): Promise<SkillSourceStat> {\n return this.#isFactoryPath(skillPath)\n ? this.#factorySource.stat(this.#factoryPath(skillPath))\n : this.fallback.stat(skillPath);\n }\n\n readFile(skillPath: string): Promise<string | Buffer> {\n return this.#isFactoryPath(skillPath)\n ? this.#factorySource.readFile(this.#factoryPath(skillPath))\n : this.fallback.readFile(skillPath);\n }\n\n async readdir(skillPath: string): Promise<SkillSourceEntry[]> {\n if (this.#isFactoryPath(skillPath)) {\n return this.#factorySource.readdir(this.#factoryPath(skillPath));\n }\n const entries = await this.fallback.readdir(skillPath);\n if (this.#fallbackSkillRoots.has(path.normalize(skillPath))) {\n return entries.filter(entry => !FACTORY_SKILL_NAMES.has(entry.name));\n }\n return entries;\n }\n\n realpath(skillPath: string): Promise<string> {\n if (this.#isFactoryPath(skillPath)) return Promise.resolve(path.normalize(skillPath));\n return this.fallback.realpath ? this.fallback.realpath(skillPath) : Promise.resolve(skillPath);\n }\n}\n\nconst factorySkillExtension: WorkspaceSkillExtension = {\n id: 'web-factory',\n paths: [FACTORY_SKILLS_MOUNT],\n createSource: (fallback, fallbackSkillRoots) => new FactorySkillSource(fallback, fallbackSkillRoots),\n};\n\ntype DynamicWorkspaceContext = Parameters<typeof getDynamicWorkspace>[0];\n\nexport interface CreateWorkspaceFactoryOptions {\n /** Factory sandbox runtime config (template machine + workdir base). */\n sandbox?: MastraFactorySandboxConfig;\n /** GitHub integration used to resolve Factory sessions and mint repo tokens. */\n github?: GithubIntegration;\n /** Fleet the per-session sandboxes are provisioned/reattached through. */\n fleet?: SandboxFleet;\n /** Work-items storage used to resolve the session's run-binding role, so\n * review-board sessions get the reviewer PAT as `GH_TOKEN`. Optional —\n * without it every session uses the default (worker) PAT. */\n workItems?: Pick<WorkItemsStorage, 'findRunBindingBySession'>;\n}\n\nexport function createWorkspaceFactory(options: CreateWorkspaceFactoryOptions = {}) {\n const { sandbox: sandboxConfig, github, fleet, workItems } = options;\n const isLocalSandbox = sandboxConfig?.machine instanceof LocalSandbox;\n const githubTokenInjectors = new Map<\n string,\n { inject: (token: string) => void; patKind: GithubPatKind; ghToken: string }\n >();\n // Concurrent requests for the same session (thread list + activity polling +\n // chat) must not each provision a sandbox and clone the repository. The\n // first caller materializes; followers await the same promise.\n const inflightMaterializations = new Map<string, Promise<Workspace>>();\n\n return async ({ requestContext, mastra, skillExtension }: DynamicWorkspaceContext) => {\n const effectiveSkillExtension = skillExtension ?? factorySkillExtension;\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const session =\n ctx?.resourceId && github ? await github.sourceControlStorage.sessions.getBySessionId(ctx.resourceId) : null;\n\n if (!session) {\n if (sandboxConfig && !isLocalSandbox) {\n throw new Error('A Factory session ID is required to create a remote sandbox workspace');\n }\n return getDynamicWorkspace({ requestContext, mastra, skillExtension: effectiveSkillExtension });\n }\n\n const user = requestContext.get('user') as FactoryAuthUser | undefined;\n const userId = getFactoryAuthUserId(user);\n if (!user?.organizationId || !userId || user.organizationId !== session.orgId || userId !== session.userId) {\n throw new Error(`Factory session ${session.sessionId} is not available to the current user`);\n }\n if (!sandboxConfig || !github || !fleet) {\n throw new Error('GitHub and sandbox providers are required to create a Factory session workspace');\n }\n\n const storage = github.sourceControlStorage;\n const projectRepository = await storage.projectRepositories.get({\n orgId: session.orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) throw new Error(`Repository link ${session.projectRepositoryId} was not found`);\n const connection = await storage.connections.get({ orgId: session.orgId, id: projectRepository.connectionId });\n const repository = await storage.repositories.get({ orgId: session.orgId, id: projectRepository.repositoryId });\n if (!connection || !repository) throw new Error(`Repository link ${session.projectRepositoryId} is incomplete`);\n const installation = await storage.installations.get({ orgId: session.orgId, id: connection.installationId });\n if (!installation) throw new Error(`GitHub installation ${connection.installationId} was not found`);\n const repoFullName = repository.slug;\n\n let workdir = isLocalSandbox\n ? fleet.computeLocalSessionWorkdir(repoFullName, session.id)\n : (session.sandboxWorkdir ?? projectRepository.sandboxWorkdir);\n // The system prompt derives its working directory from `state.projectPath`\n // and falls back to the server's own process.cwd() when unset — which\n // points the agent at the host checkout (and lets it run `git checkout`\n // there instead of in its session workdir). Pin it to the session workdir.\n // During createSession this seeds the session's initial state (the\n // workspace resolves before the session is built); on later requests it\n // self-heals live state.\n if (ctx && workdir && ctx.getState()?.projectPath !== workdir) {\n await ctx.setState({ projectPath: workdir, projectName: repoFullName });\n }\n const binding: SandboxBindingStore = {\n // Read through to the session row so teardown after a fresh provision\n // sees the just-persisted id instead of a stale snapshot.\n get sandboxId() {\n return session.sandboxId;\n },\n checkpointName: checkpointNameForSession(session.id),\n setSandboxId: async id => {\n await storage.sessions.setSandbox({ id: session.id, sandboxId: id, sandboxWorkdir: workdir });\n session.sandboxId = id;\n session.sandboxWorkdir = workdir;\n },\n clear: async () => {\n await storage.sessions.setSandbox({ id: session.id, sandboxId: null, sandboxWorkdir: workdir });\n session.sandboxId = null;\n },\n };\n\n const extensionId = effectiveSkillExtension ? `-${effectiveSkillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectRepository.id}-${session.id}${extensionId}`;\n const configDir = sandboxConfig.workdir ?? DEFAULT_CONFIG_DIR;\n try {\n const existing = mastra?.getWorkspaceById(workspaceId) as Workspace | undefined;\n if (existing) {\n existing.setToolsConfig(MASTRACODE_WORKSPACE_TOOLS);\n const registered = githubTokenInjectors.get(workspaceId);\n if (registered) {\n registerGithubTokenInjector(requestContext, registered.inject);\n registerGithubPatKind(requestContext, registered.patKind);\n // A PAT saved in Settings after this sandbox was provisioned must\n // reach the running sandbox without a server restart — re-read it\n // on every reuse and push it into the live sandbox when it changed.\n // Best-effort: a failed read or inject keeps the installed token.\n try {\n const pat = await getGithubPat(() => github.integrationStorage, session.orgId, registered.patKind);\n if (pat && pat !== registered.ghToken) {\n registered.inject(pat);\n }\n } catch {\n // Keep the token already installed in the sandbox.\n }\n }\n return existing;\n }\n } catch {\n // Not registered yet.\n }\n\n const materialize = async (): Promise<Workspace> => {\n // A terminal work item or a deleted session may have returned a\n // still-warm VM — with this repository already cloned — to the reuse\n // pool. Adopt it before provisioning a fresh sandbox. Pooled VMs carry\n // no credentials (tokens are injected per command, and the workdir is\n // scrubbed on release and again below), so any user's session for this\n // repository can claim one.\n let claimedPooledSandbox = false;\n if (!isLocalSandbox && !session.sandboxId) {\n const pooled = await storage.sandboxPool.claim({\n projectRepositoryId: session.projectRepositoryId,\n });\n if (pooled) {\n await storage.sessions.setSandbox({\n id: session.id,\n sandboxId: pooled.sandboxId,\n sandboxWorkdir: pooled.sandboxWorkdir,\n });\n session.sandboxId = pooled.sandboxId;\n session.sandboxWorkdir = pooled.sandboxWorkdir;\n workdir = pooled.sandboxWorkdir;\n claimedPooledSandbox = true;\n }\n }\n\n const access = await github.versionControl.getRepositoryAccess({\n orgId: session.orgId,\n repositoryId: repository.id,\n });\n const token = access.authorization?.token;\n if (!token) throw new Error('Repository access did not include a bearer token for the Factory session');\n\n // The `gh` CLI needs a PAT when the org configured one (installation\n // tokens 403 on integration-restricted endpoints); git clone/checkout\n // below keep using the minted installation token. Review-board sessions\n // (run-binding role `review`) authenticate `gh` as the reviewer account\n // when a reviewer token is configured; everything else — including\n // sessions with no resolvable run binding — uses the worker token.\n let patKind: GithubPatKind = 'default';\n if (workItems) {\n try {\n const address = getFactorySessionAddress(requestContext);\n const runBinding = address ? await workItems.findRunBindingBySession(address) : null;\n if (runBinding?.role === 'review' && runBinding.orgId === session.orgId) patKind = 'reviewer';\n } catch {\n // No resolvable binding — worker token.\n }\n }\n const ghCliToken = (await getGithubPat(() => github.integrationStorage, session.orgId, patKind)) ?? token;\n\n const ensureSandbox = () =>\n fleet.ensureSandbox(\n binding,\n { GH_TOKEN: ghCliToken },\n undefined,\n isLocalSandbox ? { workingDirectory: workdir } : {},\n );\n const runMaterialize = (target: Awaited<ReturnType<typeof ensureSandbox>>) =>\n materializeRepo({\n row: { id: session.id, sandboxWorkdir: workdir, materializedAt: session.materializedAt },\n repoInfo: { repoFullName: repoFullName, defaultBranch: repository.defaultBranch },\n sandbox: target,\n token,\n storage: storage.sessions,\n });\n const isGitMissing = (error: unknown) => error instanceof MaterializeError && error.code === 'git-missing';\n\n let sandbox = await ensureSandbox();\n // A claimed VM still has the previous session's branch checked out —\n // reset it to the default branch before materialize/checkout. When the\n // pooled VM was already reaped, `ensureSandbox` provisioned fresh and\n // the recycle is a no-op (no checkout on disk yet).\n if (claimedPooledSandbox) await recycleClaimedWorkdir(sandbox, workdir, repository.defaultBranch);\n try {\n await runMaterialize(sandbox);\n } catch (error) {\n if (!isGitMissing(error)) throw error;\n // A sandbox without git was booted from a bare base image (e.g. the\n // platform proxy falls back to a clean Debian base when its template\n // build fails). That VM can never materialize a repo, and its id is\n // already persisted on the binding — tear it down so re-opens stop\n // reattaching to the poisoned sandbox, then retry once on a fresh VM.\n await fleet.teardownSandbox(binding, sandbox);\n sandbox = await ensureSandbox();\n try {\n await runMaterialize(sandbox);\n } catch (retryError) {\n // Still bare — the provider's template is persistently broken.\n // Clear the binding so a later manual retry provisions fresh.\n if (isGitMissing(retryError)) await fleet.teardownSandbox(binding, sandbox);\n throw retryError;\n }\n }\n await checkoutSessionBranch(sandbox, workdir, {\n branch: session.branch,\n baseBranch: session.baseBranch || projectRepository.branch || repository.defaultBranch,\n token,\n repoFullName: repoFullName,\n });\n if (projectRepository.setupCommand) await runWorktreeSetup(sandbox, workdir, projectRepository.setupCommand);\n\n const injectGithubToken = (freshToken: string) => {\n if (!sandbox.setEnvironmentVariable) {\n throw new Error('The active sandbox provider does not support runtime GitHub token refresh.');\n }\n sandbox.setEnvironmentVariable('GH_TOKEN', freshToken);\n const registered = githubTokenInjectors.get(workspaceId);\n if (registered) registered.ghToken = freshToken;\n };\n githubTokenInjectors.set(workspaceId, { inject: injectGithubToken, patKind, ghToken: ghCliToken });\n registerGithubTokenInjector(requestContext, injectGithubToken);\n registerGithubPatKind(requestContext, patKind);\n\n const filesystem = new SandboxFilesystem({ sandbox, workdir });\n const projectSkillPaths = [path.join(configDir, 'skills'), '.claude/skills', '.agents/skills'];\n const skillPaths = [...(effectiveSkillExtension?.paths ?? []), ...projectSkillPaths];\n const workspace = new Workspace({\n id: workspaceId,\n name: 'Mastra Code Factory Session Workspace',\n filesystem,\n sandbox: sandbox as unknown as ConstructorParameters<typeof Workspace>[0]['sandbox'],\n tools: MASTRACODE_WORKSPACE_TOOLS,\n skills: skillPaths,\n skillSource: effectiveSkillExtension?.createSource(filesystem, projectSkillPaths) ?? filesystem,\n });\n // Register with the Mastra instance so sync HTTP handlers that resolve\n // the workspace via `mastra.getWorkspaceById(id)` (file tree, permissions\n // probe, MCP/tool routes) find it instead of throwing\n // `MASTRA_GET_WORKSPACE_BY_ID_NOT_FOUND`. `addWorkspace` is idempotent on\n // key collision, so the inflight coalescing and reuse paths above stay\n // race-safe. Registration happens synchronously with the return so a\n // concurrent lookup on another request cannot observe an unregistered\n // workspace.\n mastra?.addWorkspace(workspace, workspaceId, { source: 'mastra' });\n return workspace;\n };\n\n // Dedupe concurrent materializations of the same workspace: followers\n // await the leader's promise instead of provisioning a second sandbox,\n // then bind the shared token injector into their own request context.\n const inflight = inflightMaterializations.get(workspaceId);\n if (inflight) {\n const workspace = await inflight;\n const registered = githubTokenInjectors.get(workspaceId);\n if (registered) {\n registerGithubTokenInjector(requestContext, registered.inject);\n registerGithubPatKind(requestContext, registered.patKind);\n }\n return workspace;\n }\n const materialization = materialize();\n inflightMaterializations.set(workspaceId, materialization);\n try {\n return await materialization;\n } finally {\n inflightMaterializations.delete(workspaceId);\n }\n };\n}\n\nexport const getFactoryWorkspace = createWorkspaceFactory();\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;AAElC,SAAgB,yBAAyB,WAA2B;CAClE,OAAO,GAAG,0BAA0B,GAAG;AACzC;AAEA,MAAM,kBAAkB,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;AAC9D,MAAM,2BAA2B,KAAK,iBAAiB,gBAAgB;AACvE,MAAM,6BACJ;CAGE;CAGA,KAAK,iBAAi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killRoots","#isFactoryPath","#factoryPath"],"sources":["../src/workspace.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { SandboxFilesystem } from '@mastra/code-sdk/agents/sandbox-filesystem';\nimport { MASTRACODE_WORKSPACE_TOOLS } from '@mastra/code-sdk/agents/tool-availability';\nimport { getDynamicWorkspace } from '@mastra/code-sdk/agents/workspace';\nimport type { WorkspaceSkillExtension } from '@mastra/code-sdk/agents/workspace';\nimport { DEFAULT_CONFIG_DIR } from '@mastra/code-sdk/constants';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { LocalSandbox, LocalSkillSource, Workspace } from '@mastra/core/workspace';\nimport type { SkillSource, SkillSourceEntry, SkillSourceStat } from '@mastra/core/workspace';\nimport { getFactoryAuthUserId } from './auth.js';\nimport type { FactoryAuthUser } from './auth.js';\nimport type { MastraFactorySandboxConfig } from './factory.js';\nimport type { GithubIntegration } from './integrations/github/integration.js';\nimport { getGithubPat } from './integrations/github/pat.js';\nimport type { GithubPatKind } from './integrations/github/pat.js';\nimport {\n checkoutSessionBranch,\n MaterializeError,\n materializeRepo,\n recycleClaimedWorkdir,\n runWorktreeSetup,\n} from './integrations/github/sandbox.js';\nimport { registerGithubPatKind, registerGithubTokenInjector } from './integrations/github/token-refresh.js';\nimport { getFactorySessionAddress } from './rules/binding-context.js';\nimport type { SandboxBindingStore, SandboxFleet } from './sandbox/fleet.js';\nimport type { WorkItemsStorage } from './storage/domains/work-items/base.js';\n\nconst WORKSPACE_ID_PREFIX = 'mfw';\nconst SESSION_CHECKPOINT_PREFIX = 'mastracode-session';\n\nexport function checkpointNameForSession(sessionId: string): string {\n return `${SESSION_CHECKPOINT_PREFIX}-${sessionId}`;\n}\n\nconst bundleDirectory = dirname(fileURLToPath(import.meta.url));\nconst bundledFactorySkillsPath = join(bundleDirectory, 'factory-skills');\nconst FACTORY_SKILLS_SOURCE_PATH =\n [\n // Deploy bundle: the consumer copies `factory-skills/` next to the built\n // server module (e.g. via its public/ dir).\n bundledFactorySkillsPath,\n // Package layout: `dist/../factory-skills` (also `src/../factory-skills`\n // when running tests against sources).\n join(bundleDirectory, '..', 'factory-skills'),\n // Consumer repo running from its package root before a build.\n join(process.cwd(), 'src', 'mastra', 'public', 'factory-skills'),\n ].find(existsSync) ?? bundledFactorySkillsPath;\nconst FACTORY_SKILLS_MOUNT = path.resolve(path.parse(process.cwd()).root, '__mastracode_factory_skills__');\nconst FACTORY_SKILL_NAMES = new Set(['configure-factory-rules', 'factory-plan', 'factory-review', 'factory-triage']);\n\nclass FactorySkillSource implements SkillSource {\n readonly #factorySource = new LocalSkillSource({ basePath: FACTORY_SKILLS_SOURCE_PATH });\n readonly #fallbackSkillRoots: Set<string>;\n\n constructor(\n readonly fallback: SkillSource,\n fallbackSkillRoots: string[],\n ) {\n this.#fallbackSkillRoots = new Set(fallbackSkillRoots.map(skillPath => path.normalize(skillPath)));\n }\n\n #isFactoryPath(skillPath: string): boolean {\n const normalized = path.normalize(skillPath);\n return normalized === FACTORY_SKILLS_MOUNT || normalized.startsWith(`${FACTORY_SKILLS_MOUNT}${path.sep}`);\n }\n\n #factoryPath(skillPath: string): string {\n return path.relative(FACTORY_SKILLS_MOUNT, path.normalize(skillPath));\n }\n\n exists(skillPath: string): Promise<boolean> {\n return this.#isFactoryPath(skillPath)\n ? this.#factorySource.exists(this.#factoryPath(skillPath))\n : this.fallback.exists(skillPath);\n }\n\n stat(skillPath: string): Promise<SkillSourceStat> {\n return this.#isFactoryPath(skillPath)\n ? this.#factorySource.stat(this.#factoryPath(skillPath))\n : this.fallback.stat(skillPath);\n }\n\n readFile(skillPath: string): Promise<string | Buffer> {\n return this.#isFactoryPath(skillPath)\n ? this.#factorySource.readFile(this.#factoryPath(skillPath))\n : this.fallback.readFile(skillPath);\n }\n\n async readdir(skillPath: string): Promise<SkillSourceEntry[]> {\n if (this.#isFactoryPath(skillPath)) {\n return this.#factorySource.readdir(this.#factoryPath(skillPath));\n }\n const entries = await this.fallback.readdir(skillPath);\n if (this.#fallbackSkillRoots.has(path.normalize(skillPath))) {\n return entries.filter(entry => !FACTORY_SKILL_NAMES.has(entry.name));\n }\n return entries;\n }\n\n realpath(skillPath: string): Promise<string> {\n if (this.#isFactoryPath(skillPath)) return Promise.resolve(path.normalize(skillPath));\n return this.fallback.realpath ? this.fallback.realpath(skillPath) : Promise.resolve(skillPath);\n }\n}\n\nconst factorySkillExtension: WorkspaceSkillExtension = {\n id: 'web-factory',\n paths: [FACTORY_SKILLS_MOUNT],\n createSource: (fallback, fallbackSkillRoots) => new FactorySkillSource(fallback, fallbackSkillRoots),\n};\n\ntype DynamicWorkspaceContext = Parameters<typeof getDynamicWorkspace>[0];\n\nexport interface CreateWorkspaceFactoryOptions {\n /** Factory sandbox runtime config (template machine + workdir base). */\n sandbox?: MastraFactorySandboxConfig;\n /** GitHub integration used to resolve Factory sessions and mint repo tokens. */\n github?: GithubIntegration;\n /** Fleet the per-session sandboxes are provisioned/reattached through. */\n fleet?: SandboxFleet;\n /** Work-items storage used to resolve the session's run-binding role, so\n * review-board sessions get the reviewer PAT as `GH_TOKEN`. Optional —\n * without it every session uses the default (worker) PAT. */\n workItems?: Pick<WorkItemsStorage, 'findRunBindingBySession'>;\n}\n\nexport function createWorkspaceFactory(options: CreateWorkspaceFactoryOptions = {}) {\n const { sandbox: sandboxConfig, github, fleet, workItems } = options;\n const isLocalSandbox = sandboxConfig?.machine instanceof LocalSandbox;\n const githubTokenInjectors = new Map<\n string,\n { inject: (token: string) => void; patKind: GithubPatKind; ghToken: string }\n >();\n // Concurrent requests for the same session (thread list + activity polling +\n // chat) must not each provision a sandbox and clone the repository. The\n // first caller materializes; followers await the same promise.\n const inflightMaterializations = new Map<string, Promise<Workspace>>();\n\n return async ({ requestContext, mastra, skillExtension }: DynamicWorkspaceContext) => {\n const effectiveSkillExtension = skillExtension ?? factorySkillExtension;\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const session =\n ctx?.resourceId && github ? await github.sourceControlStorage.sessions.getBySessionId(ctx.resourceId) : null;\n\n if (!session) {\n if (sandboxConfig && !isLocalSandbox) {\n throw new Error('A Factory session ID is required to create a remote sandbox workspace');\n }\n return getDynamicWorkspace({ requestContext, mastra, skillExtension: effectiveSkillExtension });\n }\n\n const user = requestContext.get('user') as FactoryAuthUser | undefined;\n const userId = getFactoryAuthUserId(user);\n // No identity at all is a server-side caller that forgot to seed one\n // (webhook, cron), not someone reaching for another user's session.\n if (!user?.organizationId || !userId) {\n throw new Error(`Factory session ${session.sessionId} was resolved without a caller identity`);\n }\n if (user.organizationId !== session.orgId || userId !== session.userId) {\n throw new Error(`Factory session ${session.sessionId} is not available to the current user`);\n }\n if (!sandboxConfig || !github || !fleet) {\n throw new Error('GitHub and sandbox providers are required to create a Factory session workspace');\n }\n\n const storage = github.sourceControlStorage;\n const projectRepository = await storage.projectRepositories.get({\n orgId: session.orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) throw new Error(`Repository link ${session.projectRepositoryId} was not found`);\n const connection = await storage.connections.get({ orgId: session.orgId, id: projectRepository.connectionId });\n const repository = await storage.repositories.get({ orgId: session.orgId, id: projectRepository.repositoryId });\n if (!connection || !repository) throw new Error(`Repository link ${session.projectRepositoryId} is incomplete`);\n const installation = await storage.installations.get({ orgId: session.orgId, id: connection.installationId });\n if (!installation) throw new Error(`GitHub installation ${connection.installationId} was not found`);\n const repoFullName = repository.slug;\n\n let workdir = isLocalSandbox\n ? fleet.computeLocalSessionWorkdir(repoFullName, session.id)\n : (session.sandboxWorkdir ?? projectRepository.sandboxWorkdir);\n // The system prompt derives its working directory from `state.projectPath`\n // and falls back to the server's own process.cwd() when unset — which\n // points the agent at the host checkout (and lets it run `git checkout`\n // there instead of in its session workdir). Pin it to the session workdir.\n // During createSession this seeds the session's initial state (the\n // workspace resolves before the session is built); on later requests it\n // self-heals live state.\n if (ctx && workdir && ctx.getState()?.projectPath !== workdir) {\n await ctx.setState({ projectPath: workdir, projectName: repoFullName });\n }\n const binding: SandboxBindingStore = {\n // Read through to the session row so teardown after a fresh provision\n // sees the just-persisted id instead of a stale snapshot.\n get sandboxId() {\n return session.sandboxId;\n },\n checkpointName: checkpointNameForSession(session.id),\n setSandboxId: async id => {\n await storage.sessions.setSandbox({ id: session.id, sandboxId: id, sandboxWorkdir: workdir });\n session.sandboxId = id;\n session.sandboxWorkdir = workdir;\n },\n clear: async () => {\n await storage.sessions.setSandbox({ id: session.id, sandboxId: null, sandboxWorkdir: workdir });\n session.sandboxId = null;\n },\n };\n\n const extensionId = effectiveSkillExtension ? `-${effectiveSkillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectRepository.id}-${session.id}${extensionId}`;\n const configDir = sandboxConfig.workdir ?? DEFAULT_CONFIG_DIR;\n try {\n const existing = mastra?.getWorkspaceById(workspaceId) as Workspace | undefined;\n if (existing) {\n existing.setToolsConfig(MASTRACODE_WORKSPACE_TOOLS);\n const registered = githubTokenInjectors.get(workspaceId);\n if (registered) {\n registerGithubTokenInjector(requestContext, registered.inject);\n registerGithubPatKind(requestContext, registered.patKind);\n // A PAT saved in Settings after this sandbox was provisioned must\n // reach the running sandbox without a server restart — re-read it\n // on every reuse and push it into the live sandbox when it changed.\n // Best-effort: a failed read or inject keeps the installed token.\n try {\n const pat = await getGithubPat(() => github.integrationStorage, session.orgId, registered.patKind);\n if (pat && pat !== registered.ghToken) {\n registered.inject(pat);\n }\n } catch {\n // Keep the token already installed in the sandbox.\n }\n }\n return existing;\n }\n } catch {\n // Not registered yet.\n }\n\n const materialize = async (): Promise<Workspace> => {\n // A terminal work item or a deleted session may have returned a\n // still-warm VM — with this repository already cloned — to the reuse\n // pool. Adopt it before provisioning a fresh sandbox. Pooled VMs carry\n // no credentials (tokens are injected per command, and the workdir is\n // scrubbed on release and again below), so any user's session for this\n // repository can claim one.\n let claimedPooledSandbox = false;\n if (!isLocalSandbox && !session.sandboxId) {\n const pooled = await storage.sandboxPool.claim({\n projectRepositoryId: session.projectRepositoryId,\n });\n if (pooled) {\n await storage.sessions.setSandbox({\n id: session.id,\n sandboxId: pooled.sandboxId,\n sandboxWorkdir: pooled.sandboxWorkdir,\n });\n session.sandboxId = pooled.sandboxId;\n session.sandboxWorkdir = pooled.sandboxWorkdir;\n workdir = pooled.sandboxWorkdir;\n claimedPooledSandbox = true;\n }\n }\n\n const access = await github.versionControl.getRepositoryAccess({\n orgId: session.orgId,\n repositoryId: repository.id,\n });\n const token = access.authorization?.token;\n if (!token) throw new Error('Repository access did not include a bearer token for the Factory session');\n\n // The `gh` CLI needs a PAT when the org configured one (installation\n // tokens 403 on integration-restricted endpoints); git clone/checkout\n // below keep using the minted installation token. Review-board sessions\n // (run-binding role `review`) authenticate `gh` as the reviewer account\n // when a reviewer token is configured; everything else — including\n // sessions with no resolvable run binding — uses the worker token.\n let patKind: GithubPatKind = 'default';\n if (workItems) {\n try {\n const address = getFactorySessionAddress(requestContext);\n const runBinding = address ? await workItems.findRunBindingBySession(address) : null;\n if (runBinding?.role === 'review' && runBinding.orgId === session.orgId) patKind = 'reviewer';\n } catch {\n // No resolvable binding — worker token.\n }\n }\n const ghCliToken = (await getGithubPat(() => github.integrationStorage, session.orgId, patKind)) ?? token;\n\n const ensureSandbox = () =>\n fleet.ensureSandbox(\n binding,\n { GH_TOKEN: ghCliToken },\n undefined,\n isLocalSandbox ? { workingDirectory: workdir } : {},\n );\n const runMaterialize = (target: Awaited<ReturnType<typeof ensureSandbox>>) =>\n materializeRepo({\n row: { id: session.id, sandboxWorkdir: workdir, materializedAt: session.materializedAt },\n repoInfo: { repoFullName: repoFullName, defaultBranch: repository.defaultBranch },\n sandbox: target,\n token,\n storage: storage.sessions,\n });\n const isGitMissing = (error: unknown) => error instanceof MaterializeError && error.code === 'git-missing';\n\n let sandbox = await ensureSandbox();\n // A claimed VM still has the previous session's branch checked out —\n // reset it to the default branch before materialize/checkout. When the\n // pooled VM was already reaped, `ensureSandbox` provisioned fresh and\n // the recycle is a no-op (no checkout on disk yet).\n if (claimedPooledSandbox) await recycleClaimedWorkdir(sandbox, workdir, repository.defaultBranch);\n try {\n await runMaterialize(sandbox);\n } catch (error) {\n if (!isGitMissing(error)) throw error;\n // A sandbox without git was booted from a bare base image (e.g. the\n // platform proxy falls back to a clean Debian base when its template\n // build fails). That VM can never materialize a repo, and its id is\n // already persisted on the binding — tear it down so re-opens stop\n // reattaching to the poisoned sandbox, then retry once on a fresh VM.\n await fleet.teardownSandbox(binding, sandbox);\n sandbox = await ensureSandbox();\n try {\n await runMaterialize(sandbox);\n } catch (retryError) {\n // Still bare — the provider's template is persistently broken.\n // Clear the binding so a later manual retry provisions fresh.\n if (isGitMissing(retryError)) await fleet.teardownSandbox(binding, sandbox);\n throw retryError;\n }\n }\n await checkoutSessionBranch(sandbox, workdir, {\n branch: session.branch,\n baseBranch: session.baseBranch || projectRepository.branch || repository.defaultBranch,\n token,\n repoFullName: repoFullName,\n });\n if (projectRepository.setupCommand) await runWorktreeSetup(sandbox, workdir, projectRepository.setupCommand);\n\n const injectGithubToken = (freshToken: string) => {\n if (!sandbox.setEnvironmentVariable) {\n throw new Error('The active sandbox provider does not support runtime GitHub token refresh.');\n }\n sandbox.setEnvironmentVariable('GH_TOKEN', freshToken);\n const registered = githubTokenInjectors.get(workspaceId);\n if (registered) registered.ghToken = freshToken;\n };\n githubTokenInjectors.set(workspaceId, { inject: injectGithubToken, patKind, ghToken: ghCliToken });\n registerGithubTokenInjector(requestContext, injectGithubToken);\n registerGithubPatKind(requestContext, patKind);\n\n const filesystem = new SandboxFilesystem({ sandbox, workdir });\n const projectSkillPaths = [path.join(configDir, 'skills'), '.claude/skills', '.agents/skills'];\n const skillPaths = [...(effectiveSkillExtension?.paths ?? []), ...projectSkillPaths];\n const workspace = new Workspace({\n id: workspaceId,\n name: 'Mastra Code Factory Session Workspace',\n filesystem,\n sandbox: sandbox as unknown as ConstructorParameters<typeof Workspace>[0]['sandbox'],\n tools: MASTRACODE_WORKSPACE_TOOLS,\n skills: skillPaths,\n skillSource: effectiveSkillExtension?.createSource(filesystem, projectSkillPaths) ?? filesystem,\n });\n // Register with the Mastra instance so sync HTTP handlers that resolve\n // the workspace via `mastra.getWorkspaceById(id)` (file tree, permissions\n // probe, MCP/tool routes) find it instead of throwing\n // `MASTRA_GET_WORKSPACE_BY_ID_NOT_FOUND`. `addWorkspace` is idempotent on\n // key collision, so the inflight coalescing and reuse paths above stay\n // race-safe. Registration happens synchronously with the return so a\n // concurrent lookup on another request cannot observe an unregistered\n // workspace.\n mastra?.addWorkspace(workspace, workspaceId, { source: 'mastra' });\n return workspace;\n };\n\n // Dedupe concurrent materializations of the same workspace: followers\n // await the leader's promise instead of provisioning a second sandbox,\n // then bind the shared token injector into their own request context.\n const inflight = inflightMaterializations.get(workspaceId);\n if (inflight) {\n const workspace = await inflight;\n const registered = githubTokenInjectors.get(workspaceId);\n if (registered) {\n registerGithubTokenInjector(requestContext, registered.inject);\n registerGithubPatKind(requestContext, registered.patKind);\n }\n return workspace;\n }\n const materialization = materialize();\n inflightMaterializations.set(workspaceId, materialization);\n try {\n return await materialization;\n } finally {\n inflightMaterializations.delete(workspaceId);\n }\n };\n}\n\nexport const getFactoryWorkspace = createWorkspaceFactory();\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;AAElC,SAAgB,yBAAyB,WAA2B;CAClE,OAAO,GAAG,0BAA0B,GAAG;AACzC;AAEA,MAAM,kBAAkB,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;AAC9D,MAAM,2BAA2B,KAAK,iBAAiB,gBAAgB;AACvE,MAAM,6BACJ;CAGE;CAGA,KAAK,iBAAiB,MAAM,gBAAgB;CAE5C,KAAK,QAAQ,IAAI,GAAG,OAAO,UAAU,UAAU,gBAAgB;AACjE,CAAC,CAAC,KAAK,UAAU,KAAK;A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.5.0-alpha.1",
4
4
  "description": "Mastra Software Factory module: the server core behind the Mastra Software Factory — storage domains, integrations, and surfaces for agent-powered software delivery",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -47,13 +47,15 @@
47
47
  },
48
48
  "dependencies": {
49
49
  "@octokit/auth-app": "^8.0.0",
50
+ "chat": "^4.34.0",
50
51
  "@octokit/rest": "^22.0.1",
51
52
  "hono": "^4.12.8",
52
53
  "zod": "^4.3.6",
53
54
  "@mastra/auth-workos": "1.6.4",
54
55
  "@mastra/auth-studio": "1.3.3",
55
- "@mastra/code-sdk": "1.1.2",
56
- "@mastra/core": "1.56.0"
56
+ "@mastra/code-sdk": "1.1.3-alpha.1",
57
+ "@mastra/core": "1.57.0-alpha.1",
58
+ "@mastra/slack": "1.6.0"
57
59
  },
58
60
  "devDependencies": {
59
61
  "@types/node": "22.20.1",