@mastra/factory 0.8.0-alpha.8 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/CHANGELOG.md +660 -0
  2. package/dist/factory.d.ts.map +1 -1
  3. package/dist/factory.js +42 -4
  4. package/dist/factory.js.map +1 -1
  5. package/dist/integrations/base.d.ts +8 -0
  6. package/dist/integrations/base.d.ts.map +1 -1
  7. package/dist/integrations/github/app-identity.d.ts +43 -0
  8. package/dist/integrations/github/app-identity.d.ts.map +1 -0
  9. package/dist/integrations/github/app-identity.js +62 -0
  10. package/dist/integrations/github/app-identity.js.map +1 -0
  11. package/dist/integrations/github/integration.d.ts +9 -0
  12. package/dist/integrations/github/integration.d.ts.map +1 -1
  13. package/dist/integrations/github/integration.js +9 -1
  14. package/dist/integrations/github/integration.js.map +1 -1
  15. package/dist/integrations/github/reconcile-worker.d.ts +5 -0
  16. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  17. package/dist/integrations/github/reconcile-worker.js +7 -0
  18. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  19. package/dist/integrations/github/routes.d.ts.map +1 -1
  20. package/dist/integrations/github/routes.js +11 -6
  21. package/dist/integrations/github/routes.js.map +1 -1
  22. package/dist/integrations/github/rules.d.ts +8 -0
  23. package/dist/integrations/github/rules.d.ts.map +1 -1
  24. package/dist/integrations/github/rules.js +30 -8
  25. package/dist/integrations/github/rules.js.map +1 -1
  26. package/dist/integrations/github/sandbox.d.ts +39 -6
  27. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  28. package/dist/integrations/github/sandbox.js +48 -14
  29. package/dist/integrations/github/sandbox.js.map +1 -1
  30. package/dist/integrations/github/webhook.d.ts +39 -0
  31. package/dist/integrations/github/webhook.d.ts.map +1 -1
  32. package/dist/integrations/github/webhook.js +74 -13
  33. package/dist/integrations/github/webhook.js.map +1 -1
  34. package/dist/integrations/linear/integration.d.ts.map +1 -1
  35. package/dist/integrations/linear/integration.js +1 -0
  36. package/dist/integrations/linear/integration.js.map +1 -1
  37. package/dist/integrations/linear/routes.d.ts +10 -0
  38. package/dist/integrations/linear/routes.d.ts.map +1 -1
  39. package/dist/integrations/linear/routes.js +35 -1
  40. package/dist/integrations/linear/routes.js.map +1 -1
  41. package/dist/integrations/linear/rules.d.ts.map +1 -1
  42. package/dist/integrations/linear/rules.js +2 -1
  43. package/dist/integrations/linear/rules.js.map +1 -1
  44. package/dist/integrations/platform/github/event-worker.d.ts +11 -0
  45. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  46. package/dist/integrations/platform/github/event-worker.js +64 -16
  47. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  48. package/dist/integrations/platform/github/integration.d.ts +12 -0
  49. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  50. package/dist/integrations/platform/github/integration.js +47 -4
  51. package/dist/integrations/platform/github/integration.js.map +1 -1
  52. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  53. package/dist/integrations/platform/linear/integration.js +1 -0
  54. package/dist/integrations/platform/linear/integration.js.map +1 -1
  55. package/dist/integrations/slack/slack.d.ts.map +1 -1
  56. package/dist/integrations/slack/slack.js +2 -1
  57. package/dist/integrations/slack/slack.js.map +1 -1
  58. package/dist/routes/config.d.ts +12 -6
  59. package/dist/routes/config.d.ts.map +1 -1
  60. package/dist/routes/config.js +97 -56
  61. package/dist/routes/config.js.map +1 -1
  62. package/dist/routes/fs.d.ts.map +1 -1
  63. package/dist/routes/fs.js +2 -0
  64. package/dist/routes/fs.js.map +1 -1
  65. package/dist/routes/intake.d.ts +15 -0
  66. package/dist/routes/intake.d.ts.map +1 -1
  67. package/dist/routes/intake.js +65 -2
  68. package/dist/routes/intake.js.map +1 -1
  69. package/dist/routes/knowledge.d.ts +152 -0
  70. package/dist/routes/knowledge.d.ts.map +1 -0
  71. package/dist/routes/knowledge.js +442 -0
  72. package/dist/routes/knowledge.js.map +1 -0
  73. package/dist/routes/projects.d.ts +9 -1
  74. package/dist/routes/projects.d.ts.map +1 -1
  75. package/dist/routes/projects.js +8 -0
  76. package/dist/routes/projects.js.map +1 -1
  77. package/dist/routes/surface.d.ts +6 -0
  78. package/dist/routes/surface.d.ts.map +1 -1
  79. package/dist/routes/surface.js +10 -0
  80. package/dist/routes/surface.js.map +1 -1
  81. package/dist/routes/work-items.d.ts.map +1 -1
  82. package/dist/routes/work-items.js +3 -1
  83. package/dist/routes/work-items.js.map +1 -1
  84. package/dist/rules/binding-context.d.ts.map +1 -1
  85. package/dist/rules/binding-context.js +4 -1
  86. package/dist/rules/binding-context.js.map +1 -1
  87. package/dist/rules/defaults.d.ts.map +1 -1
  88. package/dist/rules/defaults.js +87 -4
  89. package/dist/rules/defaults.js.map +1 -1
  90. package/dist/rules/dispatcher.d.ts +6 -0
  91. package/dist/rules/dispatcher.d.ts.map +1 -1
  92. package/dist/rules/dispatcher.js +118 -16
  93. package/dist/rules/dispatcher.js.map +1 -1
  94. package/dist/rules/processor.d.ts.map +1 -1
  95. package/dist/rules/processor.js +20 -7
  96. package/dist/rules/processor.js.map +1 -1
  97. package/dist/rules/resolve.d.ts +1 -0
  98. package/dist/rules/resolve.d.ts.map +1 -1
  99. package/dist/rules/resolve.js +3 -2
  100. package/dist/rules/resolve.js.map +1 -1
  101. package/dist/rules/start-coordinator.d.ts +2 -0
  102. package/dist/rules/start-coordinator.d.ts.map +1 -1
  103. package/dist/rules/start-coordinator.js +3 -1
  104. package/dist/rules/start-coordinator.js.map +1 -1
  105. package/dist/rules/terminal-cleanup.d.ts +23 -0
  106. package/dist/rules/terminal-cleanup.d.ts.map +1 -0
  107. package/dist/rules/terminal-cleanup.js +43 -0
  108. package/dist/rules/terminal-cleanup.js.map +1 -0
  109. package/dist/rules/tools.d.ts.map +1 -1
  110. package/dist/rules/tools.js +24 -2
  111. package/dist/rules/tools.js.map +1 -1
  112. package/dist/rules/transition-service.d.ts +3 -0
  113. package/dist/rules/transition-service.d.ts.map +1 -1
  114. package/dist/rules/transition-service.js +10 -6
  115. package/dist/rules/transition-service.js.map +1 -1
  116. package/dist/rules/types.d.ts +32 -3
  117. package/dist/rules/types.d.ts.map +1 -1
  118. package/dist/rules/types.js +2 -0
  119. package/dist/rules/types.js.map +1 -1
  120. package/dist/rules/validation.d.ts.map +1 -1
  121. package/dist/rules/validation.js +8 -3
  122. package/dist/rules/validation.js.map +1 -1
  123. package/dist/sandbox/base-checkpoint-triggers.d.ts +77 -0
  124. package/dist/sandbox/base-checkpoint-triggers.d.ts.map +1 -0
  125. package/dist/sandbox/base-checkpoint-triggers.js +137 -0
  126. package/dist/sandbox/base-checkpoint-triggers.js.map +1 -0
  127. package/dist/sandbox/base-checkpoint.d.ts +59 -0
  128. package/dist/sandbox/base-checkpoint.d.ts.map +1 -0
  129. package/dist/sandbox/base-checkpoint.js +145 -0
  130. package/dist/sandbox/base-checkpoint.js.map +1 -0
  131. package/dist/sandbox/fleet.d.ts +32 -0
  132. package/dist/sandbox/fleet.d.ts.map +1 -1
  133. package/dist/sandbox/fleet.js +39 -10
  134. package/dist/sandbox/fleet.js.map +1 -1
  135. package/dist/session/checkpoint-capture.d.ts +3 -2
  136. package/dist/session/checkpoint-capture.d.ts.map +1 -1
  137. package/dist/session/checkpoint-capture.js +3 -3
  138. package/dist/session/checkpoint-capture.js.map +1 -1
  139. package/dist/session/factory-session.d.ts.map +1 -1
  140. package/dist/session/factory-session.js +2 -1
  141. package/dist/session/factory-session.js.map +1 -1
  142. package/dist/session/filesystem-capture.d.ts +7 -0
  143. package/dist/session/filesystem-capture.d.ts.map +1 -1
  144. package/dist/session/filesystem-capture.js +41 -4
  145. package/dist/session/filesystem-capture.js.map +1 -1
  146. package/dist/session/model-pack-hydration.d.ts +55 -0
  147. package/dist/session/model-pack-hydration.d.ts.map +1 -0
  148. package/dist/session/model-pack-hydration.js +56 -0
  149. package/dist/session/model-pack-hydration.js.map +1 -0
  150. package/dist/skills/service.d.ts +9 -0
  151. package/dist/skills/service.d.ts.map +1 -1
  152. package/dist/skills/service.js +10 -1
  153. package/dist/skills/service.js.map +1 -1
  154. package/dist/storage/domains/intake/base.d.ts +36 -0
  155. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  156. package/dist/storage/domains/intake/base.js +91 -2
  157. package/dist/storage/domains/intake/base.js.map +1 -1
  158. package/dist/storage/domains/model-packs/base.d.ts +26 -0
  159. package/dist/storage/domains/model-packs/base.d.ts.map +1 -1
  160. package/dist/storage/domains/model-packs/base.js +102 -13
  161. package/dist/storage/domains/model-packs/base.js.map +1 -1
  162. package/dist/storage/domains/source-control/base.d.ts +47 -1
  163. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  164. package/dist/storage/domains/source-control/base.js +78 -19
  165. package/dist/storage/domains/source-control/base.js.map +1 -1
  166. package/dist/storage/domains/source-control/inmemory.d.ts +11 -3
  167. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  168. package/dist/storage/domains/source-control/inmemory.js +10 -1
  169. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  170. package/dist/storage/domains/work-items/base.d.ts +67 -1
  171. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  172. package/dist/storage/domains/work-items/base.js +183 -12
  173. package/dist/storage/domains/work-items/base.js.map +1 -1
  174. package/dist/workspace.d.ts +31 -2
  175. package/dist/workspace.d.ts.map +1 -1
  176. package/dist/workspace.js +225 -54
  177. package/dist/workspace.js.map +1 -1
  178. package/factory-skills/factory-plan/SKILL.md +1 -1
  179. package/factory-skills/factory-rereview/SKILL.md +3 -3
  180. package/factory-skills/factory-review/SKILL.md +3 -3
  181. package/factory-skills/factory-triage/SKILL.md +2 -0
  182. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"factory-session.js","names":[],"sources":["../../src/session/factory-session.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\n\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { applyStoredMemorySettings } from './memory-settings-hydration.js';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\n/**\n * Read the factory project's default model. Best-effort: a missing project or an\n * uninitialized storage domain means \"no default\", never a failed run.\n */\nexport async function resolveFactoryDefaultModelId(\n projects: FactoryProjectsStorage | undefined,\n factoryProjectId: string | undefined,\n): Promise<string | undefined> {\n if (!projects || !factoryProjectId) return undefined;\n try {\n const project = await projects.getById({ id: factoryProjectId });\n return project?.defaultModelId ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface EnsureFactorySourceSessionArgs {\n /**\n * Storage handle of the integration that owns source control. Nothing here is\n * provider-specific: the connection is matched by the handle's own\n * `integrationId`, so GitHub, Slack-on-behalf-of-GitHub, or any future owner\n * all resolve through the same traversal.\n */\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n branch: string;\n /** Pick a specific linked repository by slug. Defaults to the first linked repository. */\n repositorySlug?: string;\n}\n\nexport interface EnsuredFactorySourceSession {\n sessionId: string;\n userId: string;\n projectRepositoryId: string;\n branch: string;\n baseBranch: string;\n}\n\nexport interface ResolvedFactorySourceRepository {\n projectRepositoryId: string;\n /** The repository's pinned branch, else its default branch. */\n baseBranch: string;\n /** Who connected the repository. The attribution for runs with no interactive user. */\n connectedByUserId: string;\n}\n\n/**\n * Outcome of {@link resolveFactorySourceRepository}. A miss carries which step\n * failed: callers differ on whether that is an error (an autonomous run cannot\n * proceed) or a routine fallback (a chat integration drops to a chat-only\n * session), and the two steps fail for different reasons worth reporting apart.\n */\nexport type FactorySourceRepositoryResult =\n | ({ found: true } & ResolvedFactorySourceRepository)\n | { found: false; reason: 'connection' | 'repository' };\n\n/**\n * Resolve which repository a factory project's source-control runs act on: the\n * owner's connection on the project, then one of its linked repositories.\n *\n * The owner is whichever integration owns source control, matched by the\n * handle's own `integrationId` — nothing here is provider-specific.\n */\nexport async function resolveFactorySourceRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n /** Pick a specific linked repository by slug. Defaults to the first linked repository. */\n repositorySlug?: string;\n}): Promise<FactorySourceRepositoryResult> {\n const { sourceControl, orgId, factoryProjectId, repositorySlug } = args;\n\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n const candidates = connections.filter(candidate => candidate.integrationId === sourceControl.integrationId);\n if (candidates.length === 0) return { found: false, reason: 'connection' };\n\n // A project can carry stale connections: a provider-app reinstall leaves the\n // old connection pointing at an installation that no longer exists, and that\n // row can sit ahead of the healthy one. Try every candidate and skip the ones\n // that no longer resolve rather than failing on the first.\n for (const connection of candidates) {\n let resolved;\n try {\n const projectRepositories = await sourceControl.projectRepositories.list({ orgId, connectionId: connection.id });\n const resolvedRepositories = await Promise.all(\n projectRepositories.map(async projectRepository => ({\n projectRepository,\n repository: await sourceControl.repositories.get({ orgId, id: projectRepository.repositoryId }),\n })),\n );\n resolved = resolvedRepositories.find(\n candidate => candidate.repository && (!repositorySlug || candidate.repository.slug === repositorySlug),\n );\n } catch {\n // The connection no longer resolves (e.g. its installation was deleted).\n continue;\n }\n if (!resolved?.repository) continue;\n\n return {\n found: true,\n projectRepositoryId: resolved.projectRepository.id,\n baseBranch: resolved.projectRepository.branch ?? resolved.repository.defaultBranch,\n connectedByUserId: connection.createdByUserId,\n };\n }\n\n return { found: false, reason: 'repository' };\n}\n\n/**\n * Walk a Factory user-session id back to the project it belongs to.\n *\n * Repo-backed channel threads are keyed by their Factory session id, which is\n * the only handle a session-start hook gets. This turns that id back into the\n * project whose configuration the session should adopt. Durable by\n * construction — it reads the same rows the session was created from, so it\n * survives restarts without any in-memory mapping.\n */\nexport async function resolveFactoryProjectForSession(args: {\n sourceControl: SourceControlStorageHandle;\n sessionId: string;\n}): Promise<{ factoryProjectId: string; orgId: string; userId: string } | null> {\n const { sourceControl, sessionId } = args;\n\n const session = await sourceControl.sessions.getBySessionId(sessionId);\n if (!session) return null;\n const projectRepository = await sourceControl.projectRepositories.get({\n orgId: session.orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) return null;\n const connection = await sourceControl.connections.get({ orgId: session.orgId, id: projectRepository.connectionId });\n if (!connection) return null;\n\n return { factoryProjectId: connection.factoryProjectId, orgId: session.orgId, userId: session.userId };\n}\n\n/**\n * Create the source-control session a repo-backed factory run needs.\n *\n * `FactoryStartCoordinator.prepare` requires this record to already exist —\n * `resolveSourceSession` throws `Factory session not found` otherwise — so every\n * autonomous entry point has to produce one before it can start a run. This is\n * that step, in one place: the owner's connection on the factory project, one of\n * its linked repositories, and a session on the requested branch with the\n * repository's pinned or default branch as the base.\n *\n * The run is attributed to whoever connected the repository\n * (`connection.createdByUserId`), because an autonomous run has no interactive\n * user of its own.\n */\nexport async function ensureFactorySourceSession(\n args: EnsureFactorySourceSessionArgs,\n): Promise<EnsuredFactorySourceSession> {\n const { sourceControl, orgId, factoryProjectId, branch, repositorySlug } = args;\n\n const resolved = await resolveFactorySourceRepository({ sourceControl, orgId, factoryProjectId, repositorySlug });\n if (!resolved.found) {\n throw new Error(\n resolved.reason === 'connection'\n ? 'Factory source-control connection not found.'\n : 'Factory source-control repository not found.',\n );\n }\n\n const userId = resolved.connectedByUserId;\n const session = await sourceControl.sessions.create({\n sessionId: randomUUID(),\n projectRepositoryId: resolved.projectRepositoryId,\n orgId,\n userId,\n branch,\n baseBranch: resolved.baseBranch,\n });\n return {\n sessionId: session.sessionId,\n userId,\n projectRepositoryId: resolved.projectRepositoryId,\n branch: session.branch,\n baseBranch: resolved.baseBranch,\n };\n}\n\nexport interface HydrateFactorySessionArgs {\n orgId: string;\n userId: string;\n /** The factory project's default model. Without it the session keeps the SDK's built-in mode default. */\n defaultModelId?: string;\n /** Omitted when the storage domain is unavailable, in which case the session runs on memory defaults. */\n memorySettings?: MemorySettingsStorage;\n}\n\n/**\n * Apply a factory project's configuration to a freshly created session:\n * observational-memory settings, then the project's default model.\n *\n * Both steps are best-effort. A retired model id or an unreachable settings row\n * must not sink a run that is otherwise ready — the session simply keeps the\n * default it was created with, and the reason is logged.\n */\nexport async function hydrateFactorySession(session: FactorySession, args: HydrateFactorySessionArgs): Promise<void> {\n if (args.memorySettings) {\n try {\n const record = await args.memorySettings.get({ orgId: args.orgId, userId: args.userId });\n await applyStoredMemorySettings(session, record);\n } catch (error) {\n console.warn('[Factory Start] Failed to apply observational-memory settings', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (args.defaultModelId) {\n try {\n await session.model.switch({ modelId: args.defaultModelId });\n } catch (error) {\n console.warn('[Factory Start] Failed to apply factory default model', {\n modelId: args.defaultModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"],"mappings":";;;;;;;AAgBA,eAAsB,6BACpB,UACA,kBAC6B;CAC7B,IAAI,CAAC,YAAY,CAAC,kBAAkB,OAAO,KAAA;CAC3C,IAAI;EAEF,QAAO,MADe,SAAS,QAAQ,EAAE,IAAI,iBAAiB,CAAC,EAAA,EAC/C,kBAAkB,KAAA;CACpC,QAAQ;EACN;CACF;AACF;;;;;;;;AAkDA,eAAsB,+BAA+B,MAMV;CACzC,MAAM,EAAE,eAAe,OAAO,kBAAkB,mBAAmB;CAGnE,MAAM,cAAa,MADO,cAAc,YAAY,KAAK;EAAE;EAAO;CAAiB,CAAC,EAAA,CACrD,QAAO,cAAa,UAAU,kBAAkB,cAAc,aAAa;CAC1G,IAAI,WAAW,WAAW,GAAG,OAAO;EAAE,OAAO;EAAO,QAAQ;CAAa;CAMzE,KAAK,MAAM,cAAc,YAAY;EACnC,IAAI;EACJ,IAAI;GACF,MAAM,sBAAsB,MAAM,cAAc,oBAAoB,KAAK;IAAE;IAAO,cAAc,WAAW;GAAG,CAAC;GAO/G,YAAW,MANwB,QAAQ,IACzC,oBAAoB,IAAI,OAAM,uBAAsB;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B,SAAS;EAC9B;EACA;EACA;EACA,YAAY,SAAS;CACvB,CAAC;CACD,OAAO;EACL,WAAW,QAAQ;EACnB;EACA,qBAAqB,SAAS;EAC9B,QAAQ,QAAQ;EAChB,YAAY,SAAS;CACvB;AACF;;;;;;;;;AAmBA,eAAsB,sBAAsB,SAAyB,MAAgD;CACnH,IAAI,KAAK,gBACP,IAAI;EAEF,MAAM,0BAA0B,SAAS,MADpB,KAAK,eAAe,IAAI;GAAE,OAAO,KAAK;GAAO,QAAQ,KAAK;EAAO,CAAC,CACxC;CACjD,SAAS,OAAO;EACd,QAAQ,KAAK,iEAAiE,EAC5E,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAC9D,CAAC;CACH;CAEF,IAAI,KAAK,gBACP,IAAI;EACF,MAAM,QAAQ,MAAM,OAAO,EAAE,SAAS,KAAK,eAAe,CAAC;CAC7D,SAAS,OAAO;EACd,QAAQ,KAAK,yDAAyD;GACpE,SAAS,KAAK;GACd,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;CACH;AAEJ"}
1
+ {"version":3,"file":"factory-session.js","names":[],"sources":["../../src/session/factory-session.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\n\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { applyStoredMemorySettings } from './memory-settings-hydration.js';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\n/**\n * Read the factory project's default model. Best-effort: a missing project or an\n * uninitialized storage domain means \"no default\", never a failed run.\n */\nexport async function resolveFactoryDefaultModelId(\n projects: FactoryProjectsStorage | undefined,\n factoryProjectId: string | undefined,\n): Promise<string | undefined> {\n if (!projects || !factoryProjectId) return undefined;\n try {\n const project = await projects.getById({ id: factoryProjectId });\n return project?.defaultModelId ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface EnsureFactorySourceSessionArgs {\n /**\n * Storage handle of the integration that owns source control. Nothing here is\n * provider-specific: the connection is matched by the handle's own\n * `integrationId`, so GitHub, Slack-on-behalf-of-GitHub, or any future owner\n * all resolve through the same traversal.\n */\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n branch: string;\n /** Pick a specific linked repository by slug. Defaults to the first linked repository. */\n repositorySlug?: string;\n}\n\nexport interface EnsuredFactorySourceSession {\n sessionId: string;\n userId: string;\n projectRepositoryId: string;\n branch: string;\n baseBranch: string;\n}\n\nexport interface ResolvedFactorySourceRepository {\n projectRepositoryId: string;\n /** The repository's pinned branch, else its default branch. */\n baseBranch: string;\n /** Who connected the repository. The attribution for runs with no interactive user. */\n connectedByUserId: string;\n}\n\n/**\n * Outcome of {@link resolveFactorySourceRepository}. A miss carries which step\n * failed: callers differ on whether that is an error (an autonomous run cannot\n * proceed) or a routine fallback (a chat integration drops to a chat-only\n * session), and the two steps fail for different reasons worth reporting apart.\n */\nexport type FactorySourceRepositoryResult =\n | ({ found: true } & ResolvedFactorySourceRepository)\n | { found: false; reason: 'connection' | 'repository' };\n\n/**\n * Resolve which repository a factory project's source-control runs act on: the\n * owner's connection on the project, then one of its linked repositories.\n *\n * The owner is whichever integration owns source control, matched by the\n * handle's own `integrationId` — nothing here is provider-specific.\n */\nexport async function resolveFactorySourceRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n /** Pick a specific linked repository by slug. Defaults to the first linked repository. */\n repositorySlug?: string;\n}): Promise<FactorySourceRepositoryResult> {\n const { sourceControl, orgId, factoryProjectId, repositorySlug } = args;\n\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n const candidates = connections.filter(candidate => candidate.integrationId === sourceControl.integrationId);\n if (candidates.length === 0) return { found: false, reason: 'connection' };\n\n // A project can carry stale connections: a provider-app reinstall leaves the\n // old connection pointing at an installation that no longer exists, and that\n // row can sit ahead of the healthy one. Try every candidate and skip the ones\n // that no longer resolve rather than failing on the first.\n for (const connection of candidates) {\n let resolved;\n try {\n const projectRepositories = await sourceControl.projectRepositories.list({ orgId, connectionId: connection.id });\n const resolvedRepositories = await Promise.all(\n projectRepositories.map(async projectRepository => ({\n projectRepository,\n repository: await sourceControl.repositories.get({ orgId, id: projectRepository.repositoryId }),\n })),\n );\n resolved = resolvedRepositories.find(\n candidate => candidate.repository && (!repositorySlug || candidate.repository.slug === repositorySlug),\n );\n } catch {\n // The connection no longer resolves (e.g. its installation was deleted).\n continue;\n }\n if (!resolved?.repository) continue;\n\n return {\n found: true,\n projectRepositoryId: resolved.projectRepository.id,\n baseBranch: resolved.projectRepository.branch ?? resolved.repository.defaultBranch,\n connectedByUserId: connection.createdByUserId,\n };\n }\n\n return { found: false, reason: 'repository' };\n}\n\n/**\n * Walk a Factory user-session id back to the project it belongs to.\n *\n * Repo-backed channel threads are keyed by their Factory session id, which is\n * the only handle a session-start hook gets. This turns that id back into the\n * project whose configuration the session should adopt. Durable by\n * construction — it reads the same rows the session was created from, so it\n * survives restarts without any in-memory mapping.\n */\nexport async function resolveFactoryProjectForSession(args: {\n sourceControl: SourceControlStorageHandle;\n sessionId: string;\n}): Promise<{ factoryProjectId: string; orgId: string; userId: string } | null> {\n const { sourceControl, sessionId } = args;\n\n const session = await sourceControl.sessions.getBySessionId(sessionId);\n if (!session) return null;\n const projectRepository = await sourceControl.projectRepositories.get({\n orgId: session.orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) return null;\n const connection = await sourceControl.connections.get({ orgId: session.orgId, id: projectRepository.connectionId });\n if (!connection) return null;\n\n return { factoryProjectId: connection.factoryProjectId, orgId: session.orgId, userId: session.userId };\n}\n\n/**\n * Create the source-control session a repo-backed factory run needs.\n *\n * `FactoryStartCoordinator.prepare` requires this record to already exist —\n * `resolveSourceSession` throws `Factory session not found` otherwise — so every\n * autonomous entry point has to produce one before it can start a run. This is\n * that step, in one place: the owner's connection on the factory project, one of\n * its linked repositories, and a session on the requested branch with the\n * repository's pinned or default branch as the base.\n *\n * The run is attributed to whoever connected the repository\n * (`connection.createdByUserId`), because an autonomous run has no interactive\n * user of its own.\n */\nexport async function ensureFactorySourceSession(\n args: EnsureFactorySourceSessionArgs,\n): Promise<EnsuredFactorySourceSession> {\n const { sourceControl, orgId, factoryProjectId, branch, repositorySlug } = args;\n\n const resolved = await resolveFactorySourceRepository({ sourceControl, orgId, factoryProjectId, repositorySlug });\n if (!resolved.found) {\n throw new Error(\n resolved.reason === 'connection'\n ? 'Factory source-control connection not found.'\n : 'Factory source-control repository not found.',\n );\n }\n\n const userId = resolved.connectedByUserId;\n const session = await sourceControl.sessions.create({\n sessionId: randomUUID(),\n projectRepositoryId: resolved.projectRepositoryId,\n orgId,\n userId,\n branch,\n baseBranch: resolved.baseBranch,\n visibility: 'org',\n });\n return {\n sessionId: session.sessionId,\n userId,\n projectRepositoryId: resolved.projectRepositoryId,\n branch: session.branch,\n baseBranch: resolved.baseBranch,\n };\n}\n\nexport interface HydrateFactorySessionArgs {\n orgId: string;\n userId: string;\n /** The factory project's default model. Without it the session keeps the SDK's built-in mode default. */\n defaultModelId?: string;\n /** Omitted when the storage domain is unavailable, in which case the session runs on memory defaults. */\n memorySettings?: MemorySettingsStorage;\n}\n\n/**\n * Apply a factory project's configuration to a freshly created session:\n * observational-memory settings, then the project's default model.\n *\n * Both steps are best-effort. A retired model id or an unreachable settings row\n * must not sink a run that is otherwise ready — the session simply keeps the\n * default it was created with, and the reason is logged.\n */\nexport async function hydrateFactorySession(session: FactorySession, args: HydrateFactorySessionArgs): Promise<void> {\n if (args.memorySettings) {\n try {\n const record = await args.memorySettings.get({ orgId: args.orgId, userId: args.userId });\n await applyStoredMemorySettings(session, record);\n } catch (error) {\n console.warn('[Factory Start] Failed to apply observational-memory settings', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (args.defaultModelId) {\n try {\n await session.model.switch({ modelId: args.defaultModelId });\n } catch (error) {\n console.warn('[Factory Start] Failed to apply factory default model', {\n modelId: args.defaultModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"],"mappings":";;;;;;;AAgBA,eAAsB,6BACpB,UACA,kBAC6B;CAC7B,IAAI,CAAC,YAAY,CAAC,kBAAkB,OAAO,KAAA;CAC3C,IAAI;EAEF,QAAO,MADe,SAAS,QAAQ,EAAE,IAAI,iBAAiB,CAAC,EAAA,EAC/C,kBAAkB,KAAA;CACpC,QAAQ;EACN;CACF;AACF;;;;;;;;AAkDA,eAAsB,+BAA+B,MAMV;CACzC,MAAM,EAAE,eAAe,OAAO,kBAAkB,mBAAmB;CAGnE,MAAM,cAAa,MADO,cAAc,YAAY,KAAK;EAAE;EAAO;CAAiB,CAAC,EAAA,CACrD,QAAO,cAAa,UAAU,kBAAkB,cAAc,aAAa;CAC1G,IAAI,WAAW,WAAW,GAAG,OAAO;EAAE,OAAO;EAAO,QAAQ;CAAa;CAMzE,KAAK,MAAM,cAAc,YAAY;EACnC,IAAI;EACJ,IAAI;GACF,MAAM,sBAAsB,MAAM,cAAc,oBAAoB,KAAK;IAAE;IAAO,cAAc,WAAW;GAAG,CAAC;GAO/G,YAAW,MANwB,QAAQ,IACzC,oBAAoB,IAAI,OAAM,uBAAsB;IAClD;IACA,YAAY,MAAM,cAAc,aAAa,IAAI;KAAE;KAAO,IAAI,kBAAkB;IAAa,CAAC;GAChG,EAAE,CACJ,EAAA,CACgC,MAC9B,cAAa,UAAU,eAAe,CAAC,kBAAkB,UAAU,WAAW,SAAS,eACzF;EACF,QAAQ;GAEN;EACF;EACA,IAAI,CAAC,UAAU,YAAY;EAE3B,OAAO;GACL,OAAO;GACP,qBAAqB,SAAS,kBAAkB;GAChD,YAAY,SAAS,kBAAkB,UAAU,SAAS,WAAW;GACrE,mBAAmB,WAAW;EAChC;CACF;CAEA,OAAO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,OAAO;EACd,QAAQ,KAAK,iEAAiE,EAC5E,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAC9D,CAAC;CACH;CAEF,IAAI,KAAK,gBACP,IAAI;EACF,MAAM,QAAQ,MAAM,OAAO,EAAE,SAAS,KAAK,eAAe,CAAC;CAC7D,SAAS,OAAO;EACd,QAAQ,KAAK,yDAAyD;GACpE,SAAS,KAAK;GACd,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;CACH;AAEJ"}
@@ -22,5 +22,12 @@ export interface FilesystemCaptureDependencies {
22
22
  }
23
23
  export declare function parseFilesystemCaptureFiles(output: string): FilesystemFile[];
24
24
  export declare function captureSessionFilesystem(session: FilesystemCaptureSession, { filesystem, sourceControl }: FilesystemCaptureDependencies): Promise<void>;
25
+ /**
26
+ * Resolve once the session's in-flight filesystem capture (if any) has
27
+ * persisted, or after `timeoutMs` so a reader that arrives mid-capture is
28
+ * never blocked by the execs' worst-case 30s timeouts. Never rejects: the
29
+ * capture body is fully try/catch contained.
30
+ */
31
+ export declare function waitForPendingFilesystemCapture(resourceId: string, timeoutMs?: number): Promise<void>;
25
32
  export declare function observeSessionFilesystem(session: FilesystemCaptureSession, dependencies: FilesystemCaptureDependencies): () => void;
26
33
  //# sourceMappingURL=filesystem-capture.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"filesystem-capture.d.ts","sourceRoot":"","sources":["../../src/session/filesystem-capture.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE/D,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAC/F,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAK5F,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,QAA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E,aAAa,IAAI,MAAM,CAAA;KAAE,CAAC;IAC/C,QAAQ,CAAC,MAAM,EAAE;QAAE,SAAS,IAAI,MAAM,CAAA;KAAE,CAAC;IACzC,YAAY,IAAI;QAAE,OAAO,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,CAAA;KAAE,GAAG,SAAS,CAAC;IACnF,gBAAgB,CAAC,QAAQ,EAAE,6BAA6B,GAAG,MAAM,IAAI,CAAC;CACvE;AAED,MAAM,WAAW,6BAA6B;IAC5C,UAAU,EAAE,IAAI,CAAC,iBAAiB,EAAE,cAAc,CAAC,CAAC;IACpD,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,gBAAgB,CAAC,CAAC;KAC1E,CAAC;CACH;AAED,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,MAAM,GAAG,cAAc,EAAE,CAmB5E;AAED,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,wBAAwB,EACjC,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE,6BAA6B,GAC3D,OAAO,CAAC,IAAI,CAAC,CA2Cf;AAYD;;;;;GAKG;AACH,wBAAsB,+BAA+B,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAc3G;AAED,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,wBAAwB,EACjC,YAAY,EAAE,6BAA6B,GAC1C,MAAM,IAAI,CAkCZ"}
@@ -62,14 +62,51 @@ async function captureSessionFilesystem(session, { filesystem, sourceControl })
62
62
  console.warn("[Factory filesystem capture] Unable to persist files.", error);
63
63
  }
64
64
  }
65
+ /**
66
+ * In-flight capture chains keyed by session resource id. Serves two purposes:
67
+ * readers of the persisted file listing (the /web/workspace routes) await the
68
+ * capture for the turn that just ended instead of racing it, and captures for
69
+ * the same resource stay sequential (last write wins) even when multiple
70
+ * scoped sessions observe the same resource id. In-process only: the factory
71
+ * server that runs the session controller also serves those routes.
72
+ */
73
+ const pendingCaptures = /* @__PURE__ */ new Map();
74
+ /**
75
+ * Resolve once the session's in-flight filesystem capture (if any) has
76
+ * persisted, or after `timeoutMs` so a reader that arrives mid-capture is
77
+ * never blocked by the execs' worst-case 30s timeouts. Never rejects: the
78
+ * capture body is fully try/catch contained.
79
+ */
80
+ async function waitForPendingFilesystemCapture(resourceId, timeoutMs = 1e4) {
81
+ const pending = pendingCaptures.get(resourceId);
82
+ if (!pending) return;
83
+ let timer;
84
+ try {
85
+ await Promise.race([pending, new Promise((resolve) => {
86
+ timer = setTimeout(resolve, timeoutMs);
87
+ })]);
88
+ } finally {
89
+ clearTimeout(timer);
90
+ }
91
+ }
65
92
  function observeSessionFilesystem(session, dependencies) {
66
- let capture = Promise.resolve();
93
+ let fallbackChain = Promise.resolve();
67
94
  return session.onBeforeAgentEnd(() => {
68
- capture = capture.then(() => captureSessionFilesystem(session, dependencies));
69
- return capture;
95
+ let resourceId;
96
+ try {
97
+ resourceId = session.identity.getResourceId();
98
+ } catch {
99
+ fallbackChain = fallbackChain.then(() => captureSessionFilesystem(session, dependencies));
100
+ return;
101
+ }
102
+ const chain = (pendingCaptures.get(resourceId) ?? Promise.resolve()).then(() => captureSessionFilesystem(session, dependencies));
103
+ pendingCaptures.set(resourceId, chain);
104
+ chain.finally(() => {
105
+ if (pendingCaptures.get(resourceId) === chain) pendingCaptures.delete(resourceId);
106
+ });
70
107
  });
71
108
  }
72
109
  //#endregion
73
- export { captureSessionFilesystem, observeSessionFilesystem, parseFilesystemCaptureFiles };
110
+ export { captureSessionFilesystem, observeSessionFilesystem, parseFilesystemCaptureFiles, waitForPendingFilesystemCapture };
74
111
 
75
112
  //# sourceMappingURL=filesystem-capture.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"filesystem-capture.js","names":[],"sources":["../../src/session/filesystem-capture.ts"],"sourcesContent":["import type { SessionBeforeAgentEndListener } from '@mastra/core/agent-controller';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\n\nimport type { FilesystemFile, FilesystemStorage } from '../storage/domains/filesystem/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\n\nconst GIT_STATUS_ARGS = ['status', '--porcelain=v1', '-z', '--untracked-files=all'];\nconst ARTIFACTS_LIST_COMMAND = 'cd \"$1\" && test -d .artifacts && find .artifacts -type f -print0 || true';\n\nexport interface FilesystemCaptureSession {\n readonly identity: { getResourceId(): string };\n readonly thread: { requireId(): string };\n getWorkspace(): { sandbox?: Pick<WorkspaceSandbox, 'executeCommand'> } | undefined;\n onBeforeAgentEnd(listener: SessionBeforeAgentEndListener): () => void;\n}\n\nexport interface FilesystemCaptureDependencies {\n filesystem: Pick<FilesystemStorage, 'replaceFiles'>;\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'getBySessionId'>;\n };\n}\n\nexport function parseFilesystemCaptureFiles(output: string): FilesystemFile[] {\n const files = new Map<string, FilesystemFile>();\n const records = output.split('\\0');\n\n for (let index = 0; index < records.length; index += 1) {\n const record = records[index];\n if (!record || record.length < 4) continue;\n\n const code = record.slice(0, 2);\n let path = record.slice(3);\n const moved = code.includes('R') || code.includes('C');\n if (moved) index += 1;\n if (path.startsWith('./')) path = path.slice(2);\n if (!path || (!code.includes('U') && code.includes('D') && !moved)) continue;\n\n files.set(path, { path });\n }\n\n return [...files.values()].toSorted((a, b) => a.path.localeCompare(b.path));\n}\n\nexport async function captureSessionFilesystem(\n session: FilesystemCaptureSession,\n { filesystem, sourceControl }: FilesystemCaptureDependencies,\n): Promise<void> {\n try {\n const resourceId = session.identity.getResourceId();\n const threadId = session.thread.requireId();\n const sourceSession = await sourceControl.sessions.getBySessionId(resourceId);\n // Chat-only sessions run without a workspace; there is nothing to capture.\n const sandbox = session.getWorkspace()?.sandbox;\n if (!sourceSession?.sandboxWorkdir || !sandbox?.executeCommand) return;\n\n const result = await sandbox.executeCommand('git', ['-C', sourceSession.sandboxWorkdir, ...GIT_STATUS_ARGS], {\n timeout: 30_000,\n });\n if (result.exitCode !== 0) {\n console.warn('[Factory filesystem capture] Unable to inspect Git status.', result.stderr);\n return;\n }\n\n const artifacts = await sandbox.executeCommand(\n 'sh',\n ['-c', ARTIFACTS_LIST_COMMAND, 'sh', sourceSession.sandboxWorkdir],\n { timeout: 30_000 },\n );\n if (artifacts.exitCode !== 0) {\n console.warn('[Factory filesystem capture] Unable to list workspace artifacts.', artifacts.stderr);\n return;\n }\n\n const files = new Map(parseFilesystemCaptureFiles(result.stdout).map(file => [file.path, file]));\n for (const path of artifacts.stdout.split('\\0')) {\n const normalizedPath = path.replace(/^\\.\\//, '');\n if (normalizedPath) {\n files.set(normalizedPath, { path: normalizedPath });\n }\n }\n\n await filesystem.replaceFiles({\n resourceId,\n threadId,\n files: [...files.values()].toSorted((a, b) => a.path.localeCompare(b.path)),\n });\n } catch (error) {\n console.warn('[Factory filesystem capture] Unable to persist files.', error);\n }\n}\n\nexport function observeSessionFilesystem(\n session: FilesystemCaptureSession,\n dependencies: FilesystemCaptureDependencies,\n): () => void {\n let capture = Promise.resolve();\n return session.onBeforeAgentEnd(() => {\n capture = capture.then(() => captureSessionFilesystem(session, dependencies));\n return capture;\n });\n}\n"],"mappings":";AAMA,MAAM,kBAAkB;CAAC;CAAU;CAAkB;CAAM;AAAuB;AAClF,MAAM,yBAAyB;AAgB/B,SAAgB,4BAA4B,QAAkC;CAC5E,MAAM,wBAAQ,IAAI,IAA4B;CAC9C,MAAM,UAAU,OAAO,MAAM,IAAI;CAEjC,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,QAAQ,SAAS,GAAG;EACtD,MAAM,SAAS,QAAQ;EACvB,IAAI,CAAC,UAAU,OAAO,SAAS,GAAG;EAElC,MAAM,OAAO,OAAO,MAAM,GAAG,CAAC;EAC9B,IAAI,OAAO,OAAO,MAAM,CAAC;EACzB,MAAM,QAAQ,KAAK,SAAS,GAAG,KAAK,KAAK,SAAS,GAAG;EACrD,IAAI,OAAO,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gBAAgB,EAAE,MAAM,eAAe,CAAC;EAEtD;EAEA,MAAM,WAAW,aAAa;GAC5B;GACA;GACA,OAAO,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC,CAAC,UAAU,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;EAC5E,CAAC;CACH,SAAS,OAAO;EACd,QAAQ,KAAK,yDAAyD,KAAK;CAC7E;AACF;AAEA,SAAgB,yBACd,SACA,cACY;CACZ,IAAI,UAAU,QAAQ,QAAQ;CAC9B,OAAO,QAAQ,uBAAuB;EACpC,UAAU,QAAQ,WAAW,yBAAyB,SAAS,YAAY,CAAC;EAC5E,OAAO;CACT,CAAC;AACH"}
1
+ {"version":3,"file":"filesystem-capture.js","names":[],"sources":["../../src/session/filesystem-capture.ts"],"sourcesContent":["import type { SessionBeforeAgentEndListener } from '@mastra/core/agent-controller';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\n\nimport type { FilesystemFile, FilesystemStorage } from '../storage/domains/filesystem/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\n\nconst GIT_STATUS_ARGS = ['status', '--porcelain=v1', '-z', '--untracked-files=all'];\nconst ARTIFACTS_LIST_COMMAND = 'cd \"$1\" && test -d .artifacts && find .artifacts -type f -print0 || true';\n\nexport interface FilesystemCaptureSession {\n readonly identity: { getResourceId(): string };\n readonly thread: { requireId(): string };\n getWorkspace(): { sandbox?: Pick<WorkspaceSandbox, 'executeCommand'> } | undefined;\n onBeforeAgentEnd(listener: SessionBeforeAgentEndListener): () => void;\n}\n\nexport interface FilesystemCaptureDependencies {\n filesystem: Pick<FilesystemStorage, 'replaceFiles'>;\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'getBySessionId'>;\n };\n}\n\nexport function parseFilesystemCaptureFiles(output: string): FilesystemFile[] {\n const files = new Map<string, FilesystemFile>();\n const records = output.split('\\0');\n\n for (let index = 0; index < records.length; index += 1) {\n const record = records[index];\n if (!record || record.length < 4) continue;\n\n const code = record.slice(0, 2);\n let path = record.slice(3);\n const moved = code.includes('R') || code.includes('C');\n if (moved) index += 1;\n if (path.startsWith('./')) path = path.slice(2);\n if (!path || (!code.includes('U') && code.includes('D') && !moved)) continue;\n\n files.set(path, { path });\n }\n\n return [...files.values()].toSorted((a, b) => a.path.localeCompare(b.path));\n}\n\nexport async function captureSessionFilesystem(\n session: FilesystemCaptureSession,\n { filesystem, sourceControl }: FilesystemCaptureDependencies,\n): Promise<void> {\n try {\n const resourceId = session.identity.getResourceId();\n const threadId = session.thread.requireId();\n const sourceSession = await sourceControl.sessions.getBySessionId(resourceId);\n // Chat-only sessions run without a workspace; there is nothing to capture.\n const sandbox = session.getWorkspace()?.sandbox;\n if (!sourceSession?.sandboxWorkdir || !sandbox?.executeCommand) return;\n\n const result = await sandbox.executeCommand('git', ['-C', sourceSession.sandboxWorkdir, ...GIT_STATUS_ARGS], {\n timeout: 30_000,\n });\n if (result.exitCode !== 0) {\n console.warn('[Factory filesystem capture] Unable to inspect Git status.', result.stderr);\n return;\n }\n\n const artifacts = await sandbox.executeCommand(\n 'sh',\n ['-c', ARTIFACTS_LIST_COMMAND, 'sh', sourceSession.sandboxWorkdir],\n { timeout: 30_000 },\n );\n if (artifacts.exitCode !== 0) {\n console.warn('[Factory filesystem capture] Unable to list workspace artifacts.', artifacts.stderr);\n return;\n }\n\n const files = new Map(parseFilesystemCaptureFiles(result.stdout).map(file => [file.path, file]));\n for (const path of artifacts.stdout.split('\\0')) {\n const normalizedPath = path.replace(/^\\.\\//, '');\n if (normalizedPath) {\n files.set(normalizedPath, { path: normalizedPath });\n }\n }\n\n await filesystem.replaceFiles({\n resourceId,\n threadId,\n files: [...files.values()].toSorted((a, b) => a.path.localeCompare(b.path)),\n });\n } catch (error) {\n console.warn('[Factory filesystem capture] Unable to persist files.', error);\n }\n}\n\n/**\n * In-flight capture chains keyed by session resource id. Serves two purposes:\n * readers of the persisted file listing (the /web/workspace routes) await the\n * capture for the turn that just ended instead of racing it, and captures for\n * the same resource stay sequential (last write wins) even when multiple\n * scoped sessions observe the same resource id. In-process only: the factory\n * server that runs the session controller also serves those routes.\n */\nconst pendingCaptures = new Map<string, Promise<void>>();\n\n/**\n * Resolve once the session's in-flight filesystem capture (if any) has\n * persisted, or after `timeoutMs` so a reader that arrives mid-capture is\n * never blocked by the execs' worst-case 30s timeouts. Never rejects: the\n * capture body is fully try/catch contained.\n */\nexport async function waitForPendingFilesystemCapture(resourceId: string, timeoutMs = 10_000): Promise<void> {\n const pending = pendingCaptures.get(resourceId);\n if (!pending) return;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n pending,\n new Promise<void>(resolve => {\n timer = setTimeout(resolve, timeoutMs);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport function observeSessionFilesystem(\n session: FilesystemCaptureSession,\n dependencies: FilesystemCaptureDependencies,\n): () => void {\n let fallbackChain = Promise.resolve();\n return session.onBeforeAgentEnd(() => {\n // Chain so captures stay sequential (last write wins), but do NOT return\n // the chain: finishAgentRun awaits every listener before emitting\n // agent_end, and the capture's sandbox execs (git status + artifacts\n // find, 30s timeouts each) must not gate turn completion. Readers that\n // need the fresh listing await the pending capture through\n // waitForPendingFilesystemCapture instead. The un-returned chain cannot\n // leak an unhandled rejection: captureSessionFilesystem's entire body\n // runs inside its own try/catch, and disposal of this listener does not\n // cancel an in-flight chain, so a final turn's capture still persists.\n let resourceId: string | undefined;\n try {\n resourceId = session.identity.getResourceId();\n } catch {\n // No resource id means no route can address this session's listing;\n // keep a per-observer chain so captures still run sequentially.\n fallbackChain = fallbackChain.then(() => captureSessionFilesystem(session, dependencies));\n return;\n }\n // Extend the resource-level chain rather than a per-session one: sessions\n // are deduplicated by (resourceId, scope), so multiple scoped sessions can\n // observe the same resource, and their captures must not interleave.\n const chain = (pendingCaptures.get(resourceId) ?? Promise.resolve()).then(() =>\n captureSessionFilesystem(session, dependencies),\n );\n pendingCaptures.set(resourceId, ch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uBAAuB;EAUpC,IAAI;EACJ,IAAI;GACF,aAAa,QAAQ,SAAS,cAAc;EAC9C,QAAQ;GAGN,gBAAgB,cAAc,WAAW,yBAAyB,SAAS,YAAY,CAAC;GACxF;EACF;EAIA,MAAM,SAAS,gBAAgB,IAAI,UAAU,KAAK,QAAQ,QAAQ,EAAA,CAAG,WACnE,yBAAyB,SAAS,YAAY,CAChD;EACA,gBAAgB,IAAI,YAAY,KAAK;EACrC,MAAW,cAAc;GACvB,IAAI,gBAAgB,IAAI,UAAU,MAAM,OACtC,gBAAgB,OAAO,UAAU;EAErC,CAAC;CACH,CAAC;AACH"}
@@ -0,0 +1,55 @@
1
+ import type { ActiveModelPackRecord, ModelPacksStorage } from '../storage/domains/model-packs/base.js';
2
+ import type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';
3
+ import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
4
+ export interface ModelPackApplicableSession {
5
+ mode: {
6
+ get(): string;
7
+ };
8
+ model: {
9
+ switch(args: {
10
+ modelId: string;
11
+ }): Promise<unknown>;
12
+ };
13
+ subagents: {
14
+ model: {
15
+ set(args: {
16
+ modelId: string;
17
+ agentType: string;
18
+ }): Promise<unknown>;
19
+ };
20
+ };
21
+ thread: {
22
+ getSetting?(args: {
23
+ key: string;
24
+ }): Promise<unknown>;
25
+ setSetting(args: {
26
+ key: string;
27
+ value: unknown;
28
+ }): Promise<unknown>;
29
+ };
30
+ }
31
+ export interface ModelPackHydrationSession extends ModelPackApplicableSession {
32
+ readonly identity: {
33
+ getResourceId(): string;
34
+ };
35
+ state: {
36
+ get(): Record<string, unknown> | undefined;
37
+ };
38
+ thread: ModelPackApplicableSession['thread'] & {
39
+ getId(): string | null | undefined;
40
+ getSetting(args: {
41
+ key: string;
42
+ }): Promise<unknown>;
43
+ };
44
+ }
45
+ export declare function applyActiveModelPack(session: ModelPackApplicableSession, activePack: Pick<ActiveModelPackRecord, 'packId' | 'models'>): Promise<void>;
46
+ export interface ModelPackHydrationDependencies {
47
+ sourceControl: {
48
+ sessions: Pick<SourceControlStorageHandle['sessions'], 'getBySessionId'>;
49
+ };
50
+ workItems: Pick<WorkItemsStorage, 'findActiveRunBindingByThread'>;
51
+ modelPacks: Pick<ModelPacksStorage, 'getActive'>;
52
+ }
53
+ /** Seed the user's default pack unless the interactive thread already selected its own pack. */
54
+ export declare function hydrateSessionModelPack(session: ModelPackHydrationSession, { sourceControl, workItems, modelPacks }: ModelPackHydrationDependencies): Promise<void>;
55
+ //# sourceMappingURL=model-pack-hydration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-pack-hydration.d.ts","sourceRoot":"","sources":["../../src/session/model-pack-hydration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,wCAAwC,CAAC;AACvG,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAC5F,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,MAAM,WAAW,0BAA0B;IACzC,IAAI,EAAE;QAAE,GAAG,IAAI,MAAM,CAAA;KAAE,CAAC;IACxB,KAAK,EAAE;QAAE,MAAM,CAAC,IAAI,EAAE;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;KAAE,CAAC;IAC/D,SAAS,EAAE;QAAE,KAAK,EAAE;YAAE,GAAG,CAAC,IAAI,EAAE;gBAAE,OAAO,EAAE,MAAM,CAAC;gBAAC,SAAS,EAAE,MAAM,CAAA;aAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;SAAE,CAAA;KAAE,CAAC;IAC9F,MAAM,EAAE;QACN,UAAU,CAAC,CAAC,IAAI,EAAE;YAAE,GAAG,EAAE,MAAM,CAAA;SAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;QACrD,UAAU,CAAC,IAAI,EAAE;YAAE,GAAG,EAAE,MAAM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elId] of Object.entries(activePack.models)) await session.thread.setSetting({
4
+ key: `modeModelId_${modeId}`,
5
+ value: modelId
6
+ });
7
+ const currentMode = session.mode.get();
8
+ const currentModeModel = currentMode === "build" || currentMode === "plan" || currentMode === "fast" ? activePack.models[currentMode] : void 0;
9
+ if (currentModeModel) await session.model.switch({ modelId: currentModeModel });
10
+ const subagentModels = [
11
+ ["explore", activePack.models.fast],
12
+ ["plan", activePack.models.plan],
13
+ ["execute", activePack.models.build]
14
+ ];
15
+ for (const [agentType, modelId] of subagentModels) await session.subagents.model.set({
16
+ modelId,
17
+ agentType
18
+ });
19
+ await session.thread.setSetting({
20
+ key: "activeModelPackId",
21
+ value: activePack.packId
22
+ });
23
+ }
24
+ /** Seed the user's default pack unless the interactive thread already selected its own pack. */
25
+ async function hydrateSessionModelPack(session, { sourceControl, workItems, modelPacks }) {
26
+ const resourceId = session.identity.getResourceId();
27
+ if (session.state.get()?.factoryProjectId || typeof session.thread.getSetting !== "function") return;
28
+ try {
29
+ const sourceSession = await sourceControl.sessions.getBySessionId(resourceId);
30
+ if (!sourceSession) return;
31
+ const threadId = session.thread.getId();
32
+ if (threadId && await workItems.findActiveRunBindingByThread({
33
+ orgId: sourceSession.orgId,
34
+ threadId,
35
+ resourceId,
36
+ sessionId: resourceId
37
+ })) return;
38
+ if ((await Promise.all([
39
+ session.thread.getSetting({ key: "activeModelPackId" }),
40
+ session.thread.getSetting({ key: "modeModelId_build" }),
41
+ session.thread.getSetting({ key: "modeModelId_plan" }),
42
+ session.thread.getSetting({ key: "modeModelId_fast" })
43
+ ])).some((setting) => typeof setting === "string")) return;
44
+ const activePack = await modelPacks.getActive({
45
+ orgId: sourceSession.orgId,
46
+ userId: sourceSession.userId
47
+ });
48
+ if (activePack) await applyActiveModelPack(session, activePack);
49
+ } catch (error) {
50
+ console.warn("[Factory model-pack hydration] Unable to apply the active model pack.", error);
51
+ }
52
+ }
53
+ //#endregion
54
+ export { applyActiveModelPack, hydrateSessionModelPack };
55
+
56
+ //# sourceMappingURL=model-pack-hydration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-pack-hydration.js","names":[],"sources":["../../src/session/model-pack-hydration.ts"],"sourcesContent":["import type { ActiveModelPackRecord, ModelPacksStorage } from '../storage/domains/model-packs/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\n\nexport interface ModelPackApplicableSession {\n mode: { get(): string };\n model: { switch(args: { modelId: string }): Promise<unknown> };\n subagents: { model: { set(args: { modelId: string; agentType: string }): Promise<unknown> } };\n thread: {\n getSetting?(args: { key: string }): Promise<unknown>;\n setSetting(args: { key: string; value: unknown }): Promise<unknown>;\n };\n}\n\nexport interface ModelPackHydrationSession extends ModelPackApplicableSession {\n readonly identity: { getResourceId(): string };\n state: { get(): Record<string, unknown> | undefined };\n thread: ModelPackApplicableSession['thread'] & {\n getId(): string | null | undefined;\n getSetting(args: { key: string }): Promise<unknown>;\n };\n}\n\nexport async function applyActiveModelPack(\n session: ModelPackApplicableSession,\n activePack: Pick<ActiveModelPackRecord, 'packId' | 'models'>,\n): Promise<void> {\n for (const [modeId, modelId] of Object.entries(activePack.models)) {\n await session.thread.setSetting({ key: `modeModelId_${modeId}`, value: modelId });\n }\n\n const currentMode = session.mode.get();\n const currentModeModel =\n currentMode === 'build' || currentMode === 'plan' || currentMode === 'fast'\n ? activePack.models[currentMode]\n : undefined;\n if (currentModeModel) {\n await session.model.switch({ modelId: currentModeModel });\n }\n\n const subagentModels = [\n ['explore', activePack.models.fast],\n ['plan', activePack.models.plan],\n ['execute', activePack.models.build],\n ] as const;\n for (const [agentType, modelId] of subagentModels) {\n await session.subagents.model.set({ modelId, agentType });\n }\n\n await session.thread.setSetting({ key: 'activeModelPackId', value: activePack.packId });\n}\n\nexport interface ModelPackHydrationDependencies {\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'getBySessionId'>;\n };\n workItems: Pick<WorkItemsStorage, 'findActiveRunBindingByThread'>;\n modelPacks: Pick<ModelPacksStorage, 'getActive'>;\n}\n\n/** Seed the user's default pack unless the interactive thread already selected its own pack. */\nexport async function hydrateSessionModelPack(\n session: ModelPackHydrationSession,\n { sourceControl, workItems, modelPacks }: ModelPackHydrationDependencies,\n): Promise<void> {\n const resourceId = session.identity.getResourceId();\n if (session.state.get()?.factoryProjectId || typeof session.thread.getSetting !== 'function') return;\n try {\n const sourceSession = await sourceControl.sessions.getBySessionId(resourceId);\n if (!sourceSession) return;\n const threadId = session.thread.getId();\n if (\n threadId &&\n (await workItems.findActiveRunBindingByThread({\n orgId: sourceSession.orgId,\n threadId,\n resourceId,\n sessionId: resourceId,\n }))\n ) {\n return;\n }\n const existingThreadSettings = await Promise.all([\n session.thread.getSetting({ key: 'activeModelPackId' }),\n session.thread.getSetting({ key: 'modeModelId_build' }),\n session.thread.getSetting({ key: 'modeModelId_plan' }),\n session.thread.getSetting({ key: 'modeModelId_fast' }),\n ]);\n if (existingThreadSettings.some(setting => typeof setting === 'string')) return;\n\n const activePack = await modelPacks.getActive({ orgId: sourceSession.orgId, userId: sourceSession.userId });\n if (activePack) await applyActiveModelPack(session, activePack);\n } catch (error) {\n console.warn('[Factory model-pack hydration] Unable to apply the active model pack.', error);\n }\n}\n"],"mappings":";AAuBA,eAAsB,qBACpB,SACA,YACe;CACf,KAAK,MAAM,CAAC,QAAQ,YAAY,OAAO,QAAQ,WAAW,MAAM,GAC9D,MAAM,QAAQ,OAAO,WAAW;EAAE,KAAK,eAAe;EAAU,OAAO;CAAQ,CAAC;CAGlF,MAAM,cAAc,QAAQ,KAAK,IAAI;CACrC,MAAM,mBACJ,gBAAgB,WAAW,gBAAgB,UAAU,gBAAgB,SACjE,WAAW,OAAO,eAClB,KAAA;CACN,IAAI,kBACF,MAAM,QAAQ,MAAM,OAAO,EAAE,SAAS,iBAAiB,CAAC;CAG1D,MAAM,iBAAiB;EACrB,CAAC,WAAW,WAAW,OAAO,IAAI;EAClC,CAAC,QAAQ,WAAW,OAAO,IAAI;EAC/B,CAAC,WAAW,WAAW,OAAO,KAAK;CACrC;CACA,KAAK,MAAM,CAAC,WAAW,YAAY,gBACjC,MAAM,QAAQ,UAAU,MAAM,IAAI;EAAE;EAAS;CAAU,CAAC;CAG1D,MAAM,QAAQ,OAAO,WAAW;EAAE,KAAK;EAAqB,OAAO,WAAW;CAAO,CAAC;AACxF;;AAWA,eAAsB,wBACpB,SACA,EAAE,eAAe,WAAW,cACb;CACf,MAAM,aAAa,QAAQ,SAAS,cAAc;CAClD,IAAI,QAAQ,MAAM,IAAI,CAAC,EAAE,oBAAoB,OAAO,QAAQ,OAAO,eAAe,YAAY;CAC9F,IAAI;EACF,MAAM,gBAAgB,MAAM,cAAc,SAAS,eAAe,UAAU;EAC5E,IAAI,CAAC,eAAe;EACpB,MAAM,WAAW,QAAQ,OAAO,MAAM;EACtC,IACE,YACC,MAAM,UAAU,6BAA6B;GAC5C,OAAO,cAAc;GACrB;GACA;GACA,WAAW;EACb,CAAC,GAED;EAQF,KAAI,MANiC,QAAQ,IAAI;GAC/C,QAAQ,OAAO,WAAW,EAAE,KAAK,oBAAoB,CAAC;GACtD,QAAQ,OAAO,WAAW,EAAE,KAAK,oBAAoB,CAAC;GACtD,QAAQ,OAAO,WAAW,EAAE,KAAK,mBAAmB,CAAC;GACrD,QAAQ,OAAO,WAAW,EAAE,KAAK,mBAAmB,CAAC;EACvD,CAAC,EAAA,CAC0B,MAAK,YAAW,OAAO,YAAY,QAAQ,GAAG;EAEzE,MAAM,aAAa,MAAM,WAAW,UAAU;GAAE,OAAO,cAAc;GAAO,QAAQ,cAAc;EAAO,CAAC;EAC1G,IAAI,YAAY,MAAM,qBAAqB,SAAS,UAAU;CAChE,SAAS,OAAO;EACd,QAAQ,KAAK,yEAAyE,KAAK;CAC7F;AACF"}
@@ -36,6 +36,15 @@ export declare class SkillInvocationError extends Error {
36
36
  readonly code: 'session_not_found' | 'skill_not_found';
37
37
  constructor(code: SkillInvocationError['code'], message: string);
38
38
  }
39
+ /** Kicks a run off from a plain prompt, for runs that activate no skill. */
40
+ export declare function resolvePromptInvocation(controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>, input: {
41
+ resourceId: string;
42
+ scope?: SkillInvocationInput['scope'];
43
+ prompt: string;
44
+ }): Promise<{
45
+ session: SkillSession;
46
+ message: string;
47
+ }>;
39
48
  export declare function resolveSkillInvocation(controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>, input: SkillInvocationInput): Promise<{
40
49
  session: SkillSession;
41
50
  skillName: string;
@@ -1 +1 @@
1
- {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/skills/service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAEnE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAExD,MAAM,WAAW,oBAAoB;IACnC,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,YAAY;IAC3B,YAAY,IAAI,SAAS,CAAC;IAC1B,WAAW,CAAC,KAAK,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1D,sBAAsB,CACpB,KAAK,EAAE;QACL,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;QAChB,QAAQ,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,QA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CAAC,IAAI,EAAE,mBAAmB,GAAG,iBAAiB,CAAC;gBAE3C,IAAI,EAAE,oBAAoB,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,MAAM;CAKhE;AAMD,4EAA4E;AAC5E,wBAAsB,uBAAuB,CAC3C,UAAU,EAAE,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,EAAE,sBAAsB,CAAC,EAC1E,KAAK,EAAE;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,oBAAoB,CAAC,OAAO,CAAC,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACnF,OAAO,CAAC;IAAE,OAAO,EAAE,YAAY,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAIrD;AAED,wBAAsB,sBAAsB,CAC1C,UAAU,EAAE,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,EAAE,sBAAsB,CAAC,EAC1E,KAAK,EAAE,oBAAoB,GAC1B,OAAO,CAAC;IAAE,OAAO,EAAE,YAAY,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAkBxE;AAED,wBAAsB,uBAAuB,CAC3C,UAAU,EAAE,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,EAAE,sBAAsB,CAAC,EAC1E,KAAK,EAAE,oBAAoB,GAC1B,OAAO,CAAC;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAIjD"}
@@ -11,6 +11,15 @@ var SkillInvocationError = class extends Error {
11
11
  function escapeSkillBoundary(value) {
12
12
  return value.replaceAll("</skill>", "&lt;/skill&gt;");
13
13
  }
14
+ /** Kicks a run off from a plain prompt, for runs that activate no skill. */
15
+ async function resolvePromptInvocation(controller, input) {
16
+ const session = await controller.getSessionByResource(input.resourceId, input.scope);
17
+ if (!session) throw new SkillInvocationError("session_not_found", "Agent controller session not found.");
18
+ return {
19
+ session,
20
+ message: input.prompt
21
+ };
22
+ }
14
23
  async function resolveSkillInvocation(controller, input) {
15
24
  const session = await controller.getSessionByResource(input.resourceId, input.scope);
16
25
  if (!session) throw new SkillInvocationError("session_not_found", "Agent controller session not found.");
@@ -35,6 +44,6 @@ async function dispatchSkillInvocation(controller, input) {
35
44
  };
36
45
  }
37
46
  //#endregion
38
- export { SkillInvocationError, dispatchSkillInvocation, resolveSkillInvocation };
47
+ export { SkillInvocationError, dispatchSkillInvocation, resolvePromptInvocation, resolveSkillInvocation };
39
48
 
40
49
  //# sourceMappingURL=service.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","names":[],"sources":["../../src/skills/service.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { SendAgentSignalResult } from '@mastra/core/agent';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { formatSkillActivation } from '@mastra/core/workspace';\nimport type { Workspace } from '@mastra/core/workspace';\n\nexport interface SkillInvocationInput {\n resourceId: string;\n scope?: string;\n name: string;\n arguments?: string;\n}\n\nexport interface SkillSession {\n getWorkspace(): Workspace;\n sendMessage(input: { content: string }): Promise<unknown>;\n sendNotificationSignal(\n input: {\n source: string;\n kind: string;\n summary: string;\n priority?: 'low' | 'medium' | 'high' | 'urgent';\n payload?: unknown;\n dedupeKey?: string;\n sourceId?: string;\n },\n options?: {\n ifActive?: { behavior?: 'deliver' | 'persist' };\n ifIdle?: { behavior?: 'persist' | 'wake' };\n requestContext?: RequestContext;\n },\n ): Promise<Pick<SendAgentSignalResult, 'persisted' | 'accepted'>>;\n}\n\nexport class SkillInvocationError extends Error {\n readonly code: 'session_not_found' | 'skill_not_found';\n\n constructor(code: SkillInvocationError['code'], message: string) {\n super(message);\n this.name = 'SkillInvocationError';\n this.code = code;\n }\n}\n\nfunction escapeSkillBoundary(value: string): string {\n return value.replaceAll('</skill>', '&lt;/skill&gt;');\n}\n\nexport async function resolveSkillInvocation(\n controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>,\n input: SkillInvocationInput,\n): Promise<{ session: SkillSession; skillName: string; message: string }> {\n const session = (await controller.getSessionByResource(input.resourceId, input.scope)) as SkillSession | undefined;\n if (!session) throw new SkillInvocationError('session_not_found', 'Agent controller session not found.');\n\n const skills = session.getWorkspace().skills;\n await skills?.maybeRefresh();\n const skill = await skills?.get(input.name);\n if (!skill || skill['user-invocable'] === false) {\n throw new SkillInvocationError('skill_not_found', `Skill not found: ${input.name}.`);\n }\n\n const args = input.arguments?.trim();\n const content = `${formatSkillActivation(skill)}${args ? `\\n\\nARGUMENTS: ${args}` : ''}`.trim();\n return {\n session,\n skillName: skill.name,\n message: `<skill name=\"${skill.name}\">\\n${escapeSkillBoundary(content)}\\n</skill>`,\n };\n}\n\nexport async function dispatchSkillInvocation(\n controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>,\n input: SkillInvocationInput,\n): Promise<{ skillName: string; message: string }> {\n const resolved = await resolveSkillInvocation(controller, input);\n await resolved.session.sendMessage({ content: resolved.message });\n return { skillName: resolved.skillName, message: resolved.message };\n}\n"],"mappings":";;AAmCA,IAAa,uBAAb,cAA0C,MAAM;CAC9C;CAEA,YAAY,MAAoC,SAAiB;EAC/D,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;AAEA,SAAS,oBAAoB,OAAuB;CAClD,OAAO,MAAM,WAAW,YAAY,gBAAgB;AACtD;AAEA,eAAsB,uBACpB,YACA,OACwE;CACxE,MAAM,UAAW,MAAM,WAAW,qBAAqB,MAAM,YAAY,MAAM,KAAK;CACpF,IAAI,CAAC,SAAS,MAAM,IAAI,qBAAqB,qBAAqB,qCAAqC;CAEvG,MAAM,SAAS,QAAQ,aAAa,CAAC,CAAC;CACtC,MAAM,QAAQ,aAAa;CAC3B,MAAM,QAAQ,MAAM,QAAQ,IAAI,MAAM,IAAI;CAC1C,IAAI,CAAC,SAAS,MAAM,sBAAsB,OACxC,MAAM,IAAI,qBAAqB,mBAAmB,oBAAoB,MAAM,KAAK,EAAE;CAGrF,MAAM,OAAO,MAAM,WAAW,KAAK;CACnC,MAAM,UAAU,GAAG,sBAAsB,KAAK,IAAI,OAAO,kBAAkB,SAAS,KAAK,KAAK;CAC9F,OAAO;EACL;EACA,WAAW,MAAM;EACjB,SAAS,gBAAgB,MAAM,KAAK,MAAM,oBAAoB,OAAO,EAAE;CACzE;AACF;AAEA,eAAsB,wBACpB,YACA,OACiD;CACjD,MAAM,WAAW,MAAM,uBAAuB,YAAY,KAAK;CAC/D,MAAM,SAAS,QAAQ,YAAY,EAAE,SAAS,SAAS,QAAQ,CAAC;CAChE,OAAO;EAAE,WAAW,SAAS;EAAW,SAAS,SAAS;CAAQ;AACpE"}
1
+ {"version":3,"file":"service.js","names":[],"sources":["../../src/skills/service.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { SendAgentSignalResult } from '@mastra/core/agent';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { formatSkillActivation } from '@mastra/core/workspace';\nimport type { Workspace } from '@mastra/core/workspace';\n\nexport interface SkillInvocationInput {\n resourceId: string;\n scope?: string;\n name: string;\n arguments?: string;\n}\n\nexport interface SkillSession {\n getWorkspace(): Workspace;\n sendMessage(input: { content: string }): Promise<unknown>;\n sendNotificationSignal(\n input: {\n source: string;\n kind: string;\n summary: string;\n priority?: 'low' | 'medium' | 'high' | 'urgent';\n payload?: unknown;\n dedupeKey?: string;\n sourceId?: string;\n },\n options?: {\n ifActive?: { behavior?: 'deliver' | 'persist' };\n ifIdle?: { behavior?: 'persist' | 'wake' };\n requestContext?: RequestContext;\n },\n ): Promise<Pick<SendAgentSignalResult, 'persisted' | 'accepted'>>;\n}\n\nexport class SkillInvocationError extends Error {\n readonly code: 'session_not_found' | 'skill_not_found';\n\n constructor(code: SkillInvocationError['code'], message: string) {\n super(message);\n this.name = 'SkillInvocationError';\n this.code = code;\n }\n}\n\nfunction escapeSkillBoundary(value: string): string {\n return value.replaceAll('</skill>', '&lt;/skill&gt;');\n}\n\n/** Kicks a run off from a plain prompt, for runs that activate no skill. */\nexport async function resolvePromptInvocation(\n controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>,\n input: { resourceId: string; scope?: SkillInvocationInput['scope']; prompt: string },\n): Promise<{ session: SkillSession; message: string }> {\n const session = (await controller.getSessionByResource(input.resourceId, input.scope)) as SkillSession | undefined;\n if (!session) throw new SkillInvocationError('session_not_found', 'Agent controller session not found.');\n return { session, message: input.prompt };\n}\n\nexport async function resolveSkillInvocation(\n controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>,\n input: SkillInvocationInput,\n): Promise<{ session: SkillSession; skillName: string; message: string }> {\n const session = (await controller.getSessionByResource(input.resourceId, input.scope)) as SkillSession | undefined;\n if (!session) throw new SkillInvocationError('session_not_found', 'Agent controller session not found.');\n\n const skills = session.getWorkspace().skills;\n await skills?.maybeRefresh();\n const skill = await skills?.get(input.name);\n if (!skill || skill['user-invocable'] === false) {\n throw new SkillInvocationError('skill_not_found', `Skill not found: ${input.name}.`);\n }\n\n const args = input.arguments?.trim();\n const content = `${formatSkillActivation(skill)}${args ? `\\n\\nARGUMENTS: ${args}` : ''}`.trim();\n return {\n session,\n skillName: skill.name,\n message: `<skill name=\"${skill.name}\">\\n${escapeSkillBoundary(content)}\\n</skill>`,\n };\n}\n\nexport async function dispatchSkillInvocation(\n controller: Pick<AgentController<MastraCodeState>, 'getSessionByResource'>,\n input: SkillInvocationInput,\n): Promise<{ skillName: string; message: string }> {\n const resolved = await resolveSkillInvocation(controller, input);\n await resolved.session.sendMessage({ content: resolved.message });\n return { skillName: resolved.skillName, message: resolved.message };\n}\n"],"mappings":";;AAmCA,IAAa,uBAAb,cAA0C,MAAM;CAC9C;CAEA,YAAY,MAAoC,SAAiB;EAC/D,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;AAEA,SAAS,oBAAoB,OAAuB;CAClD,OAAO,MAAM,WAAW,YAAY,gBAAgB;AACtD;;AAGA,eAAsB,wBACpB,YACA,OACqD;CACrD,MAAM,UAAW,MAAM,WAAW,qBAAqB,MAAM,YAAY,MAAM,KAAK;CACpF,IAAI,CAAC,SAAS,MAAM,IAAI,qBAAqB,qBAAqB,qCAAqC;CACvG,OAAO;EAAE;EAAS,SAAS,MAAM;CAAO;AAC1C;AAEA,eAAsB,uBACpB,YACA,OACwE;CACxE,MAAM,UAAW,MAAM,WAAW,qBAAqB,MAAM,YAAY,MAAM,KAAK;CACpF,IAAI,CAAC,SAAS,MAAM,IAAI,qBAAqB,qBAAqB,qCAAqC;CAEvG,MAAM,SAAS,QAAQ,aAAa,CAAC,CAAC;CACtC,MAAM,QAAQ,aAAa;CAC3B,MAAM,QAAQ,MAAM,QAAQ,IAAI,MAAM,IAAI;CAC1C,IAAI,CAAC,SAAS,MAAM,sBAAsB,OACxC,MAAM,IAAI,qBAAqB,mBAAmB,oBAAoB,MAAM,KAAK,EAAE;CAGrF,MAAM,OAAO,MAAM,WAAW,KAAK;CACnC,MAAM,UAAU,GAAG,sBAAsB,KAAK,IAAI,OAAO,kBAAkB,SAAS,KAAK,KAAK;CAC9F,OAAO;EACL;EACA,WAAW,MAAM;EACjB,SAAS,gBAAgB,MAAM,KAAK,MAAM,oBAAoB,OAAO,EAAE;CACzE;AACF;AAEA,eAAsB,wBACpB,YACA,OACiD;CACjD,MAAM,WAAW,MAAM,uBAAuB,YAAY,KAAK;CAC/D,MAAM,SAAS,QAAQ,YAAY,EAAE,SAAS,SAAS,QAAQ,CAAC;CAChE,OAAO;EAAE,WAAW,SAAS;EAAW,SAAS,SAAS;CAAQ;AACpE"}
@@ -15,6 +15,20 @@ export interface IntakeSelection {
15
15
  export type IntakeConfig = Record<string, IntakeSelection>;
16
16
  export declare const DEFAULT_INTAKE_CONFIG: IntakeConfig;
17
17
  export declare const INTAKE_SETTINGS_SCHEMA: CollectionSchema;
18
+ /**
19
+ * Binds an intake source to the Factory project its items belong to.
20
+ *
21
+ * Intake selections are per user and org-wide, so they cannot say *where* an
22
+ * ingested item should land. GitHub items are naturally scoped by their linked
23
+ * repository; providers without that link (Linear) need this explicit binding
24
+ * so viewing one project's board cannot materialize another project's items.
25
+ */
26
+ export declare const INTAKE_SOURCE_BINDINGS_SCHEMA: CollectionSchema;
27
+ export interface IntakeSourceBinding {
28
+ integrationId: string;
29
+ sourceId: string;
30
+ factoryProjectId: string;
31
+ }
18
32
  export declare class IntakeStorage extends FactoryStorageDomain {
19
33
  #private;
20
34
  constructor();
@@ -34,5 +48,27 @@ export declare class IntakeStorage extends FactoryStorageDomain {
34
48
  userId: string;
35
49
  config: IntakeConfig;
36
50
  }): Promise<void>;
51
+ /** Every source binding in the org, optionally narrowed to one integration. */
52
+ listBindings({ orgId, integrationId, }: {
53
+ orgId: string;
54
+ integrationId?: string;
55
+ }): Promise<IntakeSourceBinding[]>;
56
+ /** Source ids bound to one Factory project. Empty means "nothing bound". */
57
+ listBoundSourceIds({ orgId, integrationId, factoryProjectId, }: {
58
+ orgId: string;
59
+ integrationId: string;
60
+ factoryProjectId: string;
61
+ }): Promise<string[]>;
62
+ /**
63
+ * Points a source at a Factory project, replacing any existing binding.
64
+ * A `null` project clears the binding.
65
+ */
66
+ setBinding({ orgId, integrationId, sourceId, factoryProjectId, userId, }: {
67
+ orgId: string;
68
+ integrationId: string;
69
+ sourceId: string;
70
+ factoryProjectId: string | null;
71
+ userId?: string;
72
+ }): Promise<void>;
37
73
  }
38
74
  //# sourceMappingURL=base.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/intake/base.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,oBAAoB,EAAwB,MAAM,sBAAsB,CAAC;AAClF,OAAO,KAAK,EAAE,gBAAgB,EAAqB,MAAM,sBAAs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ASrB;;;OAGG;IACG,UAAU,CAAC,EACf,KAAK,EACL,aAAa,EACb,QAAQ,EACR,gBAAgB,EAChB,MAAM,GACP,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,aAAa,EAAE,MAAM,CAAC;QACtB,QAAQ,EAAE,MAAM,CAAC;QACjB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;QAChC,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,GAAG,OAAO,CAAC,IAAI,CAAC;CAuBlB"}
@@ -23,15 +23,52 @@ const INTAKE_SETTINGS_SCHEMA = {
23
23
  columns: ["org_id", "user_id"]
24
24
  }]
25
25
  };
26
+ /**
27
+ * Binds an intake source to the Factory project its items belong to.
28
+ *
29
+ * Intake selections are per user and org-wide, so they cannot say *where* an
30
+ * ingested item should land. GitHub items are naturally scoped by their linked
31
+ * repository; providers without that link (Linear) need this explicit binding
32
+ * so viewing one project's board cannot materialize another project's items.
33
+ */
34
+ const INTAKE_SOURCE_BINDINGS_SCHEMA = {
35
+ name: "intake_source_bindings",
36
+ columns: {
37
+ id: { type: "uuid-pk" },
38
+ org_id: { type: "text" },
39
+ integration_id: { type: "text" },
40
+ source_id: { type: "text" },
41
+ factory_project_id: { type: "text" },
42
+ created_by_user_id: {
43
+ type: "text",
44
+ nullable: true
45
+ },
46
+ created_at: { type: "timestamp" },
47
+ updated_at: { type: "timestamp" }
48
+ },
49
+ indexes: [{
50
+ name: "intake_source_bindings_project_idx",
51
+ columns: ["org_id", "factory_project_id"]
52
+ }],
53
+ uniqueIndexes: [{
54
+ name: "intake_source_bindings_org_integration_source_unique",
55
+ columns: [
56
+ "org_id",
57
+ "integration_id",
58
+ "source_id"
59
+ ]
60
+ }]
61
+ };
26
62
  var IntakeStorage = class extends FactoryStorageDomain {
27
63
  constructor() {
28
64
  super("intake");
29
65
  }
30
66
  async init() {
31
- await this.ensureCollections([INTAKE_SETTINGS_SCHEMA]);
67
+ await this.ensureCollections([INTAKE_SETTINGS_SCHEMA, INTAKE_SOURCE_BINDINGS_SCHEMA]);
32
68
  }
33
69
  async dangerouslyClearAll() {
34
70
  await this.ops.deleteMany("intake_settings", {});
71
+ await this.ops.deleteMany("intake_source_bindings", {});
35
72
  }
36
73
  get #db() {
37
74
  return this.ops;
@@ -73,8 +110,60 @@ var IntakeStorage = class extends FactoryStorageDomain {
73
110
  });
74
111
  }
75
112
  }
113
+ /** Every source binding in the org, optionally narrowed to one integration. */
114
+ async listBindings({ orgId, integrationId }) {
115
+ return (await this.#db.findMany("intake_source_bindings", {
116
+ org_id: orgId,
117
+ ...integrationId ? { integration_id: integrationId } : {}
118
+ })).map((row) => ({
119
+ integrationId: row.integration_id,
120
+ sourceId: row.source_id,
121
+ factoryProjectId: row.factory_project_id
122
+ }));
123
+ }
124
+ /** Source ids bound to one Factory project. Empty means "nothing bound". */
125
+ async listBoundSourceIds({ orgId, integrationId, factoryProjectId }) {
126
+ return (await this.#db.findMany("intake_source_bindings", {
127
+ org_id: orgId,
128
+ integration_id: integrationId,
129
+ factory_project_id: factoryProjectId
130
+ })).map((row) => row.source_id);
131
+ }
132
+ /**
133
+ * Points a source at a Factory project, replacing any existing binding.
134
+ * A `null` project clears the binding.
135
+ */
136
+ async setBinding({ orgId, integrationId, sourceId, factoryProjectId, userId }) {
137
+ const where = {
138
+ org_id: orgId,
139
+ integration_id: integrationId,
140
+ source_id: sourceId
141
+ };
142
+ if (factoryProjectId === null) {
143
+ await this.#db.deleteMany("intake_source_bindings", where);
144
+ return;
145
+ }
146
+ const now = /* @__PURE__ */ new Date();
147
+ const patch = {
148
+ factory_project_id: factoryProjectId,
149
+ updated_at: now
150
+ };
151
+ if (await this.#db.updateMany("intake_source_bindings", where, patch) > 0) return;
152
+ try {
153
+ await this.#db.insertOne("intake_source_bindings", {
154
+ ...where,
155
+ factory_project_id: factoryProjectId,
156
+ created_by_user_id: userId ?? null,
157
+ created_at: now,
158
+ updated_at: now
159
+ });
160
+ } catch (error) {
161
+ if (!(error instanceof UniqueViolationError)) throw error;
162
+ await this.#db.updateMany("intake_source_bindings", where, patch);
163
+ }
164
+ }
76
165
  };
77
166
  //#endregion
78
- export { DEFAULT_INTAKE_CONFIG, INTAKE_SETTINGS_SCHEMA, IntakeStorage };
167
+ export { DEFAULT_INTAKE_CONFIG, INTAKE_SETTINGS_SCHEMA, INTAKE_SOURCE_BINDINGS_SCHEMA, IntakeStorage };
79
168
 
80
169
  //# sourceMappingURL=base.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":["#db"],"sources":["../../../../src/storage/domains/intake/base.ts"],"sourcesContent":["/**\n * Per-user intake selections for every configured intake integration.\n *\n * Integration ids are dynamic. Each integration contributes provider-neutral\n * sources through `FactoryIntegration.intake`; this domain only persists which\n * source ids the user selected.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nexport interface IntakeSelection {\n enabled: boolean;\n /** Provider-owned source ids; `null` means nothing is selected. */\n sourceIds: string[] | null;\n}\n\nexport type IntakeConfig = Record<string, IntakeSelection>;\n\nexport const DEFAULT_INTAKE_CONFIG: IntakeConfig = {};\n\nexport const INTAKE_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_settings_org_user_unique', columns: ['org_id', 'user_id'] }],\n};\n\nexport class IntakeStorage extends FactoryStorageDomain {\n constructor() {\n super('intake');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([INTAKE_SETTINGS_SCHEMA]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('intake_settings', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async getConfig({\n orgId,\n userId,\n integrationIds,\n }: {\n orgId: string;\n userId: string;\n /**\n * When provided, the result contains exactly these integration ids, with\n * unset integrations defaulting to `{ enabled: true, sourceIds: null }`.\n */\n integrationIds?: string[];\n }): Promise<IntakeConfig> {\n const row = await this.#db.findOne<{ config: IntakeConfig }>('intake_settings', {\n org_id: orgId,\n user_id: userId,\n });\n const saved = structuredClone(row?.config ?? DEFAULT_INTAKE_CONFIG);\n if (!integrationIds) return saved;\n return Object.fromEntries(\n integrationIds.map(integrationId => [integrationId, saved[integrationId] ?? { enabled: true, sourceIds: null }]),\n );\n }\n\n async saveConfig({ orgId, userId, config }: { orgId: string; userId: string; config: IntakeConfig }): Promise<void> {\n const now = new Date();\n const where = { org_id: orgId, user_id: userId };\n const updated = await this.#db.updateMany('intake_settings', where, { config, updated_at: now });\n if (updated > 0) return;\n try {\n await this.#db.insertOne('intake_settings', { ...where, config, created_at: now, updated_at: now });\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n await this.#db.updateMany('intake_settings', where, { config, updated_at: now });\n }\n }\n}\n"],"mappings":";;;;;;;;;AAmBA,MAAa,wBAAsC,CAAC;AAEpD,MAAa,yBAA2C;CACtD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,SAAS,EAAE,MAAM,OAAO;EACxB,QAAQ,EAAE,MAAM,OAAO;EACvB,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CAAC;EAAE,MAAM;EAAmC,SAAS,CAAC,UAAU,SAAS;CAAE,CAAC;AAC7F;AAEA,IAAa,gBAAb,cAAmC,qBAAqB;CACtD,cAAc;EACZ,MAAM,QAAQ;CAChB;CAEA,MAAM,OAAsB;EAC1B,MAAM,KAAK,kBAAkB,CAAC,sBAAsB,CAAC;CACvD;CAEA,MAAM,sBAAqC;EACzC,MAAM,KAAK,IAAI,WAAW,mBAAmB,CAAC,CAAC;CACjD;CAEA,IAAIA,MAAyB;EAC3B,OAAO,KAAK;CACd;CAEA,MAAM,UAAU,EACd,OACA,QACA,kBASwB;EACxB,MAAM,MAAM,MAAM,KAAKA,IAAI,QAAkC,mBAAmB;GAC9E,QAAQ;GACR,SAAS;EACX,CAAC;EACD,MAAM,QAAQ,gBAAgB,KAAK,UAAU,qBAAqB;EAClE,IAAI,CAAC,gBAAgB,OAAO;EAC5B,OAAO,OAAO,YACZ,eAAe,KAAI,kBAAiB,CAAC,eAAe,MAAM,kBAAkB;GAAE,SAAS;GAAM,WAAW;EAAK,CAAC,CAAC,CACjH;CACF;CAEA,MAAM,WAAW,EAAE,OAAO,QAAQ,UAAkF;EAClH,MAAM,sBAAM,IAAI,KAAK;EACrB,MAAM,QAAQ;GAAE,QAAQ;GAAO,SAAS;EAAO;EAE/C,IAAI,MADkB,KAAKA,IAAI,WAAW,mBAAmB,OAAO;GAAE;GAAQ,YAAY;EAAI,CAAC,IACjF,GAAG;EACjB,IAAI;GACF,MAAM,KAAKA,IAAI,UAAU,mBAAmB;IAAE,GAAG;IAAO;IAAQ,YAAY;IAAK,YAAY;GAAI,CAAC;EACpG,SAAS,OAAO;GACd,IAAI,EAAE,iBAAiB,uBAAuB,MAAM;GACpD,MAAM,KAAKA,IAAI,WAAW,mBAAmB,OAAO;IAAE;IAAQ,YAAY;GAAI,CAAC;EACjF;CACF;AACF"}
1
+ {"version":3,"file":"base.js","names":["#db"],"sources":["../../../../src/storage/domains/intake/base.ts"],"sourcesContent":["/**\n * Per-user intake selections for every configured intake integration.\n *\n * Integration ids are dynamic. Each integration contributes provider-neutral\n * sources through `FactoryIntegration.intake`; this domain only persists which\n * source ids the user selected.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nexport interface IntakeSelection {\n enabled: boolean;\n /** Provider-owned source ids; `null` means nothing is selected. */\n sourceIds: string[] | null;\n}\n\nexport type IntakeConfig = Record<string, IntakeSelection>;\n\nexport const DEFAULT_INTAKE_CONFIG: IntakeConfig = {};\n\nexport const INTAKE_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_settings_org_user_unique', columns: ['org_id', 'user_id'] }],\n};\n\n/**\n * Binds an intake source to the Factory project its items belong to.\n *\n * Intake selections are per user and org-wide, so they cannot say *where* an\n * ingested item should land. GitHub items are naturally scoped by their linked\n * repository; providers without that link (Linear) need this explicit binding\n * so viewing one project's board cannot materialize another project's items.\n */\nexport const INTAKE_SOURCE_BINDINGS_SCHEMA: CollectionSchema = {\n name: 'intake_source_bindings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_bindings_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_bindings_org_integration_source_unique',\n columns: ['org_id', 'integration_id', 'source_id'],\n },\n ],\n};\n\nexport interface IntakeSourceBinding {\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n}\n\ntype IntakeSourceBindingRow = {\n integration_id: string;\n source_id: string;\n factory_project_id: string;\n};\n\nexport class IntakeStorage extends FactoryStorageDomain {\n constructor() {\n super('intake');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([INTAKE_SETTINGS_SCHEMA, INTAKE_SOURCE_BINDINGS_SCHEMA]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('intake_settings', {});\n await this.ops.deleteMany('intake_source_bindings', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async getConfig({\n orgId,\n userId,\n integrationIds,\n }: {\n orgId: string;\n userId: string;\n /**\n * When provided, the result contains exactly these integration ids, with\n * unset integrations defaulting to `{ enabled: true, sourceIds: null }`.\n */\n integrationIds?: string[];\n }): Promise<IntakeConfig> {\n const row = await this.#db.findOne<{ config: IntakeConfig }>('intake_settings', {\n org_id: orgId,\n user_id: userId,\n });\n const saved = structuredClone(row?.config ?? DEFAULT_INTAKE_CONFIG);\n if (!integrationIds) return saved;\n return Object.fromEntries(\n integrationIds.map(integrationId => [integrationId, saved[integrationId] ?? { enabled: true, sourceIds: null }]),\n );\n }\n\n async saveConfig({ orgId, userId, config }: { orgId: string; userId: string; config: IntakeConfig }): Promise<void> {\n const now = new Date();\n const where = { org_id: orgId, user_id: userId };\n const updated = await this.#db.updateMany('intake_settings', where, { config, updated_at: now });\n if (updated > 0) return;\n try {\n await this.#db.insertOne('intake_settings', { ...where, config, created_at: now, updated_at: now });\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n await this.#db.updateMany('intake_settings', where, { config, updated_at: now });\n }\n }\n\n /** Every source binding in the org, optionally narrowed to one integration. */\n async listBindings({\n orgId,\n integrationId,\n }: {\n orgId: string;\n integrationId?: string;\n }): Promise<IntakeSourceBinding[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_bindings', {\n org_id: orgId,\n ...(integrationId ? { integration_id: integrationId } : {}),\n });\n return rows.map(row => ({\n integrationId: row.integration_id,\n sourceId: row.source_id,\n factoryProjectId: row.factory_project_id,\n }));\n }\n\n /** Source ids bound to one Factory project. Empty means \"nothing bound\". */\n async listBoundSourceIds({\n orgId,\n integrationId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n factoryProjectId: string;\n }): Promise<string[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_bindings', {\n org_id: orgId,\n integration_id: integrationId,\n factory_project_id: factoryProjectId,\n });\n return rows.map(row => row.source_id);\n }\n\n /**\n * Points a source at a Factory project, replacing any existing binding.\n * A `null` project clears the binding.\n */\n async setBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string | null;\n userId?: string;\n }): Promise<void> {\n const where = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n if (factoryProjectId === null) {\n await this.#db.deleteMany('intake_source_bindings', where);\n return;\n }\n const now = new Date();\n const patch = { factory_project_id: factoryProjectId, updated_at: now };\n const updated = await this.#db.updateMany('intake_source_bindings', where, patch);\n if (updated > 0) return;\n try {\n await this.#db.insertOne('intake_source_bindings', {\n ...where,\n factory_project_id: factoryProjectId,\n created_by_user_id: userId ?? null,\n created_at: now,\n updated_at: now,\n });\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n await this.#db.updateMany('intake_source_bindings', where, patch);\n }\n }\n}\n"],"mappings":";;;;;;;;;AAmBA,MAAa,wBAAsC,CAAC;AAEpD,MAAa,yBAA2C;CACtD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,SAAS,EAAE,MAAM,OAAO;EACxB,QAAQ,EAAE,MAAM,OAAO;EACvB,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CAAC;EAAE,MAAM;EAAmC,SAAS,CAAC,UAAU,SAAS;CAAE,CAAC;AAC7F;;;;;;;;;AAUA,MAAa,gCAAkD;CAC7D,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,gBAAgB,EAAE,MAAM,OAAO;EAC/B,WAAW,EAAE,MAAM,OAAO;EAC1B,oBAAoB,EAAE,MAAM,OAAO;EACnC,oBAAoB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACnD,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,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