@mastra/factory 0.28.0 → 0.29.0-alpha.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 (224) hide show
  1. package/README.md +6 -4
  2. package/dist/boards/reroute.d.ts +31 -0
  3. package/dist/boards/reroute.d.ts.map +1 -0
  4. package/dist/boards/reroute.js +71 -0
  5. package/dist/boards/reroute.js.map +1 -0
  6. package/dist/environment/repository-access.d.ts +2 -0
  7. package/dist/environment/repository-access.d.ts.map +1 -1
  8. package/dist/environment/repository-access.js +9 -4
  9. package/dist/environment/repository-access.js.map +1 -1
  10. package/dist/factory.d.ts.map +1 -1
  11. package/dist/factory.js +9 -6
  12. package/dist/factory.js.map +1 -1
  13. package/dist/integrations/base.d.ts +8 -0
  14. package/dist/integrations/base.d.ts.map +1 -1
  15. package/dist/integrations/dependabot/default-rules.d.ts +38 -0
  16. package/dist/integrations/dependabot/default-rules.d.ts.map +1 -0
  17. package/dist/integrations/dependabot/default-rules.js +63 -0
  18. package/dist/integrations/dependabot/default-rules.js.map +1 -0
  19. package/dist/integrations/dependabot/rules.d.ts +42 -0
  20. package/dist/integrations/dependabot/rules.d.ts.map +1 -0
  21. package/dist/integrations/dependabot/rules.js +187 -0
  22. package/dist/integrations/dependabot/rules.js.map +1 -0
  23. package/dist/integrations/dependabot/sync.d.ts +76 -0
  24. package/dist/integrations/dependabot/sync.d.ts.map +1 -0
  25. package/dist/integrations/dependabot/sync.js +111 -0
  26. package/dist/integrations/dependabot/sync.js.map +1 -0
  27. package/dist/integrations/github/routes.d.ts.map +1 -1
  28. package/dist/integrations/github/routes.js +7 -2
  29. package/dist/integrations/github/routes.js.map +1 -1
  30. package/dist/integrations/github/sandbox.d.ts +12 -0
  31. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  32. package/dist/integrations/github/sandbox.js +22 -1
  33. package/dist/integrations/github/sandbox.js.map +1 -1
  34. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  35. package/dist/integrations/platform/connect/routes.js +4 -0
  36. package/dist/integrations/platform/connect/routes.js.map +1 -1
  37. package/dist/integrations/platform/github/event-worker.d.ts +5 -0
  38. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  39. package/dist/integrations/platform/github/event-worker.js +33 -2
  40. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  41. package/dist/integrations/platform/github/integration.d.ts +19 -1
  42. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  43. package/dist/integrations/platform/github/integration.js +46 -0
  44. package/dist/integrations/platform/github/integration.js.map +1 -1
  45. package/dist/integrations/platform/vanta/integration.d.ts +33 -0
  46. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -0
  47. package/dist/integrations/platform/vanta/integration.js +133 -0
  48. package/dist/integrations/platform/vanta/integration.js.map +1 -0
  49. package/dist/integrations/vanta/default-rules.d.ts +34 -0
  50. package/dist/integrations/vanta/default-rules.d.ts.map +1 -0
  51. package/dist/integrations/vanta/default-rules.js +61 -0
  52. package/dist/integrations/vanta/default-rules.js.map +1 -0
  53. package/dist/integrations/vanta/rules.d.ts +40 -0
  54. package/dist/integrations/vanta/rules.d.ts.map +1 -0
  55. package/dist/integrations/vanta/rules.js +208 -0
  56. package/dist/integrations/vanta/rules.js.map +1 -0
  57. package/dist/integrations/vanta/sync.d.ts +36 -0
  58. package/dist/integrations/vanta/sync.d.ts.map +1 -0
  59. package/dist/integrations/vanta/sync.js +73 -0
  60. package/dist/integrations/vanta/sync.js.map +1 -0
  61. package/dist/mcp/routes.d.ts.map +1 -1
  62. package/dist/mcp/routes.js +1 -1
  63. package/dist/mcp/routes.js.map +1 -1
  64. package/dist/routes/board-snapshot.d.ts +8 -1
  65. package/dist/routes/board-snapshot.d.ts.map +1 -1
  66. package/dist/routes/board-snapshot.js +23 -2
  67. package/dist/routes/board-snapshot.js.map +1 -1
  68. package/dist/routes/contracts.d.ts +205 -0
  69. package/dist/routes/contracts.d.ts.map +1 -1
  70. package/dist/routes/contracts.js +159 -5
  71. package/dist/routes/contracts.js.map +1 -1
  72. package/dist/routes/intake-routes.d.ts +3 -0
  73. package/dist/routes/intake-routes.d.ts.map +1 -1
  74. package/dist/routes/intake-routes.js +44 -0
  75. package/dist/routes/intake-routes.js.map +1 -1
  76. package/dist/routes/knowledge.d.ts.map +1 -1
  77. package/dist/routes/knowledge.js +3 -2
  78. package/dist/routes/knowledge.js.map +1 -1
  79. package/dist/routes/source-control-sessions.d.ts +1 -1
  80. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  81. package/dist/routes/source-control-sessions.js +109 -3
  82. package/dist/routes/source-control-sessions.js.map +1 -1
  83. package/dist/routes/surface.d.ts +6 -1
  84. package/dist/routes/surface.d.ts.map +1 -1
  85. package/dist/routes/surface.js +72 -9
  86. package/dist/routes/surface.js.map +1 -1
  87. package/dist/routes/work-item-selection.d.ts +0 -4
  88. package/dist/routes/work-item-selection.d.ts.map +1 -1
  89. package/dist/routes/work-item-selection.js +4 -21
  90. package/dist/routes/work-item-selection.js.map +1 -1
  91. package/dist/routes/work-item-starters.d.ts.map +1 -1
  92. package/dist/routes/work-item-starters.js +4 -21
  93. package/dist/routes/work-item-starters.js.map +1 -1
  94. package/dist/routes/work-items.d.ts.map +1 -1
  95. package/dist/routes/work-items.js +112 -36
  96. package/dist/routes/work-items.js.map +1 -1
  97. package/dist/rules/dispatch-errors.d.ts +3 -0
  98. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  99. package/dist/rules/dispatch-errors.js +5 -0
  100. package/dist/rules/dispatch-errors.js.map +1 -1
  101. package/dist/rules/dispatcher.d.ts +2 -0
  102. package/dist/rules/dispatcher.d.ts.map +1 -1
  103. package/dist/rules/dispatcher.js +39 -18
  104. package/dist/rules/dispatcher.js.map +1 -1
  105. package/dist/rules/index.d.ts +2 -2
  106. package/dist/rules/index.d.ts.map +1 -1
  107. package/dist/rules/index.js +2 -2
  108. package/dist/rules/start-coordinator.d.ts +6 -1
  109. package/dist/rules/start-coordinator.d.ts.map +1 -1
  110. package/dist/rules/start-coordinator.js +6 -2
  111. package/dist/rules/start-coordinator.js.map +1 -1
  112. package/dist/rules/transition-service.d.ts.map +1 -1
  113. package/dist/rules/transition-service.js +3 -2
  114. package/dist/rules/transition-service.js.map +1 -1
  115. package/dist/rules/types.d.ts +71 -3
  116. package/dist/rules/types.d.ts.map +1 -1
  117. package/dist/rules/types.js +10 -2
  118. package/dist/rules/types.js.map +1 -1
  119. package/dist/rules/validation.d.ts.map +1 -1
  120. package/dist/rules/validation.js +5 -0
  121. package/dist/rules/validation.js.map +1 -1
  122. package/dist/session/factory-session.d.ts +20 -5
  123. package/dist/session/factory-session.d.ts.map +1 -1
  124. package/dist/session/factory-session.js +20 -6
  125. package/dist/session/factory-session.js.map +1 -1
  126. package/dist/storage/domains/audit/actions.d.ts +1 -1
  127. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  128. package/dist/storage/domains/audit/actions.js +2 -1
  129. package/dist/storage/domains/audit/actions.js.map +1 -1
  130. package/dist/storage/domains/audit/actors.d.ts.map +1 -1
  131. package/dist/storage/domains/audit/actors.js +1 -1
  132. package/dist/storage/domains/audit/actors.js.map +1 -1
  133. package/dist/storage/domains/intake/base.d.ts +1 -1
  134. package/dist/storage/domains/intake/base.js +2 -2
  135. package/dist/storage/domains/intake/base.js.map +1 -1
  136. package/dist/storage/domains/projects/base.d.ts +8 -0
  137. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  138. package/dist/storage/domains/projects/base.js +11 -1
  139. package/dist/storage/domains/projects/base.js.map +1 -1
  140. package/dist/storage/domains/work-items/base.d.ts +15 -4
  141. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  142. package/dist/storage/domains/work-items/base.js +19 -1
  143. package/dist/storage/domains/work-items/base.js.map +1 -1
  144. package/dist/tools/approval-tools.d.ts +20 -0
  145. package/dist/tools/approval-tools.d.ts.map +1 -1
  146. package/dist/tools/approval-tools.js +79 -30
  147. package/dist/tools/approval-tools.js.map +1 -1
  148. package/dist/tools/audit-events-tool.d.ts +1 -1
  149. package/dist/tools/messaging-tools.d.ts.map +1 -1
  150. package/dist/tools/messaging-tools.js +1 -1
  151. package/dist/tools/messaging-tools.js.map +1 -1
  152. package/dist/tools/read-tools.d.ts +0 -2
  153. package/dist/tools/read-tools.d.ts.map +1 -1
  154. package/dist/tools/read-tools.js +2 -7
  155. package/dist/tools/read-tools.js.map +1 -1
  156. package/dist/tools/reports.d.ts +3 -0
  157. package/dist/tools/reports.d.ts.map +1 -1
  158. package/dist/tools/reports.js +3 -3
  159. package/dist/tools/reports.js.map +1 -1
  160. package/dist/tools/run-watch.d.ts +14 -2
  161. package/dist/tools/run-watch.d.ts.map +1 -1
  162. package/dist/tools/run-watch.js +24 -4
  163. package/dist/tools/run-watch.js.map +1 -1
  164. package/dist/tools/session-tools.d.ts.map +1 -1
  165. package/dist/tools/session-tools.js +17 -6
  166. package/dist/tools/session-tools.js.map +1 -1
  167. package/dist/tools/side-sessions.d.ts.map +1 -1
  168. package/dist/tools/side-sessions.js +1 -1
  169. package/dist/tools/side-sessions.js.map +1 -1
  170. package/dist/tools/work-item-tools.d.ts.map +1 -1
  171. package/dist/tools/work-item-tools.js +12 -2
  172. package/dist/tools/work-item-tools.js.map +1 -1
  173. package/dist/work-item-branch.d.ts +1 -1
  174. package/dist/work-item-branch.d.ts.map +1 -1
  175. package/dist/work-item-branch.js +2 -0
  176. package/dist/work-item-branch.js.map +1 -1
  177. package/dist/work-items/board-filter-options.d.ts +5 -0
  178. package/dist/work-items/board-filter-options.d.ts.map +1 -0
  179. package/dist/work-items/board-filter-options.js +27 -0
  180. package/dist/work-items/board-filter-options.js.map +1 -0
  181. package/dist/work-items/board-phases.d.ts +28 -0
  182. package/dist/work-items/board-phases.d.ts.map +1 -0
  183. package/dist/work-items/board-phases.js +165 -0
  184. package/dist/work-items/board-phases.js.map +1 -0
  185. package/dist/work-items/card-facts.d.ts +24 -0
  186. package/dist/work-items/card-facts.d.ts.map +1 -0
  187. package/dist/work-items/card-facts.js +75 -0
  188. package/dist/work-items/card-facts.js.map +1 -0
  189. package/dist/work-items/card-labels.d.ts +5 -0
  190. package/dist/work-items/card-labels.d.ts.map +1 -0
  191. package/dist/work-items/card-labels.js +13 -0
  192. package/dist/work-items/card-labels.js.map +1 -0
  193. package/dist/work-items/card-number.d.ts +10 -0
  194. package/dist/work-items/card-number.d.ts.map +1 -0
  195. package/dist/work-items/card-number.js +15 -0
  196. package/dist/work-items/card-number.js.map +1 -0
  197. package/dist/work-items/card-people.d.ts +25 -0
  198. package/dist/work-items/card-people.d.ts.map +1 -0
  199. package/dist/work-items/card-people.js +100 -0
  200. package/dist/work-items/card-people.js.map +1 -0
  201. package/dist/work-items/card-search-text.d.ts +4 -0
  202. package/dist/work-items/card-search-text.d.ts.map +1 -0
  203. package/dist/work-items/card-search-text.js +15 -0
  204. package/dist/work-items/card-search-text.js.map +1 -0
  205. package/dist/work-items/card-source-filters.d.ts +23 -0
  206. package/dist/work-items/card-source-filters.d.ts.map +1 -0
  207. package/dist/work-items/card-source-filters.js +25 -0
  208. package/dist/work-items/card-source-filters.js.map +1 -0
  209. package/dist/work-items/create-work-item.d.ts +0 -6
  210. package/dist/work-items/create-work-item.d.ts.map +1 -1
  211. package/dist/work-items/create-work-item.js +2 -7
  212. package/dist/work-items/create-work-item.js.map +1 -1
  213. package/dist/work-items/list-related-cards.d.ts +4 -0
  214. package/dist/work-items/list-related-cards.d.ts.map +1 -0
  215. package/dist/work-items/list-related-cards.js +24 -0
  216. package/dist/work-items/list-related-cards.js.map +1 -0
  217. package/dist/work-items/search-words.d.ts +5 -0
  218. package/dist/work-items/search-words.d.ts.map +1 -0
  219. package/dist/work-items/search-words.js +12 -0
  220. package/dist/work-items/search-words.js.map +1 -0
  221. package/dist/workspace.d.ts.map +1 -1
  222. package/dist/workspace.js +92 -47
  223. package/dist/workspace.js.map +1 -1
  224. package/package.json +6 -5
@@ -1 +1 @@
1
- {"version":3,"file":"read-tools.js","names":[],"sources":["../../src/tools/read-tools.ts"],"sourcesContent":["import { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport {\n awaitsAcceptance,\n boardFlow,\n boardForWorkItem,\n isTerminalWorkItem,\n pullRequestSourceNumber,\n pullRequestSources,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { factorySessionUrl, factoryWorkItemUrl } from '../links.js';\nimport { parkedRunLabel } from '../routes/attention-parked.js';\nimport { decisionRetryable, overtakenDecisionIds } from '../rules/decision-applicability.js';\nimport { factoryDispatchFailureMetadata } from '../rules/dispatch-errors.js';\nimport { needsApproval } from '../rules/types.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport { resolveWorkItemRepository } from '../session/work-item-repository.js';\nimport type { AuditStorage } from '../storage/domains/audit/base.js';\nimport type {\n FactoryDeferredDecisionRecord,\n FactoryRunBindingRecord,\n Card,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport { CARD_NUMBER_METADATA_KEY } from '../work-items/create-work-item.js';\nimport { sessionActivity } from './deliver.js';\nimport type { FactorySessionActivity } from './deliver.js';\nimport type { FactoryMessaging } from './messaging-tools.js';\nimport type { FactoryToolScope } from './scope.js';\n\nexport const MAX_TEXT = 600;\nexport const MAX_ERROR = 400;\nexport const MAX_LIST = 50;\nconst DEFAULT_LIST = 25;\n\nexport interface FactoryReadToolDependencies {\n workItems: Pick<\n WorkItemsStorage,\n | 'listShared'\n | 'getForProject'\n | 'listRunBindings'\n | 'listDeferredDecisions'\n | 'listByIds'\n | 'listDecisionsForEvaluations'\n | 'listWorkItemSubscribers'\n | 'listSessionSubscriptions'\n >;\n audit: Pick<AuditStorage, 'list'>;\n /** A fixed registry, or the per-project boards. */\n boards: BoardRegistry | ProjectBoardSource;\n /** The live controller, for whether a session is mid-run and when it last moved; absent before the mount is up. */\n messaging?: () => Promise<Pick<FactoryMessaging, 'controller'> | null>;\n /** Finds the caller session's source-control provider, to tell which cards can't pick a repository. */\n sessions?: Pick<SourceControlSessionLookup, 'getSourceControlBySessionId'>;\n /** Which live sessions are parked on a tool prompt; absent before the mount is up. */\n liveSessions?: () => Pick<LiveSessions, 'parked' | 'parkedIn'> | undefined;\n}\n\nexport function truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n\nfunction iso(value: Date | string | null | undefined): string | null {\n if (!value) return null;\n const date = value instanceof Date ? value : new Date(value);\n return Number.isFinite(date.getTime()) ? date.toISOString() : null;\n}\n\n/** The number a person sees on the card: the issue or PR number the item was filed from, or the project's own number for a card filed by hand. */\nexport function workItemNumber(item: Pick<Card, 'workItem' | 'metadata'>): number | null {\n const number =\n item.workItem.metadata?.number ??\n item.workItem.metadata?.githubIssueNumber ??\n item.workItem.metadata?.githubPullRequestNumber ??\n item.metadata?.[CARD_NUMBER_METADATA_KEY];\n return typeof number === 'number' ? number : null;\n}\n\nexport function workItemStage(item: Pick<Card, 'stages'>): string {\n return item.stages.join('+');\n}\n\n/** A work item id or its card number; anything else can't name an item. */\nexport const workItemRefSchema = z\n .string()\n .trim()\n .max(64)\n .refine(ref => z.string().uuid().safeParse(ref).success || /^#?\\d+$/.test(ref), {\n message: 'Use a work item id (UUID) or its number like \"#123\".',\n })\n .describe('Work item id, or its number like \"#123\".');\n\n/** Resolve `<uuid>` or `#123` to an item in this Factory only. Pass a ref validated by `workItemRefSchema`. */\nexport async function findWorkItem(\n workItems: Pick<WorkItemsStorage, 'listShared' | 'getForProject'>,\n scope: Pick<FactoryToolScope, 'orgId' | 'factoryProjectId'>,\n ref: string,\n): Promise<Card | null> {\n const trimmed = ref.trim();\n const number = /^#?(\\d+)$/.exec(trimmed)?.[1];\n if (number === undefined) return workItems.getForProject(scope.orgId, scope.factoryProjectId, trimmed);\n const items = await workItems.listShared(scope);\n const matches = items.filter(item => workItemNumber(item) === Number(number));\n // Issue and PR numbers share a space on GitHub; prefer the issue's card.\n const workCards = matches.filter(item => item.externalSource?.type !== 'pull-request');\n // Hand-filed card numbers and issue numbers from several repositories can repeat; refuse to guess.\n refuseAmbiguous(number, workCards);\n const match = workCards[0] ?? matches[0];\n if (match) return structuredClone(match);\n // A pull request attached to an issue's card is found through that card. Pull request numbers\n // repeat across repositories too.\n const carriers = items.filter(item =>\n pullRequestSources(item).some(source => pullRequestSourceNumber(source) === Number(number)),\n );\n refuseAmbiguous(number, carriers);\n return carriers[0] ? structuredClone(carriers[0]) : null;\n}\n\nfunction refuseAmbiguous(number: string, items: readonly Card[]): void {\n if (items.length <= 1) return;\n const candidates = items.map(item => `${item.id} (${item.title})`).join(', ');\n throw new Error(`#${number} matches more than one work item; use its id instead: ${candidates}.`);\n}\n\nexport function workItemNotFound(ref: string): Error {\n return new Error(`No work item ${ref} was found in this Factory.`);\n}\n\nfunction activeWorker(bindings: FactoryRunBindingRecord[], itemId: string) {\n const binding = bindings.find(candidate => candidate.workItemId === itemId && candidate.status === 'active');\n return binding ? { role: binding.role, sessionId: binding.sessionId } : null;\n}\n\n/** The card on its Factory board; null when the server has no public URL configured. */\nfunction workItemUrl(item: Card) {\n return (\n factoryWorkItemUrl({\n factoryProjectId: item.factoryProjectId,\n board: boardForWorkItem(item),\n workItemId: item.id,\n }) ?? null\n );\n}\n\nfunction summarizeItem(item: Card, bindings: FactoryRunBindingRecord[]) {\n return {\n id: item.id,\n number: workItemNumber(item),\n title: truncate(item.title, MAX_TEXT),\n board: boardForWorkItem(item),\n stage: workItemStage(item),\n url: workItemUrl(item),\n activeWorker: activeWorker(bindings, item.id),\n requestedBy: item.createdBy,\n updatedAt: iso(item.updatedAt),\n };\n}\n\nfunction summarizeDecision(decision: FactoryDeferredDecisionRecord, overtaken = false) {\n const type = typeof decision.decision.type === 'string' ? decision.decision.type : 'decision';\n const role = typeof decision.decision.role === 'string' ? decision.decision.role : null;\n return {\n id: decision.id,\n workItemId: decision.workItemId,\n type,\n role,\n status: decision.status,\n attempts: decision.attempts,\n failureCode: decision.failureCode,\n failureLabel: decision.failureCode ? factoryDispatchFailureMetadata(decision.failureCode).label : null,\n canRetry: decisionRetryable(decision, overtaken),\n error: decision.lastError ? truncate(decision.lastError, MAX_ERROR) : null,\n approvedBy: decision.approvedBy,\n updatedAt: iso(decision.updatedAt),\n };\n}\n\n/**\n * Held: a card triage left resting (or whose source asks for approval), until a person moves it\n * on. A card that has been past triage since (parked by self-review, or dragged back) resumes\n * instead, matching the board's held state.\n */\nfunction isHeld(boards: BoardRegistry, item: Card): boolean {\n const board = boards.get(boardForWorkItem(item));\n const stage = item.stages.length === 1 ? item.stages[0]! : undefined;\n if (!board || !stage || board.phaseKind(stage) !== 'resting') return false;\n if (needsApproval(item, phase => awaitsAcceptance(board, phase))) return true;\n const triage = boardFlow(board).triage;\n const triageRole = triage ? board.roleForPhase(triage) : undefined;\n if (!triageRole || item.sessions[triageRole] === undefined) return false;\n return !item.stageHistory.some(entry => entry.stage !== triage && board.isWorking(entry.stage));\n}\n\nconst listInputSchema = z\n .object({\n query: z\n .string()\n .trim()\n .min(1)\n .max(200)\n .optional()\n .describe('Case-insensitive text in the title, or an exact card number like \"#123\".'),\n stage: z.string().min(1).max(64).optional().describe('Only items in this stage, e.g. \"triage\" or \"review\".'),\n board: z.string().min(1).max(64).optional().describe('Only items on this board, e.g. \"work\" or \"review\".'),\n role: z.string().min(1).max(64).optional().describe('Only items that have a session for this role.'),\n active: z.boolean().optional().describe('true: only items with an agent working now; false: only idle items.'),\n requestedBy: z.literal('me').optional().describe('\"me\": only items you filed.'),\n subscribed: z\n .boolean()\n .optional()\n .describe('true: only items this session follows; false: only items it does not.'),\n limit: z.number().int().min(1).max(MAX_LIST).optional().describe(`Default ${DEFAULT_LIST}, max ${MAX_LIST}.`),\n })\n .strict();\n\nexport function createFactoryReadTools(scope: FactoryToolScope, deps: FactoryReadToolDependencies): IntegrationTools {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n /**\n * Of `cards` filed by hand, those that name no repository while the Factory\n * links several, so a run on them refuses to start until someone picks one.\n */\n const cardsWithoutRepository = async (cards: Card[]): Promise<{ items: Card[]; candidates: string[] }> => {\n const unnamed = cards.filter(card => typeof card.metadata?.repository !== 'string');\n if (unnamed.length === 0 || !deps.sessions) return { items: [], candidates: [] };\n const sourceControl = await deps.sessions.getSourceControlBySessionId(scope.sessionId);\n if (!sourceControl) return { items: [], candidates: [] };\n // A card filed by hand has no source repository, so one that names none resolves like an empty card.\n const resolution = await resolveWorkItemRepository({\n sourceControl,\n ...project,\n item: { metadata: null, workItem: { metadata: null } },\n });\n return resolution.status === 'ambiguous'\n ? { items: unnamed, candidates: resolution.candidates }\n : { items: [], candidates: [] };\n };\n\n return {\n factory_list_work_items: createTool({\n id: 'factory_list_work_items',\n description:\n \"List this Factory's work items, newest activity first, with counts per stage for the whole Factory. Filter by text or #number, stage, board, role, whether an agent is working on it, items you filed, or items this session follows. Check here for an existing item before filing a new one.\",\n inputSchema: listInputSchema,\n execute: async input => {\n const [items, bindings, followed] = await Promise.all([\n deps.workItems.listShared(project),\n deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId),\n input.subscribed === undefined\n ? undefined\n : deps.workItems.listSessionSubscriptions({ ...project, sessionId: scope.sessionId }),\n ]);\n const followedIds = new Set(followed?.map(subscription => subscription.workItemId));\n const byStage: Record<string, number> = {};\n for (const item of items) {\n const stage = workItemStage(item);\n byStage[stage] = (byStage[stage] ?? 0) + 1;\n }\n const numberQuery = input.query ? /^#(\\d+)$/.exec(input.query)?.[1] : undefined;\n const text = input.query?.toLowerCase();\n const matches = items\n .filter(item => {\n if (numberQuery !== undefined) {\n if (workItemNumber(item) !== Number(numberQuery)) return false;\n } else if (text && !item.title.toLowerCase().includes(text)) return false;\n if (input.stage && !item.stages.includes(input.stage)) return false;\n if (input.board && boardForWorkItem(item) !== input.board) return false;\n if (input.role && !item.sessions[input.role]) return false;\n if (input.active !== undefined && (activeWorker(bindings, item.id) !== null) !== input.active) return false;\n if (input.requestedBy === 'me' && item.createdBy !== scope.userId) return false;\n if (input.subscribed !== undefined && followedIds.has(item.id) !== input.subscribed) return false;\n return true;\n })\n .sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime());\n const limit = input.limit ?? DEFAULT_LIST;\n return {\n counts: { total: items.length, byStage },\n items: matches.slice(0, limit).map(item => summarizeItem(item, bindings)),\n truncated: matches.length > limit,\n };\n },\n }),\n\n factory_inspect_work_item: createTool({\n id: 'factory_inspect_work_item',\n description:\n 'Everything the Factory knows about one work item: its description, stage history, sessions by role (with whether each is mid-run and when its thread last moved), decisions with errors, recent audit events, labels, linked items and the sessions following it. Use it to explain why an item is where it is.',\n inputSchema: z.object({ workItem: workItemRefSchema }).strict(),\n execute: async ({ workItem }) => {\n const item = await findWorkItem(deps.workItems, scope, workItem);\n if (!item) throw workItemNotFound(workItem);\n const [bindings, decisions, audit, all, subscribers] = await Promise.all([\n deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId, item.id),\n deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId, { workItemId: item.id }),\n deps.audit.list({ ...project, limit: 200 }),\n deps.workItems.listShared(project),\n deps.workItems.listWorkItemSubscribers({ orgId: scope.orgId, workItemId: item.id }),\n ]);\n const itemDecisions = decisions.slice(-MAX_LIST);\n const overtaken = await overtakenDecisionIds(\n deps.workItems,\n await toBoardSource(deps.boards).load(project),\n project,\n itemDecisions.filter(decision => decision.status === 'failed'),\n );\n const labels = Array.isArray(item.workItem.labels)\n ? item.workItem.labels.filter((label): label is string => typeof label === 'string').slice(0, MAX_LIST)\n : [];\n const parent = item.parentWorkItemId\n ? all.find(candidate => candidate.id === item.parentWorkItemId)\n : undefined;\n const children = all.filter(candidate => candidate.parentWorkItemId === item.id);\n const controller = (await deps.messaging?.())?.controller;\n const activity = async (sessionId: string, threadId: string): Promise<FactorySessionActivity | null> =>\n controller ? sessionActivity(controller, sessionId, threadId) : null;\n const sessions = await Promise.all(\n Object.entries(item.sessions).map(async ([role, ref]) => ({\n role,\n sessionId: ref.sessionId,\n threadId: ref.threadId,\n url:\n factorySessionUrl({\n factoryProjectId: item.factoryProjectId,\n sessionId: ref.sessionId,\n threadId: ref.threadId,\n }) ?? null,\n startedBy: ref.startedBy,\n active: bindings.some(\n binding => binding.role === role && binding.sessionId === ref.sessionId && binding.status === 'active',\n ),\n // `running` with an old `lastActivityAt` is a stuck run; `running` with a recent one is a long one.\n ...((await activity(ref.sessionId, ref.threadId)) ?? { running: null, lastActivityAt: null }),\n })),\n );\n return {\n item: {\n ...summarizeItem(item, bindings),\n description: item.description,\n source: item.externalSource ? `${item.externalSource.integrationId}:${item.externalSource.type}` : 'manual',\n sourceUrl: typeof item.workItem.url === 'string' ? item.workItem.url : null,\n revision: item.revision,\n },\n labels,\n stageHistory: item.stageHistory.slice(-MAX_LIST).map(entry => ({\n stage: entry.stage,\n enteredAt: entry.enteredAt,\n exitedAt: entry.exitedAt ?? null,\n by: entry.by,\n })),\n sessions,\n decisions: itemDecisions.map(decision => summarizeDecision(decision, overtaken.has(decision.id))),\n audit: audit.events\n .filter(event => event.targets.some(target => target.type === 'work_item' && target.id === item.id))\n .slice(0, 25)\n .map(event => ({\n action: event.action,\n actorId: event.actorId,\n actorType: event.actorType,\n occurredAt: iso(event.occurredAt),\n })),\n parent: parent ? summarizeItem(parent, bindings) : null,\n children: children.slice(0, MAX_LIST).map(child => summarizeItem(child, bindings)),\n subscribers: subscribers.slice(0, MAX_LIST).map(subscription => ({\n sessionId: subscription.sessionId,\n reason: subscription.reason,\n isCaller: subscription.sessionId === scope.sessionId,\n })),\n };\n },\n }),\n\n factory_list_attention: createTool({\n id: 'factory_list_attention',\n description:\n 'What in this Factory needs a person: failed decisions grouped by failure code and error (one incident per group), proposals waiting for approval, runs parked on a tool prompt (a plan to review, a question to answer) while still in flight, Work cards triage left in Intake for a person to move on, and open cards filed by hand that need a repository set (factory_update_work_item) before a run can start.',\n inputSchema: z.object({ limit: z.number().int().min(1).max(MAX_LIST).optional() }).strict(),\n execute: async ({ limit = DEFAULT_LIST }) => {\n const [decisions, items] = await Promise.all([\n deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId, {\n statuses: ['failed', 'proposed'],\n }),\n deps.workItems.listShared(project),\n ]);\n const itemsById = new Map(items.map(item => [item.id, item]));\n const failed = decisions.filter(decision => decision.status === 'failed');\n const groups = new Map<\n string,\n { failureCode: string; error: string; decisions: FactoryDeferredDecisionRecord[] }\n >();\n for (const decision of failed) {\n const error = truncate(decision.lastError ?? '', MAX_ERROR);\n const key = `${decision.failureCode ?? 'unknown'}|${error}`;\n const group = groups.get(key) ?? { failureCode: decision.failureCode ?? 'unknown', error, decisions: [] };\n group.decisions.push(decision);\n groups.set(key, group);\n }\n const ref = (workItemId: string | null) => {\n const item = workItemId ? itemsById.get(workItemId) : undefined;\n return {\n workItemId,\n number: item ? workItemNumber(item) : null,\n title: item ? truncate(item.title, MAX_TEXT) : null,\n url: item ? workItemUrl(item) : null,\n };\n };\n const allIncidents = [...groups.values()].sort((a, b) => b.decisions.length - a.decisions.length);\n const incidents = allIncidents\n .slice(0, limit)\n .map(group => ({ ...group, shown: group.decisions.slice(0, limit) }));\n // Check exactly the decisions this call returns, so every canRetry is real.\n const boards = await toBoardSource(deps.boards).load(project);\n const overtaken = await overtakenDecisionIds(\n deps.workItems,\n boards,\n project,\n incidents.flatMap(group => group.shown),\n );\n const proposals = decisions.filter(decision => decision.status === 'proposed');\n const held = items.filter(item => isHeld(boards, item));\n const unplaced = await cardsWithoutRepository(\n items.filter(item => !item.externalSource && !isTerminalWorkItem(boards, item)),\n );\n const needsRepository = unplaced.items;\n const waiting = (deps.liveSessions?.()?.parkedIn(scope.factoryProjectId) ?? []).sort(\n (a, b) => a.run.suspendedAt - b.run.suspendedAt,\n );\n return {\n incidents: incidents.map(group => ({\n failureCode: group.failureCode,\n failureLabel: factoryDispatchFailureMetadata(group.decisions[0]!.failureCode).label,\n error: group.error,\n count: group.decisions.length,\n decisions: group.shown.map(decision => ({\n id: decision.id,\n ...ref(decision.workItemId),\n attempts: decision.attempts,\n canRetry: decisionRetryable(decision, overtaken.has(decision.id)),\n })),\n })),\n proposals: proposals\n .slice(0, limit)\n .map(decision => ({ ...summarizeDecision(decision), ...ref(decision.workItemId) })),\n waiting: waiting.slice(0, limit).map(({ sessionId, run }) => ({\n sessionId,\n toolName: run.toolName,\n label: parkedRunLabel(run.toolName),\n waitingSince: new Date(run.suspendedAt).toISOString(),\n })),\n held: held.slice(0, limit).map(item => ({\n ...ref(item.id),\n stage: workItemStage(item),\n })),\n needsRepository: needsRepository.slice(0, limit).map(item => ({\n ...ref(item.id),\n stage: workItemStage(item),\n })),\n ...(needsRepository.length > 0 ? { linkedRepositories: unplaced.candidates } : {}),\n truncated:\n allIncidents.length > limit ||\n incidents.some(group => group.shown.length < group.decisions.length) ||\n proposals.length > limit ||\n waiting.length > limit ||\n held.length > limit ||\n needsRepository.length > limit,\n };\n },\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAoCA,MAAa,WAAW;AACxB,MAAa,YAAY;AACzB,MAAa,WAAW;AACxB,MAAM,eAAe;AAyBrB,SAAgB,SAAS,MAAc,KAAqB;CAC1D,OAAO,KAAK,SAAS,MAAM,GAAG,KAAK,MAAM,GAAG,MAAM,CAAC,EAAE,KAAK;AAC5D;AAEA,SAAS,IAAI,OAAwD;CACnE,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,OAAO,iBAAiB,OAAO,QAAQ,IAAI,KAAK,KAAK;CAC3D,OAAO,OAAO,SAAS,KAAK,QAAQ,CAAC,IAAI,KAAK,YAAY,IAAI;AAChE;;AAGA,SAAgB,eAAe,MAA0D;CACvF,MAAM,SACJ,KAAK,SAAS,UAAU,UACxB,KAAK,SAAS,UAAU,qBACxB,KAAK,SAAS,UAAU,2BACxB,KAAK,WAAA;CACP,OAAO,OA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AI,SAAS;OACb,GAAG,IAAI,SAAS,UAAU;OAC1B,UAAU,SAAS;OACnB,UAAU,kBAAkB,UAAU,UAAU,IAAI,SAAS,EAAE,CAAC;MAClE,EAAE;KACJ,EAAE;KACF,WAAW,UACR,MAAM,GAAG,KAAK,CAAC,CACf,KAAI,cAAa;MAAE,GAAG,kBAAkB,QAAQ;MAAG,GAAG,IAAI,SAAS,UAAU;KAAE,EAAE;KACpF,SAAS,QAAQ,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK,EAAE,WAAW,WAAW;MAC5D;MACA,UAAU,IAAI;MACd,OAAO,eAAe,IAAI,QAAQ;MAClC,cAAc,IAAI,KAAK,IAAI,WAAW,CAAC,CAAC,YAAY;KACtD,EAAE;KACF,MAAM,KAAK,MAAM,GAAG,KAAK,CAAC,CAAC,KAAI,UAAS;MACtC,GAAG,IAAI,KAAK,EAAE;MACd,OAAO,cAAc,IAAI;KAC3B,EAAE;KACF,iBAAiB,gBAAgB,MAAM,GAAG,KAAK,CAAC,CAAC,KAAI,UAAS;MAC5D,GAAG,IAAI,KAAK,EAAE;MACd,OAAO,cAAc,IAAI;KAC3B,EAAE;KACF,GAAI,gBAAgB,SAAS,IAAI,EAAE,oBAAoB,SAAS,WAAW,IAAI,CAAC;KAChF,WACE,aAAa,SAAS,SACtB,UAAU,MAAK,UAAS,MAAM,MAAM,SAAS,MAAM,UAAU,MAAM,KACnE,UAAU,SAAS,SACnB,QAAQ,SAAS,SACjB,KAAK,SAAS,SACd,gBAAgB,SAAS;IAC7B;GACF;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"read-tools.js","names":[],"sources":["../../src/tools/read-tools.ts"],"sourcesContent":["import { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport {\n awaitsAcceptance,\n boardFlow,\n boardForWorkItem,\n isTerminalWorkItem,\n pullRequestSourceNumber,\n pullRequestSources,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { factorySessionUrl, factoryWorkItemUrl } from '../links.js';\nimport { parkedRunLabel } from '../routes/attention-parked.js';\nimport { decisionRetryable, overtakenDecisionIds } from '../rules/decision-applicability.js';\nimport { factoryDispatchFailureMetadata } from '../rules/dispatch-errors.js';\nimport { needsApproval } from '../rules/types.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport { resolveWorkItemRepository } from '../session/work-item-repository.js';\nimport type { AuditStorage } from '../storage/domains/audit/base.js';\nimport type {\n FactoryDeferredDecisionRecord,\n FactoryRunBindingRecord,\n Card,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport { workItemNumber } from '../work-items/card-number.js';\nimport { sessionActivity } from './deliver.js';\nimport type { FactorySessionActivity } from './deliver.js';\nimport type { FactoryMessaging } from './messaging-tools.js';\nimport type { FactoryToolScope } from './scope.js';\n\nexport const MAX_TEXT = 600;\nexport const MAX_ERROR = 400;\nexport const MAX_LIST = 50;\nconst DEFAULT_LIST = 25;\n\nexport interface FactoryReadToolDependencies {\n workItems: Pick<\n WorkItemsStorage,\n | 'listShared'\n | 'getForProject'\n | 'listRunBindings'\n | 'listDeferredDecisions'\n | 'listByIds'\n | 'listDecisionsForEvaluations'\n | 'listWorkItemSubscribers'\n | 'listSessionSubscriptions'\n >;\n audit: Pick<AuditStorage, 'list'>;\n /** A fixed registry, or the per-project boards. */\n boards: BoardRegistry | ProjectBoardSource;\n /** The live controller, for whether a session is mid-run and when it last moved; absent before the mount is up. */\n messaging?: () => Promise<Pick<FactoryMessaging, 'controller'> | null>;\n /** Finds the caller session's source-control provider, to tell which cards can't pick a repository. */\n sessions?: Pick<SourceControlSessionLookup, 'getSourceControlBySessionId'>;\n /** Which live sessions are parked on a tool prompt; absent before the mount is up. */\n liveSessions?: () => Pick<LiveSessions, 'parked' | 'parkedIn'> | undefined;\n}\n\nexport function truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n\nfunction iso(value: Date | string | null | undefined): string | null {\n if (!value) return null;\n const date = value instanceof Date ? value : new Date(value);\n return Number.isFinite(date.getTime()) ? date.toISOString() : null;\n}\n\nexport function workItemStage(item: Pick<Card, 'stages'>): string {\n return item.stages.join('+');\n}\n\n/** A work item id or its card number; anything else can't name an item. */\nexport const workItemRefSchema = z\n .string()\n .trim()\n .max(64)\n .refine(ref => z.string().uuid().safeParse(ref).success || /^#?\\d+$/.test(ref), {\n message: 'Use a work item id (UUID) or its number like \"#123\".',\n })\n .describe('Work item id, or its number like \"#123\".');\n\n/** Resolve `<uuid>` or `#123` to an item in this Factory only. Pass a ref validated by `workItemRefSchema`. */\nexport async function findWorkItem(\n workItems: Pick<WorkItemsStorage, 'listShared' | 'getForProject'>,\n scope: Pick<FactoryToolScope, 'orgId' | 'factoryProjectId'>,\n ref: string,\n): Promise<Card | null> {\n const trimmed = ref.trim();\n const number = /^#?(\\d+)$/.exec(trimmed)?.[1];\n if (number === undefined) return workItems.getForProject(scope.orgId, scope.factoryProjectId, trimmed);\n const items = await workItems.listShared(scope);\n const matches = items.filter(item => workItemNumber(item) === Number(number));\n // Issue and PR numbers share a space on GitHub; prefer the issue's card.\n const workCards = matches.filter(item => item.externalSource?.type !== 'pull-request');\n // Hand-filed card numbers and issue numbers from several repositories can repeat; refuse to guess.\n refuseAmbiguous(number, workCards);\n const match = workCards[0] ?? matches[0];\n if (match) return structuredClone(match);\n // A pull request attached to an issue's card is found through that card. Pull request numbers\n // repeat across repositories too.\n const carriers = items.filter(item =>\n pullRequestSources(item).some(source => pullRequestSourceNumber(source) === Number(number)),\n );\n refuseAmbiguous(number, carriers);\n return carriers[0] ? structuredClone(carriers[0]) : null;\n}\n\nfunction refuseAmbiguous(number: string, items: readonly Card[]): void {\n if (items.length <= 1) return;\n const candidates = items.map(item => `${item.id} (${item.title})`).join(', ');\n throw new Error(`#${number} matches more than one work item; use its id instead: ${candidates}.`);\n}\n\nexport function workItemNotFound(ref: string): Error {\n return new Error(`No work item ${ref} was found in this Factory.`);\n}\n\nfunction activeWorker(bindings: FactoryRunBindingRecord[], itemId: string) {\n const binding = bindings.find(candidate => candidate.workItemId === itemId && candidate.status === 'active');\n return binding ? { role: binding.role, sessionId: binding.sessionId } : null;\n}\n\n/** The card on its Factory board; null when the server has no public URL configured. */\nfunction workItemUrl(item: Card) {\n return (\n factoryWorkItemUrl({\n factoryProjectId: item.factoryProjectId,\n board: boardForWorkItem(item),\n workItemId: item.id,\n }) ?? null\n );\n}\n\nfunction summarizeItem(item: Card, bindings: FactoryRunBindingRecord[]) {\n return {\n id: item.id,\n number: workItemNumber(item),\n title: truncate(item.title, MAX_TEXT),\n board: boardForWorkItem(item),\n stage: workItemStage(item),\n url: workItemUrl(item),\n activeWorker: activeWorker(bindings, item.id),\n requestedBy: item.createdBy,\n updatedAt: iso(item.updatedAt),\n };\n}\n\nfunction summarizeDecision(decision: FactoryDeferredDecisionRecord, overtaken = false) {\n const type = typeof decision.decision.type === 'string' ? decision.decision.type : 'decision';\n const role = typeof decision.decision.role === 'string' ? decision.decision.role : null;\n return {\n id: decision.id,\n workItemId: decision.workItemId,\n type,\n role,\n status: decision.status,\n attempts: decision.attempts,\n failureCode: decision.failureCode,\n failureLabel: decision.failureCode ? factoryDispatchFailureMetadata(decision.failureCode).label : null,\n canRetry: decisionRetryable(decision, overtaken),\n error: decision.lastError ? truncate(decision.lastError, MAX_ERROR) : null,\n approvedBy: decision.approvedBy,\n updatedAt: iso(decision.updatedAt),\n };\n}\n\n/**\n * Held: a card triage left resting (or whose source asks for approval), until a person moves it\n * on. A card that has been past triage since (parked by self-review, or dragged back) resumes\n * instead, matching the board's held state.\n */\nfunction isHeld(boards: BoardRegistry, item: Card): boolean {\n const board = boards.get(boardForWorkItem(item));\n const stage = item.stages.length === 1 ? item.stages[0]! : undefined;\n if (!board || !stage || board.phaseKind(stage) !== 'resting') return false;\n if (needsApproval(item, phase => awaitsAcceptance(board, phase))) return true;\n const triage = boardFlow(board).triage;\n const triageRole = triage ? board.roleForPhase(triage) : undefined;\n if (!triageRole || item.sessions[triageRole] === undefined) return false;\n return !item.stageHistory.some(entry => entry.stage !== triage && board.isWorking(entry.stage));\n}\n\nconst listInputSchema = z\n .object({\n query: z\n .string()\n .trim()\n .min(1)\n .max(200)\n .optional()\n .describe('Case-insensitive text in the title, or an exact card number like \"#123\".'),\n stage: z.string().min(1).max(64).optional().describe('Only items in this stage, e.g. \"triage\" or \"review\".'),\n board: z.string().min(1).max(64).optional().describe('Only items on this board, e.g. \"work\" or \"review\".'),\n role: z.string().min(1).max(64).optional().describe('Only items that have a session for this role.'),\n active: z.boolean().optional().describe('true: only items with an agent working now; false: only idle items.'),\n requestedBy: z.literal('me').optional().describe('\"me\": only items you filed.'),\n subscribed: z\n .boolean()\n .optional()\n .describe('true: only items this session follows; false: only items it does not.'),\n limit: z.number().int().min(1).max(MAX_LIST).optional().describe(`Default ${DEFAULT_LIST}, max ${MAX_LIST}.`),\n })\n .strict();\n\nexport function createFactoryReadTools(scope: FactoryToolScope, deps: FactoryReadToolDependencies): IntegrationTools {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n /**\n * Of `cards` filed by hand, those that name no repository while the Factory\n * links several, so a run on them refuses to start until someone picks one.\n */\n const cardsWithoutRepository = async (cards: Card[]): Promise<{ items: Card[]; candidates: string[] }> => {\n const unnamed = cards.filter(card => typeof card.metadata?.repository !== 'string');\n if (unnamed.length === 0 || !deps.sessions) return { items: [], candidates: [] };\n const sourceControl = await deps.sessions.getSourceControlBySessionId(scope.sessionId);\n if (!sourceControl) return { items: [], candidates: [] };\n // A card filed by hand has no source repository, so one that names none resolves like an empty card.\n const resolution = await resolveWorkItemRepository({\n sourceControl,\n ...project,\n item: { metadata: null, workItem: { metadata: null } },\n });\n return resolution.status === 'ambiguous'\n ? { items: unnamed, candidates: resolution.candidates }\n : { items: [], candidates: [] };\n };\n\n return {\n factory_list_work_items: createTool({\n id: 'factory_list_work_items',\n description:\n \"List this Factory's work items, newest activity first, with counts per stage for the whole Factory. Filter by text or #number, stage, board, role, whether an agent is working on it, items you filed, or items this session follows. Check here for an existing item before filing a new one.\",\n inputSchema: listInputSchema,\n execute: async input => {\n const [items, bindings, followed] = await Promise.all([\n deps.workItems.listShared(project),\n deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId),\n input.subscribed === undefined\n ? undefined\n : deps.workItems.listSessionSubscriptions({ ...project, sessionId: scope.sessionId }),\n ]);\n const followedIds = new Set(followed?.map(subscription => subscription.workItemId));\n const byStage: Record<string, number> = {};\n for (const item of items) {\n const stage = workItemStage(item);\n byStage[stage] = (byStage[stage] ?? 0) + 1;\n }\n const numberQuery = input.query ? /^#(\\d+)$/.exec(input.query)?.[1] : undefined;\n const text = input.query?.toLowerCase();\n const matches = items\n .filter(item => {\n if (numberQuery !== undefined) {\n if (workItemNumber(item) !== Number(numberQuery)) return false;\n } else if (text && !item.title.toLowerCase().includes(text)) return false;\n if (input.stage && !item.stages.includes(input.stage)) return false;\n if (input.board && boardForWorkItem(item) !== input.board) return false;\n if (input.role && !item.sessions[input.role]) return false;\n if (input.active !== undefined && (activeWorker(bindings, item.id) !== null) !== input.active) return false;\n if (input.requestedBy === 'me' && item.createdBy !== scope.userId) return false;\n if (input.subscribed !== undefined && followedIds.has(item.id) !== input.subscribed) return false;\n return true;\n })\n .sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime());\n const limit = input.limit ?? DEFAULT_LIST;\n return {\n counts: { total: items.length, byStage },\n items: matches.slice(0, limit).map(item => summarizeItem(item, bindings)),\n truncated: matches.length > limit,\n };\n },\n }),\n\n factory_inspect_work_item: createTool({\n id: 'factory_inspect_work_item',\n description:\n 'Everything the Factory knows about one work item: its description, stage history, sessions by role (with whether each is mid-run and when its thread last moved), decisions with errors, recent audit events, labels, linked items and the sessions following it. Use it to explain why an item is where it is.',\n inputSchema: z.object({ workItem: workItemRefSchema }).strict(),\n execute: async ({ workItem }) => {\n const item = await findWorkItem(deps.workItems, scope, workItem);\n if (!item) throw workItemNotFound(workItem);\n const [bindings, decisions, audit, all, subscribers] = await Promise.all([\n deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId, item.id),\n deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId, { workItemId: item.id }),\n deps.audit.list({ ...project, limit: 200 }),\n deps.workItems.listShared(project),\n deps.workItems.listWorkItemSubscribers({ orgId: scope.orgId, workItemId: item.id }),\n ]);\n const itemDecisions = decisions.slice(-MAX_LIST);\n const overtaken = await overtakenDecisionIds(\n deps.workItems,\n await toBoardSource(deps.boards).load(project),\n project,\n itemDecisions.filter(decision => decision.status === 'failed'),\n );\n const labels = Array.isArray(item.workItem.labels)\n ? item.workItem.labels.filter((label): label is string => typeof label === 'string').slice(0, MAX_LIST)\n : [];\n const parent = item.parentWorkItemId\n ? all.find(candidate => candidate.id === item.parentWorkItemId)\n : undefined;\n const children = all.filter(candidate => candidate.parentWorkItemId === item.id);\n const controller = (await deps.messaging?.())?.controller;\n const activity = async (sessionId: string, threadId: string): Promise<FactorySessionActivity | null> =>\n controller ? sessionActivity(controller, sessionId, threadId) : null;\n const sessions = await Promise.all(\n Object.entries(item.sessions).map(async ([role, ref]) => ({\n role,\n sessionId: ref.sessionId,\n threadId: ref.threadId,\n url:\n factorySessionUrl({\n factoryProjectId: item.factoryProjectId,\n sessionId: ref.sessionId,\n threadId: ref.threadId,\n }) ?? null,\n startedBy: ref.startedBy,\n active: bindings.some(\n binding => binding.role === role && binding.sessionId === ref.sessionId && binding.status === 'active',\n ),\n // `running` with an old `lastActivityAt` is a stuck run; `running` with a recent one is a long one.\n ...((await activity(ref.sessionId, ref.threadId)) ?? { running: null, lastActivityAt: null }),\n })),\n );\n return {\n item: {\n ...summarizeItem(item, bindings),\n description: item.description,\n source: item.externalSource ? `${item.externalSource.integrationId}:${item.externalSource.type}` : 'manual',\n sourceUrl: typeof item.workItem.url === 'string' ? item.workItem.url : null,\n revision: item.revision,\n },\n labels,\n stageHistory: item.stageHistory.slice(-MAX_LIST).map(entry => ({\n stage: entry.stage,\n enteredAt: entry.enteredAt,\n exitedAt: entry.exitedAt ?? null,\n by: entry.by,\n })),\n sessions,\n decisions: itemDecisions.map(decision => summarizeDecision(decision, overtaken.has(decision.id))),\n audit: audit.events\n .filter(event => event.targets.some(target => target.type === 'work_item' && target.id === item.id))\n .slice(0, 25)\n .map(event => ({\n action: event.action,\n actorId: event.actorId,\n actorType: event.actorType,\n occurredAt: iso(event.occurredAt),\n })),\n parent: parent ? summarizeItem(parent, bindings) : null,\n children: children.slice(0, MAX_LIST).map(child => summarizeItem(child, bindings)),\n subscribers: subscribers.slice(0, MAX_LIST).map(subscription => ({\n sessionId: subscription.sessionId,\n reason: subscription.reason,\n isCaller: subscription.sessionId === scope.sessionId,\n })),\n };\n },\n }),\n\n factory_list_attention: createTool({\n id: 'factory_list_attention',\n description:\n 'What in this Factory needs a person: failed decisions grouped by failure code and error (one incident per group), proposals waiting for approval, runs parked on a tool prompt (a plan to review, a question to answer) while still in flight, Work cards triage left in Intake for a person to move on, and open cards filed by hand that need a repository set (factory_update_work_item) before a run can start.',\n inputSchema: z.object({ limit: z.number().int().min(1).max(MAX_LIST).optional() }).strict(),\n execute: async ({ limit = DEFAULT_LIST }) => {\n const [decisions, items] = await Promise.all([\n deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId, {\n statuses: ['failed', 'proposed'],\n }),\n deps.workItems.listShared(project),\n ]);\n const itemsById = new Map(items.map(item => [item.id, item]));\n const failed = decisions.filter(decision => decision.status === 'failed');\n const groups = new Map<\n string,\n { failureCode: string; error: string; decisions: FactoryDeferredDecisionRecord[] }\n >();\n for (const decision of failed) {\n const error = truncate(decision.lastError ?? '', MAX_ERROR);\n const key = `${decision.failureCode ?? 'unknown'}|${error}`;\n const group = groups.get(key) ?? { failureCode: decision.failureCode ?? 'unknown', error, decisions: [] };\n group.decisions.push(decision);\n groups.set(key, group);\n }\n const ref = (workItemId: string | null) => {\n const item = workItemId ? itemsById.get(workItemId) : undefined;\n return {\n workItemId,\n number: item ? workItemNumber(item) : null,\n title: item ? truncate(item.title, MAX_TEXT) : null,\n url: item ? workItemUrl(item) : null,\n };\n };\n const allIncidents = [...groups.values()].sort((a, b) => b.decisions.length - a.decisions.length);\n const incidents = allIncidents\n .slice(0, limit)\n .map(group => ({ ...group, shown: group.decisions.slice(0, limit) }));\n // Check exactly the decisions this call returns, so every canRetry is real.\n const boards = await toBoardSource(deps.boards).load(project);\n const overtaken = await overtakenDecisionIds(\n deps.workItems,\n boards,\n project,\n incidents.flatMap(group => group.shown),\n );\n const proposals = decisions.filter(decision => decision.status === 'proposed');\n const held = items.filter(item => isHeld(boards, item));\n const unplaced = await cardsWithoutRepository(\n items.filter(item => !item.externalSource && !isTerminalWorkItem(boards, item)),\n );\n const needsRepository = unplaced.items;\n const waiting = (deps.liveSessions?.()?.parkedIn(scope.factoryProjectId) ?? []).sort(\n (a, b) => a.run.suspendedAt - b.run.suspendedAt,\n );\n return {\n incidents: incidents.map(group => ({\n failureCode: group.failureCode,\n failureLabel: factoryDispatchFailureMetadata(group.decisions[0]!.failureCode).label,\n error: group.error,\n count: group.decisions.length,\n decisions: group.shown.map(decision => ({\n id: decision.id,\n ...ref(decision.workItemId),\n attempts: decision.attempts,\n canRetry: decisionRetryable(decision, overtaken.has(decision.id)),\n })),\n })),\n proposals: proposals\n .slice(0, limit)\n .map(decision => ({ ...summarizeDecision(decision), ...ref(decision.workItemId) })),\n waiting: waiting.slice(0, limit).map(({ sessionId, run }) => ({\n sessionId,\n toolName: run.toolName,\n label: parkedRunLabel(run.toolName),\n waitingSince: new Date(run.suspendedAt).toISOString(),\n })),\n held: held.slice(0, limit).map(item => ({\n ...ref(item.id),\n stage: workItemStage(item),\n })),\n needsRepository: needsRepository.slice(0, limit).map(item => ({\n ...ref(item.id),\n stage: workItemStage(item),\n })),\n ...(needsRepository.length > 0 ? { linkedRepositories: unplaced.candidates } : {}),\n truncated:\n allIncidents.length > limit ||\n incidents.some(group => group.shown.length < group.decisions.length) ||\n proposals.length > limit ||\n waiting.length > limit ||\n held.length > limit ||\n needsRepository.length > limit,\n };\n },\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAoCA,MAAa,WAAW;AACxB,MAAa,YAAY;AACzB,MAAa,WAAW;AACxB,MAAM,eAAe;AAyBrB,SAAgB,SAAS,MAAc,KAAqB;CAC1D,OAAO,KAAK,SAAS,MAAM,GAAG,KAAK,MAAM,GAAG,MAAM,CAAC,EAAE,KAAK;AAC5D;AAEA,SAAS,IAAI,OAAwD;CACnE,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,OAAO,iBAAiB,OAAO,QAAQ,IAAI,KAAK,KAAK;CAC3D,OAAO,OAAO,SAAS,KAAK,QAAQ,CAAC,IAAI,KAAK,YAAY,IAAI;AAChE;AAEA,SAAgB,cAAc,MAAoC;CAChE,OAAO,KAAK,OAAO,KAAK,GAAG;AAC7B;;AAGA,MAAa,oBAAoB,EAC9B,OAAO,CAAC,CACR,KAAK,CAAC,CACN,IAAI,EAAE,CAAC,CACP,QAAO,QAAO,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,UAAU,GAAG,CAAC,CAAC,WAAW,UAAU,KAAK,GAAG,GAAG,EAC9E,SAAS,yDACX,CAAC,CAAC,CACD,SAAS,4CAA0C;;AAGtD,eAAsB,aACpB,WACA,OACA,KACsB;CACtB,MAAM,UAAU,IAAI,KAAK;CACzB,MAAM,SAAS,YAAY,KAAK,OAAO,CAAC,GAAG;CAC3C,IAAI,WAAW,KAAA,GAAW,OAAO,UAAU,cAAc,MAAM,OAAO,MAAM,kBAAkB,OAAO;CACrG,MAAM,QAAQ,MAAM,UAAU,WAAW,KAAK;CAC9C,MAAM,UAAU,MAAM,QAAO,SAAQ,eAAe,IAAI,MAAM,OAAO,MAAM,CAA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AAG,IAAI,KAAK,EAAE;MACd,OAAO,cAAc,IAAI;KAC3B,EAAE;KACF,GAAI,gBAAgB,SAAS,IAAI,EAAE,oBAAoB,SAAS,WAAW,IAAI,CAAC;KAChF,WACE,aAAa,SAAS,SACtB,UAAU,MAAK,UAAS,MAAM,MAAM,SAAS,MAAM,UAAU,MAAM,KACnE,UAAU,SAAS,SACnB,QAAQ,SAAS,SACjB,KAAK,SAAS,SACd,gBAAgB,SAAS;IAC7B;GACF;EACF,CAAC;CACH;AACF"}
@@ -85,7 +85,10 @@ export type FactoryRunOutcome = {
85
85
  status: 'blocked';
86
86
  toolName?: string;
87
87
  toolCallId?: string;
88
+ /** The call waits for a person to allow it. */
88
89
  approval?: boolean;
90
+ /** The tool paused itself, and a yes or no from a follower is all it needs. */
91
+ decision?: boolean;
89
92
  };
90
93
  /** `waiting`: the session is waiting for an answer, so a later run owes the final report. */
91
94
  export interface FactoryRunEndResult {
@@ -1 +1 @@
1
- {"version":3,"file":"reports.d.ts","sourceRoot":"","sources":["../../src/tools/reports.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EACV,oBAAoB,EACpB,oBAAoB,EACpB,2BAA2B,EAC5B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,OAAO,KAAK,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAGjF,MAAM,MAAM,mBAAmB,GAAG,UAAU,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,CAAC;AAE7E,4GAA4G;AAC5G,eAAO,MAAM,oBAAoB,EAAE,MAAM,CACvC,mBAAmB,GAAG,QAAQ,EAC9B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,oBAAoB,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAA;CA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 -1,5 +1,5 @@
1
+ import { workItemNumber } from "../work-items/card-number.js";
1
2
  import { FACTORY_SESSION_NOTIFICATION_SOURCE } from "./deliver.js";
2
- import { workItemNumber } from "./read-tools.js";
3
3
  // src/tools/reports.ts
4
4
  /** How each report status travels. Final reports never coalesce, so a later report can't overwrite them. */
5
5
  const FACTORY_REPORT_FORMS = {
@@ -155,7 +155,7 @@ async function workItemReportAttributes(workItems, { orgId, factoryProjectId, wo
155
155
  */
156
156
  async function sendRunEndReport(reporting, { sender, recipients, since, outcome, subject, attributes = {} }) {
157
157
  const kinds = outcome.status === "blocked" ? ["blocked"] : ["done", "failed"];
158
- const message = outcome.status === "done" ? `${subject} finished.` : outcome.status === "failed" ? `${subject} failed${outcome.failureCode ? ` (${outcome.failureCode})` : ""}: ${outcome.reason}` : outcome.approval ? `${subject} is waiting for someone to approve ${outcome.toolName ?? "a tool call"} in that session.` : `${subject} is waiting${outcome.toolName ? ` on ${outcome.toolName}` : ""} and needs an answer.${outcome.toolName === "submit_plan" && outcome.toolCallId ? ` Answer it with factory_answer_approval (toolCallId ${outcome.toolCallId}).` : ""}`;
158
+ const message = outcome.status === "done" ? `${subject} finished.` : outcome.status === "failed" ? `${subject} failed${outcome.failureCode ? ` (${outcome.failureCode})` : ""}: ${outcome.reason}` : outcome.approval ? `${subject} is waiting for someone to approve ${outcome.toolName ?? "a tool call"} in that session.` : `${subject} is waiting${outcome.toolName ? ` on ${outcome.toolName}` : ""} and needs an answer.${outcome.decision && outcome.toolCallId ? ` Approve or decline it with factory_answer_approval (sessionId "${sender.sessionId}", toolCallId "${outcome.toolCallId}").` : ""}`;
159
159
  const notification = reportNotification({
160
160
  sender,
161
161
  status: outcome.status,
@@ -166,7 +166,7 @@ async function sendRunEndReport(reporting, { sender, recipients, since, outcome,
166
166
  ...outcome.status === "failed" && outcome.failureCode ? { "failure-code": outcome.failureCode } : {},
167
167
  ...outcome.status === "blocked" && outcome.toolName ? { "parked-tool": outcome.toolName } : {},
168
168
  ...outcome.status === "blocked" && outcome.toolCallId ? { "tool-call-id": outcome.toolCallId } : {},
169
- ...outcome.status === "blocked" && outcome.approval ? { "waiting-for": "approval" } : {}
169
+ ...outcome.status === "blocked" && (outcome.approval || outcome.decision) ? { "waiting-for": "approval" } : {}
170
170
  }
171
171
  });
172
172
  const report = (recipient, reportKinds, agentOnly = false) => hasFinalReport(reporting.notifications, {
@@ -1 +1 @@
1
- {"version":3,"file":"reports.js","names":[],"sources":["../../src/tools/reports.ts"],"sourcesContent":["/**\n * Reports from sessions doing the work back to whoever follows it: a side\n * session's origin, or every subscriber of a work item. The agent reports with\n * `factory_message_origin`; when a run ends without one, the run-end backstop\n * sends it, so each run produces exactly one final report per recipient.\n */\n\nimport type {\n NotificationPriority,\n NotificationsStorage,\n SendNotificationSignalInput,\n} from '@mastra/core/notifications';\n\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { FACTORY_SESSION_NOTIFICATION_SOURCE } from './deliver.js';\nimport type { FactoryDeliveryResult, FactoryDeliveryTarget } from './deliver.js';\nimport { workItemNumber } from './read-tools.js';\n\nexport type FactoryReportStatus = 'progress' | 'blocked' | 'done' | 'failed';\n\n/** How each report status travels. Final reports never coalesce, so a later report can't overwrite them. */\nexport const FACTORY_REPORT_FORMS: Record<\n FactoryReportStatus | 'report',\n { kind: string; priority: NotificationPriority; coalesce: boolean }\n> = {\n failed: { kind: 'failed', priority: 'urgent', coalesce: false },\n blocked: { kind: 'blocked', priority: 'urgent', coalesce: false },\n done: { kind: 'done', priority: 'high', coalesce: false },\n progress: { kind: 'progress', priority: 'low', coalesce: true },\n // Not `message`: only messages can be answered, so a report can't start a reply loop.\n report: { kind: 'report', priority: 'high', coalesce: false },\n};\n\n/** How many recent `factory-session` notifications on a recipient thread the final-report check reads. */\nconst FINAL_REPORT_SCAN = 100;\n\nexport interface FactoryReportSender {\n sessionId: string;\n threadId: string;\n userId: string;\n}\n\nexport type FactoryReportDeliver = (\n target: FactoryDeliveryTarget,\n notification: Omit<SendNotificationSignalInput, 'source'>,\n options?: { onlyIfLive?: boolean },\n) => Promise<FactoryDeliveryResult>;\n\nexport interface FactoryReporting {\n deliver: FactoryReportDeliver;\n notifications: Pick<NotificationsStorage, 'listNotifications'>;\n}\n\n/**\n * Whether `senderSessionId` already put a report of one of `kinds` on the\n * recipient thread since `since`. Reads the durable notifications store, so it\n * holds across restarts. `listNotifications` has no time filter: records come\n * newest-updated first, and the scan stops at the first one last updated\n * before `since` (nothing after it can have been created later).\n */\nexport async function hasFinalReport(\n notifications: FactoryReporting['notifications'],\n {\n senderSessionId,\n recipientThreadId,\n since,\n kinds,\n agentOnly = false,\n }: {\n senderSessionId: string;\n recipientThreadId: string;\n since: Date;\n kinds: readonly string[];\n /** Ignore reports Factory sent on the session's behalf (the backstop). */\n agentOnly?: boolean;\n },\n): Promise<boolean> {\n const records = await notifications.listNotifications({\n threadId: recipientThreadId,\n source: FACTORY_SESSION_NOTIFICATION_SOURCE,\n limit: FINAL_REPORT_SCAN,\n });\n for (const record of records) {\n if (record.updatedAt < since) break;\n if (\n record.attributes?.['from-session'] === senderSessionId &&\n !(agentOnly && record.attributes?.backstop === 'true') &&\n // A reply carrying a final status counts like the report itself.\n (kinds.includes(record.kind) ||\n (record.kind === 'reply' &&\n typeof record.attributes?.status === 'string' &&\n kinds.includes(record.attributes.status))) &&\n record.createdAt >= since\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** The newest report `senderSessionId` put on the recipient thread. */\nasync function lastReport(\n notifications: FactoryReporting['notifications'],\n { senderSessionId, recipientThreadId }: { senderSessionId: string; recipientThreadId: string },\n) {\n const records = await notifications.listNotifications({\n threadId: recipientThreadId,\n source: FACTORY_SESSION_NOTIFICATION_SOURCE,\n limit: FINAL_REPORT_SCAN,\n });\n return records\n .filter(record => record.attributes?.['from-session'] === senderSessionId)\n .reduce<(typeof records)[number] | undefined>(\n (newest, record) => (!newest || reportedAt(record) > reportedAt(newest) ? record : newest),\n undefined,\n );\n}\n\n/**\n * When a report last said something. `updatedAt` also moves when a report is\n * read, so it only counts once a later report has coalesced into this one;\n * otherwise the report says what it said when it was created.\n */\nfunction reportedAt(record: { createdAt: Date; updatedAt: Date; coalescedCount?: number }): Date {\n return (record.coalescedCount ?? 1) > 1 ? record.updatedAt : record.createdAt;\n}\n\n/**\n * Whether the newest report `senderSessionId` put on the recipient thread is\n * already this exact `failed` backstop. A session stuck failing the same way\n * (a run that dies before the model, restarted over and over) then reports\n * once, not once per attempt; any other report in between resets it.\n */\nexport async function repeatsLastFailure(\n notifications: FactoryReporting['notifications'],\n {\n senderSessionId,\n recipientThreadId,\n summary,\n }: { senderSessionId: string; recipientThreadId: string; summary: string },\n): Promise<boolean> {\n const last = await lastReport(notifications, { senderSessionId, recipientThreadId });\n return last?.kind === 'failed' && last.attributes?.backstop === 'true' && last.summary === summary;\n}\n\n/**\n * Whether the newest report `senderSessionId` put on the recipient thread\n * already says it is done. A session woken again after it finished (a PR it\n * subscribed to gets comments, reviews and CI results) ends each of those runs\n * with nothing new to say, so the follower hears \"finished\" once, not per wake.\n */\nasync function alreadyReportedDone(\n notifications: FactoryReporting['notifications'],\n target: { senderSessionId: string; recipientThreadId: string },\n): Promise<boolean> {\n const last = await lastReport(notifications, target);\n return last?.kind === 'done' || (last?.kind === 'reply' && last.attributes?.status === 'done');\n}\n\nexport function reportNotification({\n sender,\n status,\n message,\n attributes = {},\n}: {\n sender: FactoryReportSender;\n status?: FactoryReportStatus;\n message: string;\n attributes?: Record<string, string>;\n}): Omit<SendNotificationSignalInput, 'source'> {\n const form = FACTORY_REPORT_FORMS[status ?? 'report'];\n return {\n kind: form.kind,\n priority: form.priority,\n // The whole text: a notification's summary is all the recipient's agent ever sees, even\n // through notification_inbox (which hides payloads), so a cut-off report loses its verdict.\n summary: message,\n payload: { message },\n sourceId: sender.sessionId,\n ...(form.coalesce ? { coalesceKey: `factory-session:${sender.sessionId}:${form.kind}` } : {}),\n attributes: {\n ...attributes,\n ...(status ? { status } : {}),\n // Last, so nothing above can claim another sender.\n 'from-session': sender.sessionId,\n 'from-thread': sender.threadId,\n 'from-user': sender.userId,\n },\n };\n}\n\n/** Everyone following a work item, except the session doing the reporting. */\nexport async function workItemReportRecipients(\n workItems: Pick<WorkItemsStorage, 'listWorkItemSubscribers'>,\n { orgId, workItemId, senderSessionId }: { orgId: string; workItemId: string; senderSessionId: string },\n): Promise<FactoryDeliveryTarget[]> {\n const subscribers = await workItems.listWorkItemSubscribers({ orgId, workItemId });\n return subscribers\n .filter(subscriber => subscriber.sessionId !== senderSessionId)\n .map(subscriber => ({ sessionId: subscriber.sessionId, threadId: subscriber.threadId }));\n}\n\n/** How reports name an item: `#n`, else its quoted title, else its id. */\nasync function workItemReference(\n workItems: Pick<WorkItemsStorage, 'getForProject'>,\n { orgId, factoryProjectId, workItemId }: { orgId: string; factoryProjectId: string; workItemId: string },\n): Promise<{ label: string; ref: string }> {\n const item = await workItems.getForProject(orgId, factoryProjectId, workItemId);\n const number = item ? workItemNumber(item) : null;\n if (number !== null) return { label: `#${number}`, ref: `#${number}` };\n return { label: item ? `\"${item.title}\"` : workItemId, ref: workItemId };\n}\n\n/** Attributes that say which item and role a worker's report is about. */\nexport async function workItemReportAttributes(\n workItems: Pick<WorkItemsStorage, 'getForProject'>,\n {\n orgId,\n factoryProjectId,\n workItemId,\n role,\n }: { orgId: string; factoryProjectId: string; workItemId: string; role: string },\n): Promise<{ label: string; attributes: Record<string, string> }> {\n const { label, ref } = await workItemReference(workItems, { orgId, factoryProjectId, workItemId });\n return { label, attributes: { 'work-item': ref, role } };\n}\n\nexport type FactoryRunOutcome =\n | { status: 'done' }\n | { status: 'failed'; reason: string; failureCode?: string }\n | { status: 'blocked'; toolName?: string; toolCallId?: string; approval?: boolean };\n\n/** `waiting`: the session is waiting for an answer, so a later run owes the final report. */\nexport interface FactoryRunEndResult {\n waiting: boolean;\n deliveries?: FactoryDeliveryResult[];\n}\n\n/**\n * The run-end backstop: send `outcome` to each recipient that hasn't had a\n * final report from this sender since the run started. An agent's own `done`\n * or `failed` report wins. A run that completes after the agent's own\n * `blocked` sends nothing: the agent ended its turn to wait for an answer, and\n * its `done` comes from a later run. A `failed` backstop still goes out after an\n * earlier `blocked`.\n */\nexport async function sendRunEndReport(\n reporting: FactoryReporting,\n {\n sender,\n recipients,\n since,\n outcome,\n subject,\n attributes = {},\n }: {\n sender: FactoryReportSender;\n recipients: FactoryDeliveryTarget[];\n since: Date;\n outcome: FactoryRunOutcome;\n /** Who finished, e.g. \"The work session for #12\". */\n subject: string;\n attributes?: Record<string, string>;\n },\n): Promise<FactoryRunEndResult> {\n const kinds = outcome.status === 'blocked' ? ['blocked'] : ['done', 'failed'];\n const message =\n outcome.status === 'done'\n ? `${subject} finished.`\n : outcome.status === 'failed'\n ? `${subject} failed${outcome.failureCode ? ` (${outcome.failureCode})` : ''}: ${outcome.reason}`\n : outcome.approval\n ? `${subject} is waiting for someone to approve ${outcome.toolName ?? 'a tool call'} in that session.`\n : `${subject} is waiting${outcome.toolName ? ` on ${outcome.toolName}` : ''} and needs an answer.${\n outcome.toolName === 'submit_plan' && outcome.toolCallId\n ? ` Answer it with factory_answer_approval (toolCallId ${outcome.toolCallId}).`\n : ''\n }`;\n const notification = reportNotification({\n sender,\n status: outcome.status,\n message,\n attributes: {\n ...attributes,\n backstop: 'true',\n ...(outcome.status === 'failed' && outcome.failureCode ? { 'failure-code': outcome.failureCode } : {}),\n ...(outcome.status === 'blocked' && outcome.toolName ? { 'parked-tool': outcome.toolName } : {}),\n ...(outcome.status === 'blocked' && outcome.toolCallId ? { 'tool-call-id': outcome.toolCallId } : {}),\n ...(outcome.status === 'blocked' && outcome.approval ? { 'waiting-for': 'approval' } : {}),\n },\n });\n const report = (recipient: FactoryDeliveryTarget, reportKinds: string[], agentOnly = false) =>\n hasFinalReport(reporting.notifications, {\n senderSessionId: sender.sessionId,\n recipientThreadId: recipient.threadId,\n since,\n kinds: reportKinds,\n agentOnly,\n });\n let waiting = outcome.status === 'blocked';\n const deliveries: FactoryDeliveryResult[] = [];\n for (const recipient of recipients) {\n // Only the agent's own reports count: an earlier run's backstop lands after this\n // run's window opened. A reply already told that follower how a finished run went.\n if (await report(recipient, outcome.status === 'done' ? [...kinds, 'reply'] : kinds, true)) continue;\n // Only the agent's own `blocked` means it ended its turn to wait; a backstop `blocked` from a parked run doesn't.\n if (outcome.status === 'done' && (await report(recipient, ['blocked'], true))) {\n waiting = true;\n continue;\n }\n if (\n outcome.status === 'done' &&\n (await alreadyReportedDone(reporting.notifications, {\n senderSessionId: sender.sessionId,\n recipientThreadId: recipient.threadId,\n }))\n ) {\n continue;\n }\n if (\n outcome.status === 'failed' &&\n (await repeatsLastFailure(reporting.notifications, {\n senderSessionId: sender.sessionId,\n recipientThreadId: recipient.threadId,\n summary: message,\n }))\n ) {\n continue;\n }\n deliveries.push(await reporting.deliver(recipient, notification));\n }\n return { waiting, deliveries };\n}\n\nexport interface FactoryRunEndInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n role: string;\n sender: FactoryReportSender;\n since: Date;\n outcome: FactoryRunOutcome;\n}\n\nexport type FactoryRunEndReporter = (input: FactoryRunEndInput) => Promise<FactoryRunEndResult>;\n\n/** The backstop for a work-item run: reports to the item's subscribers. Failures are logged, never thrown. */\nexport function createWorkItemRunEndReporter({\n workItems,\n reporting,\n}: {\n workItems: Pick<WorkItemsStorage, 'listWorkItemSubscribers' | 'getForProject'>;\n /** Resolved per report: the controller exists only once the mount is up. */\n reporting: () => Promise<FactoryReporting | null>;\n}): FactoryRunEndReporter {\n return async input => {\n try {\n const resolved = await reporting();\n if (!resolved) return { waiting: false };\n const recipients = await workItemReportRecipients(workItems, {\n orgId: input.orgId,\n workItemId: input.workItemId,\n senderSessionId: input.sender.sessionId,\n });\n if (recipients.length === 0) return { waiting: false };\n const { label, attributes } = await workItemReportAttributes(workItems, input);\n return await sendRunEndReport(resolved, {\n sender: input.sender,\n recipients,\n since: input.since,\n outcome: input.outcome,\n subject: `The ${input.role} session for ${label}`,\n attributes,\n });\n } catch (error) {\n console.warn('[Factory reports] Unable to send the run-end report.', error);\n return { waiting: false };\n }\n };\n}\n\nexport interface FactoryStageChange {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n fromStage: string | undefined;\n toStage: string;\n}\n\n/**\n * Tells a work item's subscribers it moved, at `low` priority. Only sessions\n * already live hear it: a stage change never brings a session online; an\n * offline subscriber sees the stage in its state signal on its next turn.\n */\nexport function createStageChangeNotifier({\n workItems,\n reporting,\n}: {\n workItems: Pick<WorkItemsStorage, 'listWorkItemSubscribers' | 'getForProject'>;\n reporting: () => Promise<FactoryReporting | null>;\n}): (change: FactoryStageChange) => Promise<void> {\n return async change => {\n const subscribers = await workItems.listWorkItemSubscribers({\n orgId: change.orgId,\n workItemId: change.workItemId,\n });\n if (subscribers.length === 0) return;\n const resolved = await reporting();\n if (!resolved) return;\n const { label, ref } = await workItemReference(workItems, change);\n const summary = change.fromStage\n ? `${label} moved from ${change.fromStage} to ${change.toStage}.`\n : `${label} moved to ${change.toStage}.`;\n const notification: Omit<SendNotificationSignalInput, 'source'> = {\n kind: 'stage',\n priority: 'low',\n summary,\n payload: { message: summary },\n sourceId: change.workItemId,\n coalesceKey: `factory-stage:${change.workItemId}`,\n attributes: {\n 'work-item': ref,\n ...(change.fromStage ? { 'from-stage': change.fromStage } : {}),\n 'to-stage': change.toStage,\n },\n };\n for (const subscriber of subscribers) {\n try {\n await resolved.deliver({ sessionId: subscriber.sessionId, threadId: subscriber.threadId }, notification, {\n onlyIfLive: true,\n });\n } catch (error) {\n console.warn(`[Factory reports] Unable to tell ${subscriber.sessionId} that ${label} moved.`, error);\n }\n }\n };\n}\n\n/** Reports one run end of a session; the thread is the one the run used. */\nexport type FactorySessionRunEndReporter = (input: {\n sessionId: string;\n threadId: string | null;\n outcome: FactoryRunOutcome;\n since: Date;\n}) => Promise<void>;\n\n/** A tool call a session's run is holding until someone approves or declines it. */\nexport interface FactoryApprovalRequest {\n sessionId: string;\n threadId: string | null;\n toolName: string;\n toolCallId: string;\n args: unknown;\n}\n\nexport type FactoryApprovalNotifier = (request: FactoryApprovalRequest) => Promise<void>;\n\ninterface SessionReportDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n workItems: Pick<\n WorkItemsStorage,\n 'findActiveRunBindingForSession' | 'findRunBindingBySession' | 'listWorkItemSubscribers' | 'getForProject'\n >;\n reporting: () => Promise<FactoryReporting | null>;\n}\n\n/** How much of a gated call's arguments an approval notice quotes. */\nconst APPROVAL_ARGS_LENGTH = 3000;\n\n/**\n * Who hears from a session: a work session (one with an active run binding)\n * reports to its item's followers, a side session to the session that started\n * it. Any other session (a person's own) has nobody to tell.\n */\nasync function sessionAudience(\n { sessions, workItems }: Omit<SessionReportDependencies, 'reporting'>,\n sessionId: string,\n threadId: string | null,\n /** When the run started: a binding revoked since then (the run moved its card to a finished stage) still counts. */\n since?: Date,\n): Promise<\n | {\n kind: 'work-item';\n binding: NonNullable<Awaited<ReturnType<WorkItemsStorage['findActiveRunBindingForSession']>>>;\n sender: FactoryReportSender;\n }\n | {\n kind: 'origin';\n sender: FactoryReportSender;\n recipient: FactoryDeliveryTarget;\n subject: string;\n /** Set while the origin has muted this side session's reports (approval notices still go through). */\n mutedAt: Date | null;\n }\n | null\n> {\n const row = await sessions.getBySessionId(sessionId);\n if (!row?.factoryProjectId) return null;\n let binding = await workItems.findActiveRunBindingForSession({\n orgId: row.orgId,\n factoryProjectId: row.factoryProjectId,\n sessionId: row.sessionId,\n });\n if (!binding && since && threadId) {\n // The binding records the memory resource the run used: the Factory's, its\n // own id for a run kept on its own resource, or its owner's for a person's\n // session the run started in.\n for (const resourceId of new Set([row.factoryProjectId, row.sessionId, row.userId])) {\n const latest = await workItems.findRunBindingBySession({\n factoryProjectId: row.factoryProjectId,\n threadId,\n resourceId,\n sessionId: row.sessionId,\n });\n if (latest?.orgId === row.orgId && latest.revokedAt && latest.revokedAt >= since) {\n binding = latest;\n break;\n }\n }\n }\n if (binding) {\n return {\n kind: 'work-item',\n binding,\n sender: { sessionId: row.sessionId, threadId: binding.threadId, userId: row.userId },\n };\n }\n if (!row.originSessionId || !row.originThreadId || !threadId) return null;\n return {\n kind: 'origin',\n sender: { sessionId: row.sessionId, threadId, userId: row.userId },\n recipient: { sessionId: row.originSessionId, threadId: row.originThreadId },\n subject: `The side session \"${row.title ?? row.sessionId}\"`,\n mutedAt: row.originMutedAt ?? null,\n };\n}\n\n/** Reports each run end of a work or side session to whoever follows it. */\nexport function createSessionRunEndReporter(deps: SessionReportDependencies): FactorySessionRunEndReporter {\n const workItemRunEnd = createWorkItemRunEndReporter(deps);\n return async ({ sessionId, threadId, outcome, since }) => {\n const audience = await sessionAudience(deps, sessionId, threadId, since);\n if (!audience) return;\n if (audience.kind === 'work-item') {\n const { binding, sender } = audience;\n await workItemRunEnd({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n role: binding.role,\n sender,\n since,\n outcome,\n });\n return;\n }\n // A muted origin still hears when the session is blocked: nothing else would tell it the session is waiting.\n if (audience.mutedAt && outcome.status !== 'blocked') return;\n const resolved = await deps.reporting();\n if (!resolved) return;\n await sendRunEndReport(resolved, {\n sender: audience.sender,\n recipients: [audience.recipient],\n since,\n outcome,\n subject: audience.subject,\n });\n };\n}\n\n/**\n * Tells whoever follows a session, urgently, the moment its run holds a tool\n * call for approval. The run stays open on the gate, so no run end would say\n * so; the notice names the session and call so a follower can answer it with\n * `factory_answer_approval`.\n */\nexport function createSessionApprovalNotifier(deps: SessionReportDependencies): FactoryApprovalNotifier {\n return async ({ sessionId, threadId, toolName, toolCallId, args }) => {\n const audience = await sessionAudience(deps, sessionId, threadId);\n if (!audience) return;\n const resolved = await deps.reporting();\n if (!resolved) return;\n let subject: string;\n let recipients: FactoryDeliveryTarget[];\n let attributes: Record<string, string> = {};\n if (audience.kind === 'work-item') {\n const { binding } = audience;\n recipients = await workItemReportRecipients(deps.workItems, {\n orgId: binding.orgId,\n workItemId: binding.workItemId,\n senderSessionId: audience.sender.sessionId,\n });\n const named = await workItemReportAttributes(deps.workItems, binding);\n subject = `The ${binding.role} session for ${named.label}`;\n attributes = named.attributes;\n } else {\n recipients = [audience.recipient];\n subject = audience.subject;\n }\n if (recipients.length === 0) return;\n const argsText = JSON.stringify(args ?? {}) ?? '{}';\n const quoted = argsText.length > APPROVAL_ARGS_LENGTH ? `${argsText.slice(0, APPROVAL_ARGS_LENGTH)}…` : argsText;\n const message = [\n `${subject} is waiting for approval to run ${toolName} with ${quoted}.`,\n `Answer it with factory_answer_approval (sessionId \"${audience.sender.sessionId}\", toolCallId \"${toolCallId}\"), or open that session to approve or decline it there.`,\n ].join(' ');\n const notification = {\n ...reportNotification({\n sender: audience.sender,\n message,\n attributes: { ...attributes, 'waiting-for': 'approval', 'tool-name': toolName, 'tool-call-id': toolCallId },\n }),\n kind: 'approval',\n priority: 'urgent' as const,\n // One notice per held call, even if the gate is announced again.\n dedupeKey: `factory-approval:${toolCallId}`,\n };\n for (const recipient of recipients) await resolved.deliver(recipient, notification);\n };\n}\n"],"mappings":";;;;AAsBA,MAAa,uBAGT;CACF,QAAQ;EAAE,MAAM;EAAU,UAAU;EAAU,UAAU;CAAM;CAC9D,SAAS;EAAE,MAAM;EAAW,UAAU;EAAU,UAAU;CAAM;CAChE,MAAM;EAAE,MAAM;EAAQ,UAAU;EAAQ,UAAU;CAAM;CACxD,UAAU;EAAE,MAAM;EAAY,UAAU;EAAO,UAAU;CAAK;CAE9D,QAAQ;EAAE,MAAM;EAAU,UAAU;EAAQ,UAAU;CAAM;AAC9D;;AAGA,MAAM,oBAAoB;;;;;;;;AA0B1B,eAAsB,eACpB,eACA,EACE,iBACA,mBACA,OACA,OACA,YAAY,SASI;CAClB,MAAM,UAAU,MAAM,cAAc,kBAAkB;EACpD,UAAU;EACV,QAAQ;EACR,OAAO;CACT,CAAC;CACD,KAAK,MAAM,UAAU,SAA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AAS,OAAO;GACnC,CAAC;GACD,MAAM,QAAQ,MAAM,yBAAyB,KAAK,WAAW,OAAO;GACpE,UAAU,OAAO,QAAQ,KAAK,eAAe,MAAM;GACnD,aAAa,MAAM;EACrB,OAAO;GACL,aAAa,CAAC,SAAS,SAAS;GAChC,UAAU,SAAS;EACrB;EACA,IAAI,WAAW,WAAW,GAAG;EAC7B,MAAM,WAAW,KAAK,UAAU,QAAQ,CAAC,CAAC,KAAK;EAC/C,MAAM,SAAS,SAAS,SAAS,uBAAuB,GAAG,SAAS,MAAM,GAAG,oBAAoB,EAAE,KAAK;EACxG,MAAM,UAAU,CACd,GAAG,QAAQ,kCAAkC,SAAS,QAAQ,OAAO,IACrE,sDAAsD,SAAS,OAAO,UAAU,iBAAiB,WAAW,yDAC9G,CAAC,CAAC,KAAK,GAAG;EACV,MAAM,eAAe;GACnB,GAAG,mBAAmB;IACpB,QAAQ,SAAS;IACjB;IACA,YAAY;KAAE,GAAG;KAAY,eAAe;KAAY,aAAa;KAAU,gBAAgB;IAAW;GAC5G,CAAC;GACD,MAAM;GACN,UAAU;GAEV,WAAW,oBAAoB;EACjC;EACA,KAAK,MAAM,aAAa,YAAY,MAAM,SAAS,QAAQ,WAAW,YAAY;CACpF;AACF"}
1
+ {"version":3,"file":"reports.js","names":[],"sources":["../../src/tools/reports.ts"],"sourcesContent":["/**\n * Reports from sessions doing the work back to whoever follows it: a side\n * session's origin, or every subscriber of a work item. The agent reports with\n * `factory_message_origin`; when a run ends without one, the run-end backstop\n * sends it, so each run produces exactly one final report per recipient.\n */\n\nimport type {\n NotificationPriority,\n NotificationsStorage,\n SendNotificationSignalInput,\n} from '@mastra/core/notifications';\n\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { workItemNumber } from '../work-items/card-number.js';\nimport { FACTORY_SESSION_NOTIFICATION_SOURCE } from './deliver.js';\nimport type { FactoryDeliveryResult, FactoryDeliveryTarget } from './deliver.js';\n\nexport type FactoryReportStatus = 'progress' | 'blocked' | 'done' | 'failed';\n\n/** How each report status travels. Final reports never coalesce, so a later report can't overwrite them. */\nexport const FACTORY_REPORT_FORMS: Record<\n FactoryReportStatus | 'report',\n { kind: string; priority: NotificationPriority; coalesce: boolean }\n> = {\n failed: { kind: 'failed', priority: 'urgent', coalesce: false },\n blocked: { kind: 'blocked', priority: 'urgent', coalesce: false },\n done: { kind: 'done', priority: 'high', coalesce: false },\n progress: { kind: 'progress', priority: 'low', coalesce: true },\n // Not `message`: only messages can be answered, so a report can't start a reply loop.\n report: { kind: 'report', priority: 'high', coalesce: false },\n};\n\n/** How many recent `factory-session` notifications on a recipient thread the final-report check reads. */\nconst FINAL_REPORT_SCAN = 100;\n\nexport interface FactoryReportSender {\n sessionId: string;\n threadId: string;\n userId: string;\n}\n\nexport type FactoryReportDeliver = (\n target: FactoryDeliveryTarget,\n notification: Omit<SendNotificationSignalInput, 'source'>,\n options?: { onlyIfLive?: boolean },\n) => Promise<FactoryDeliveryResult>;\n\nexport interface FactoryReporting {\n deliver: FactoryReportDeliver;\n notifications: Pick<NotificationsStorage, 'listNotifications'>;\n}\n\n/**\n * Whether `senderSessionId` already put a report of one of `kinds` on the\n * recipient thread since `since`. Reads the durable notifications store, so it\n * holds across restarts. `listNotifications` has no time filter: records come\n * newest-updated first, and the scan stops at the first one last updated\n * before `since` (nothing after it can have been created later).\n */\nexport async function hasFinalReport(\n notifications: FactoryReporting['notifications'],\n {\n senderSessionId,\n recipientThreadId,\n since,\n kinds,\n agentOnly = false,\n }: {\n senderSessionId: string;\n recipientThreadId: string;\n since: Date;\n kinds: readonly string[];\n /** Ignore reports Factory sent on the session's behalf (the backstop). */\n agentOnly?: boolean;\n },\n): Promise<boolean> {\n const records = await notifications.listNotifications({\n threadId: recipientThreadId,\n source: FACTORY_SESSION_NOTIFICATION_SOURCE,\n limit: FINAL_REPORT_SCAN,\n });\n for (const record of records) {\n if (record.updatedAt < since) break;\n if (\n record.attributes?.['from-session'] === senderSessionId &&\n !(agentOnly && record.attributes?.backstop === 'true') &&\n // A reply carrying a final status counts like the report itself.\n (kinds.includes(record.kind) ||\n (record.kind === 'reply' &&\n typeof record.attributes?.status === 'string' &&\n kinds.includes(record.attributes.status))) &&\n record.createdAt >= since\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** The newest report `senderSessionId` put on the recipient thread. */\nasync function lastReport(\n notifications: FactoryReporting['notifications'],\n { senderSessionId, recipientThreadId }: { senderSessionId: string; recipientThreadId: string },\n) {\n const records = await notifications.listNotifications({\n threadId: recipientThreadId,\n source: FACTORY_SESSION_NOTIFICATION_SOURCE,\n limit: FINAL_REPORT_SCAN,\n });\n return records\n .filter(record => record.attributes?.['from-session'] === senderSessionId)\n .reduce<(typeof records)[number] | undefined>(\n (newest, record) => (!newest || reportedAt(record) > reportedAt(newest) ? record : newest),\n undefined,\n );\n}\n\n/**\n * When a report last said something. `updatedAt` also moves when a report is\n * read, so it only counts once a later report has coalesced into this one;\n * otherwise the report says what it said when it was created.\n */\nfunction reportedAt(record: { createdAt: Date; updatedAt: Date; coalescedCount?: number }): Date {\n return (record.coalescedCount ?? 1) > 1 ? record.updatedAt : record.createdAt;\n}\n\n/**\n * Whether the newest report `senderSessionId` put on the recipient thread is\n * already this exact `failed` backstop. A session stuck failing the same way\n * (a run that dies before the model, restarted over and over) then reports\n * once, not once per attempt; any other report in between resets it.\n */\nexport async function repeatsLastFailure(\n notifications: FactoryReporting['notifications'],\n {\n senderSessionId,\n recipientThreadId,\n summary,\n }: { senderSessionId: string; recipientThreadId: string; summary: string },\n): Promise<boolean> {\n const last = await lastReport(notifications, { senderSessionId, recipientThreadId });\n return last?.kind === 'failed' && last.attributes?.backstop === 'true' && last.summary === summary;\n}\n\n/**\n * Whether the newest report `senderSessionId` put on the recipient thread\n * already says it is done. A session woken again after it finished (a PR it\n * subscribed to gets comments, reviews and CI results) ends each of those runs\n * with nothing new to say, so the follower hears \"finished\" once, not per wake.\n */\nasync function alreadyReportedDone(\n notifications: FactoryReporting['notifications'],\n target: { senderSessionId: string; recipientThreadId: string },\n): Promise<boolean> {\n const last = await lastReport(notifications, target);\n return last?.kind === 'done' || (last?.kind === 'reply' && last.attributes?.status === 'done');\n}\n\nexport function reportNotification({\n sender,\n status,\n message,\n attributes = {},\n}: {\n sender: FactoryReportSender;\n status?: FactoryReportStatus;\n message: string;\n attributes?: Record<string, string>;\n}): Omit<SendNotificationSignalInput, 'source'> {\n const form = FACTORY_REPORT_FORMS[status ?? 'report'];\n return {\n kind: form.kind,\n priority: form.priority,\n // The whole text: a notification's summary is all the recipient's agent ever sees, even\n // through notification_inbox (which hides payloads), so a cut-off report loses its verdict.\n summary: message,\n payload: { message },\n sourceId: sender.sessionId,\n ...(form.coalesce ? { coalesceKey: `factory-session:${sender.sessionId}:${form.kind}` } : {}),\n attributes: {\n ...attributes,\n ...(status ? { status } : {}),\n // Last, so nothing above can claim another sender.\n 'from-session': sender.sessionId,\n 'from-thread': sender.threadId,\n 'from-user': sender.userId,\n },\n };\n}\n\n/** Everyone following a work item, except the session doing the reporting. */\nexport async function workItemReportRecipients(\n workItems: Pick<WorkItemsStorage, 'listWorkItemSubscribers'>,\n { orgId, workItemId, senderSessionId }: { orgId: string; workItemId: string; senderSessionId: string },\n): Promise<FactoryDeliveryTarget[]> {\n const subscribers = await workItems.listWorkItemSubscribers({ orgId, workItemId });\n return subscribers\n .filter(subscriber => subscriber.sessionId !== senderSessionId)\n .map(subscriber => ({ sessionId: subscriber.sessionId, threadId: subscriber.threadId }));\n}\n\n/** How reports name an item: `#n`, else its quoted title, else its id. */\nasync function workItemReference(\n workItems: Pick<WorkItemsStorage, 'getForProject'>,\n { orgId, factoryProjectId, workItemId }: { orgId: string; factoryProjectId: string; workItemId: string },\n): Promise<{ label: string; ref: string }> {\n const item = await workItems.getForProject(orgId, factoryProjectId, workItemId);\n const number = item ? workItemNumber(item) : null;\n if (number !== null) return { label: `#${number}`, ref: `#${number}` };\n return { label: item ? `\"${item.title}\"` : workItemId, ref: workItemId };\n}\n\n/** Attributes that say which item and role a worker's report is about. */\nexport async function workItemReportAttributes(\n workItems: Pick<WorkItemsStorage, 'getForProject'>,\n {\n orgId,\n factoryProjectId,\n workItemId,\n role,\n }: { orgId: string; factoryProjectId: string; workItemId: string; role: string },\n): Promise<{ label: string; attributes: Record<string, string> }> {\n const { label, ref } = await workItemReference(workItems, { orgId, factoryProjectId, workItemId });\n return { label, attributes: { 'work-item': ref, role } };\n}\n\nexport type FactoryRunOutcome =\n | { status: 'done' }\n | { status: 'failed'; reason: string; failureCode?: string }\n | {\n status: 'blocked';\n toolName?: string;\n toolCallId?: string;\n /** The call waits for a person to allow it. */\n approval?: boolean;\n /** The tool paused itself, and a yes or no from a follower is all it needs. */\n decision?: boolean;\n };\n\n/** `waiting`: the session is waiting for an answer, so a later run owes the final report. */\nexport interface FactoryRunEndResult {\n waiting: boolean;\n deliveries?: FactoryDeliveryResult[];\n}\n\n/**\n * The run-end backstop: send `outcome` to each recipient that hasn't had a\n * final report from this sender since the run started. An agent's own `done`\n * or `failed` report wins. A run that completes after the agent's own\n * `blocked` sends nothing: the agent ended its turn to wait for an answer, and\n * its `done` comes from a later run. A `failed` backstop still goes out after an\n * earlier `blocked`.\n */\nexport async function sendRunEndReport(\n reporting: FactoryReporting,\n {\n sender,\n recipients,\n since,\n outcome,\n subject,\n attributes = {},\n }: {\n sender: FactoryReportSender;\n recipients: FactoryDeliveryTarget[];\n since: Date;\n outcome: FactoryRunOutcome;\n /** Who finished, e.g. \"The work session for #12\". */\n subject: string;\n attributes?: Record<string, string>;\n },\n): Promise<FactoryRunEndResult> {\n const kinds = outcome.status === 'blocked' ? ['blocked'] : ['done', 'failed'];\n const message =\n outcome.status === 'done'\n ? `${subject} finished.`\n : outcome.status === 'failed'\n ? `${subject} failed${outcome.failureCode ? ` (${outcome.failureCode})` : ''}: ${outcome.reason}`\n : outcome.approval\n ? `${subject} is waiting for someone to approve ${outcome.toolName ?? 'a tool call'} in that session.`\n : `${subject} is waiting${outcome.toolName ? ` on ${outcome.toolName}` : ''} and needs an answer.${\n outcome.decision && outcome.toolCallId\n ? ` Approve or decline it with factory_answer_approval (sessionId \"${sender.sessionId}\", toolCallId \"${outcome.toolCallId}\").`\n : ''\n }`;\n const notification = reportNotification({\n sender,\n status: outcome.status,\n message,\n attributes: {\n ...attributes,\n backstop: 'true',\n ...(outcome.status === 'failed' && outcome.failureCode ? { 'failure-code': outcome.failureCode } : {}),\n ...(outcome.status === 'blocked' && outcome.toolName ? { 'parked-tool': outcome.toolName } : {}),\n ...(outcome.status === 'blocked' && outcome.toolCallId ? { 'tool-call-id': outcome.toolCallId } : {}),\n ...(outcome.status === 'blocked' && (outcome.approval || outcome.decision) ? { 'waiting-for': 'approval' } : {}),\n },\n });\n const report = (recipient: FactoryDeliveryTarget, reportKinds: string[], agentOnly = false) =>\n hasFinalReport(reporting.notifications, {\n senderSessionId: sender.sessionId,\n recipientThreadId: recipient.threadId,\n since,\n kinds: reportKinds,\n agentOnly,\n });\n let waiting = outcome.status === 'blocked';\n const deliveries: FactoryDeliveryResult[] = [];\n for (const recipient of recipients) {\n // Only the agent's own reports count: an earlier run's backstop lands after this\n // run's window opened. A reply already told that follower how a finished run went.\n if (await report(recipient, outcome.status === 'done' ? [...kinds, 'reply'] : kinds, true)) continue;\n // Only the agent's own `blocked` means it ended its turn to wait; a backstop `blocked` from a parked run doesn't.\n if (outcome.status === 'done' && (await report(recipient, ['blocked'], true))) {\n waiting = true;\n continue;\n }\n if (\n outcome.status === 'done' &&\n (await alreadyReportedDone(reporting.notifications, {\n senderSessionId: sender.sessionId,\n recipientThreadId: recipient.threadId,\n }))\n ) {\n continue;\n }\n if (\n outcome.status === 'failed' &&\n (await repeatsLastFailure(reporting.notifications, {\n senderSessionId: sender.sessionId,\n recipientThreadId: recipient.threadId,\n summary: message,\n }))\n ) {\n continue;\n }\n deliveries.push(await reporting.deliver(recipient, notification));\n }\n return { waiting, deliveries };\n}\n\nexport interface FactoryRunEndInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n role: string;\n sender: FactoryReportSender;\n since: Date;\n outcome: FactoryRunOutcome;\n}\n\nexport type FactoryRunEndReporter = (input: FactoryRunEndInput) => Promise<FactoryRunEndResult>;\n\n/** The backstop for a work-item run: reports to the item's subscribers. Failures are logged, never thrown. */\nexport function createWorkItemRunEndReporter({\n workItems,\n reporting,\n}: {\n workItems: Pick<WorkItemsStorage, 'listWorkItemSubscribers' | 'getForProject'>;\n /** Resolved per report: the controller exists only once the mount is up. */\n reporting: () => Promise<FactoryReporting | null>;\n}): FactoryRunEndReporter {\n return async input => {\n try {\n const resolved = await reporting();\n if (!resolved) return { waiting: false };\n const recipients = await workItemReportRecipients(workItems, {\n orgId: input.orgId,\n workItemId: input.workItemId,\n senderSessionId: input.sender.sessionId,\n });\n if (recipients.length === 0) return { waiting: false };\n const { label, attributes } = await workItemReportAttributes(workItems, input);\n return await sendRunEndReport(resolved, {\n sender: input.sender,\n recipients,\n since: input.since,\n outcome: input.outcome,\n subject: `The ${input.role} session for ${label}`,\n attributes,\n });\n } catch (error) {\n console.warn('[Factory reports] Unable to send the run-end report.', error);\n return { waiting: false };\n }\n };\n}\n\nexport interface FactoryStageChange {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n fromStage: string | undefined;\n toStage: string;\n}\n\n/**\n * Tells a work item's subscribers it moved, at `low` priority. Only sessions\n * already live hear it: a stage change never brings a session online; an\n * offline subscriber sees the stage in its state signal on its next turn.\n */\nexport function createStageChangeNotifier({\n workItems,\n reporting,\n}: {\n workItems: Pick<WorkItemsStorage, 'listWorkItemSubscribers' | 'getForProject'>;\n reporting: () => Promise<FactoryReporting | null>;\n}): (change: FactoryStageChange) => Promise<void> {\n return async change => {\n const subscribers = await workItems.listWorkItemSubscribers({\n orgId: change.orgId,\n workItemId: change.workItemId,\n });\n if (subscribers.length === 0) return;\n const resolved = await reporting();\n if (!resolved) return;\n const { label, ref } = await workItemReference(workItems, change);\n const summary = change.fromStage\n ? `${label} moved from ${change.fromStage} to ${change.toStage}.`\n : `${label} moved to ${change.toStage}.`;\n const notification: Omit<SendNotificationSignalInput, 'source'> = {\n kind: 'stage',\n priority: 'low',\n summary,\n payload: { message: summary },\n sourceId: change.workItemId,\n coalesceKey: `factory-stage:${change.workItemId}`,\n attributes: {\n 'work-item': ref,\n ...(change.fromStage ? { 'from-stage': change.fromStage } : {}),\n 'to-stage': change.toStage,\n },\n };\n for (const subscriber of subscribers) {\n try {\n await resolved.deliver({ sessionId: subscriber.sessionId, threadId: subscriber.threadId }, notification, {\n onlyIfLive: true,\n });\n } catch (error) {\n console.warn(`[Factory reports] Unable to tell ${subscriber.sessionId} that ${label} moved.`, error);\n }\n }\n };\n}\n\n/** Reports one run end of a session; the thread is the one the run used. */\nexport type FactorySessionRunEndReporter = (input: {\n sessionId: string;\n threadId: string | null;\n outcome: FactoryRunOutcome;\n since: Date;\n}) => Promise<void>;\n\n/** A tool call a session's run is holding until someone approves or declines it. */\nexport interface FactoryApprovalRequest {\n sessionId: string;\n threadId: string | null;\n toolName: string;\n toolCallId: string;\n args: unknown;\n}\n\nexport type FactoryApprovalNotifier = (request: FactoryApprovalRequest) => Promise<void>;\n\ninterface SessionReportDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n workItems: Pick<\n WorkItemsStorage,\n 'findActiveRunBindingForSession' | 'findRunBindingBySession' | 'listWorkItemSubscribers' | 'getForProject'\n >;\n reporting: () => Promise<FactoryReporting | null>;\n}\n\n/** How much of a gated call's arguments an approval notice quotes. */\nconst APPROVAL_ARGS_LENGTH = 3000;\n\n/**\n * Who hears from a session: a work session (one with an active run binding)\n * reports to its item's followers, a side session to the session that started\n * it. Any other session (a person's own) has nobody to tell.\n */\nasync function sessionAudience(\n { sessions, workItems }: Omit<SessionReportDependencies, 'reporting'>,\n sessionId: string,\n threadId: string | null,\n /** When the run started: a binding revoked since then (the run moved its card to a finished stage) still counts. */\n since?: Date,\n): Promise<\n | {\n kind: 'work-item';\n binding: NonNullable<Awaited<ReturnType<WorkItemsStorage['findActiveRunBindingForSession']>>>;\n sender: FactoryReportSender;\n }\n | {\n kind: 'origin';\n sender: FactoryReportSender;\n recipient: FactoryDeliveryTarget;\n subject: string;\n /** Set while the origin has muted this side session's reports (approval notices still go through). */\n mutedAt: Date | null;\n }\n | null\n> {\n const row = await sessions.getBySessionId(sessionId);\n if (!row?.factoryProjectId) return null;\n let binding = await workItems.findActiveRunBindingForSession({\n orgId: row.orgId,\n factoryProjectId: row.factoryProjectId,\n sessionId: row.sessionId,\n });\n if (!binding && since && threadId) {\n // The binding records the memory resource the run used: the Factory's, its\n // own id for a run kept on its own resource, or its owner's for a person's\n // session the run started in.\n for (const resourceId of new Set([row.factoryProjectId, row.sessionId, row.userId])) {\n const latest = await workItems.findRunBindingBySession({\n factoryProjectId: row.factoryProjectId,\n threadId,\n resourceId,\n sessionId: row.sessionId,\n });\n if (latest?.orgId === row.orgId && latest.revokedAt && latest.revokedAt >= since) {\n binding = latest;\n break;\n }\n }\n }\n if (binding) {\n return {\n kind: 'work-item',\n binding,\n sender: { sessionId: row.sessionId, threadId: binding.threadId, userId: row.userId },\n };\n }\n if (!row.originSessionId || !row.originThreadId || !threadId) return null;\n return {\n kind: 'origin',\n sender: { sessionId: row.sessionId, threadId, userId: row.userId },\n recipient: { sessionId: row.originSessionId, threadId: row.originThreadId },\n subject: `The side session \"${row.title ?? row.sessionId}\"`,\n mutedAt: row.originMutedAt ?? null,\n };\n}\n\n/** Reports each run end of a work or side session to whoever follows it. */\nexport function createSessionRunEndReporter(deps: SessionReportDependencies): FactorySessionRunEndReporter {\n const workItemRunEnd = createWorkItemRunEndReporter(deps);\n return async ({ sessionId, threadId, outcome, since }) => {\n const audience = await sessionAudience(deps, sessionId, threadId, since);\n if (!audience) return;\n if (audience.kind === 'work-item') {\n const { binding, sender } = audience;\n await workItemRunEnd({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n role: binding.role,\n sender,\n since,\n outcome,\n });\n return;\n }\n // A muted origin still hears when the session is blocked: nothing else would tell it the session is waiting.\n if (audience.mutedAt && outcome.status !== 'blocked') return;\n const resolved = await deps.reporting();\n if (!resolved) return;\n await sendRunEndReport(resolved, {\n sender: audience.sender,\n recipients: [audience.recipient],\n since,\n outcome,\n subject: audience.subject,\n });\n };\n}\n\n/**\n * Tells whoever follows a session, urgently, the moment its run holds a tool\n * call for approval. The run stays open on the gate, so no run end would say\n * so; the notice names the session and call so a follower can answer it with\n * `factory_answer_approval`.\n */\nexport function createSessionApprovalNotifier(deps: SessionReportDependencies): FactoryApprovalNotifier {\n return async ({ sessionId, threadId, toolName, toolCallId, args }) => {\n const audience = await sessionAudience(deps, sessionId, threadId);\n if (!audience) return;\n const resolved = await deps.reporting();\n if (!resolved) return;\n let subject: string;\n let recipients: FactoryDeliveryTarget[];\n let attributes: Record<string, string> = {};\n if (audience.kind === 'work-item') {\n const { binding } = audience;\n recipients = await workItemReportRecipients(deps.workItems, {\n orgId: binding.orgId,\n workItemId: binding.workItemId,\n senderSessionId: audience.sender.sessionId,\n });\n const named = await workItemReportAttributes(deps.workItems, binding);\n subject = `The ${binding.role} session for ${named.label}`;\n attributes = named.attributes;\n } else {\n recipients = [audience.recipient];\n subject = audience.subject;\n }\n if (recipients.length === 0) return;\n const argsText = JSON.stringify(args ?? {}) ?? '{}';\n const quoted = argsText.length > APPROVAL_ARGS_LENGTH ? `${argsText.slice(0, APPROVAL_ARGS_LENGTH)}…` : argsText;\n const message = [\n `${subject} is waiting for approval to run ${toolName} with ${quoted}.`,\n `Answer it with factory_answer_approval (sessionId \"${audience.sender.sessionId}\", toolCallId \"${toolCallId}\"), or open that session to approve or decline it there.`,\n ].join(' ');\n const notification = {\n ...reportNotification({\n sender: audience.sender,\n message,\n attributes: { ...attributes, 'waiting-for': 'approval', 'tool-name': toolName, 'tool-call-id': toolCallId },\n }),\n kind: 'approval',\n priority: 'urgent' as const,\n // One notice per held call, even if the gate is announced again.\n dedupeKey: `factory-approval:${toolCallId}`,\n };\n for (const recipient of recipients) await resolved.deliver(recipient, notification);\n };\n}\n"],"mappings":";;;;AAsBA,MAAa,uBAGT;CACF,QAAQ;EAAE,MAAM;EAAU,UAAU;EAAU,UAAU;CAAM;CAC9D,SAAS;EAAE,MAAM;EAAW,UAAU;EAAU,UAAU;CAAM;CAChE,MAAM;EAAE,MAAM;EAAQ,UAAU;EAAQ,UAAU;CAAM;CACxD,UAAU;EAAE,MAAM;EAAY,UAAU;EAAO,UAAU;CAAK;CAE9D,QAAQ;EAAE,MAAM;EAAU,UAAU;EAAQ,UAAU;CAAM;AAC9D;;AAGA,MAAM,oBAAoB;;;;;;;;AA0B1B,eAAsB,eACpB,eACA,EACE,iBACA,mBACA,OACA,OACA,YAAY,SASI;CAClB,MAAM,UAAU,MAAM,cAAc,kBAAkB;EACpD,UAAU;EACV,QAAQ;EACR,OAAO;CACT,CAAC;CACD,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,OAAO,YAAY,OAAO;EAC9B,IACE,OAAO,aAAa,oBAAoB,mBACxC,EAAE,aAAa,OAAO,YAAY,aAAa,YAE9C,MAAM,SAAS,OAAO,IAAI,KACxB,OAAO,SAAS,WACf,OAAO,OAAO,YAAY,WAAW,YACrC,MAAM,SAAS,OAAO,WAAW,MAAM,MAC3C,OAAO,aAAa,OAEpB,OAAO;CAEX;CACA,OAAO;AACT;;AAGA,eAAe,WACb,eACA,EAAE,iBAAiB,qBACnB;CAMA,QAAO,MALe,cAAc,kBAAkB;EACpD,UAAU;EACV,QAAQ;EACR,OAAO;CACT,CAAC,EAAA,CAEE,QAAO,WAAU,OAAO,aAAa,oBAAoB,eAAe,CAAC,CACzE,QACE,QAAQ,WAAY,CAAC,UAAU,WAAW,MAAM,IAAI,WAAW,MAAM,IAAI,SAAS,QACnF,KAAA,CACF;AACJ;;;;;;AAOA,SAAS,WAAW,QAA6E;CAC/F,QAAQ,OAA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,YAAY;KAAE,GAAG;KAAY,eAAe;KAAY,aAAa;KAAU,gBAAgB;IAAW;GAC5G,CAAC;GACD,MAAM;GACN,UAAU;GAEV,WAAW,oBAAoB;EACjC;EACA,KAAK,MAAM,aAAa,YAAY,MAAM,SAAS,QAAQ,WAAW,YAAY;CACpF;AACF"}
@@ -4,11 +4,21 @@ import type { FactoryRunOutcome } from './reports.js';
4
4
  type RunEndReason = Extract<AgentControllerEvent, {
5
5
  type: 'agent_end';
6
6
  }>['reason'];
7
+ /**
8
+ * Whether a bare yes or no is all a paused tool needs to carry on: its resume data is an
9
+ * object whose `action` is `approved` or `rejected`, and nothing else is required. A
10
+ * question to the person (free text, a choice, a decision plus a required detail) does
11
+ * not fit, and is answered in the session itself.
12
+ */
13
+ export declare function resumesOnDecision(resumeSchema: string | undefined): boolean;
7
14
  /** What a run stopped on: a tool waiting for an answer, or one waiting for approval. */
8
15
  export interface ParkedTool {
9
16
  toolName: string;
10
17
  toolCallId: string;
18
+ /** The call has not run yet, and waits for a person to allow it. */
11
19
  approval: boolean;
20
+ /** The tool paused itself, and a bare yes or no is all it needs to carry on. */
21
+ decision?: boolean;
12
22
  }
13
23
  export interface RunReportSession {
14
24
  subscribe(listener: (event: AgentControllerEvent) => void): () => void;
@@ -28,8 +38,10 @@ export type SessionApprovalReport = (request: {
28
38
  * stopped or steered says nothing, and its window carries into the next run,
29
39
  * so reports the agent made in it still count.
30
40
  */
31
- export declare function observeSessionRunReports(session: RunReportSession, report: SessionRunEndReport, { onApprovalRequested }?: {
41
+ export declare function observeSessionRunReports(session: RunReportSession, report: SessionRunEndReport, { onApprovalRequested, answersItself, }?: {
32
42
  onApprovalRequested?: SessionApprovalReport;
43
+ /** Whether the Factory answers this paused call without a person, so its run carries on and nobody needs telling. */
44
+ answersItself?: (toolCallId: string) => boolean;
33
45
  }): () => void;
34
46
  /**
35
47
  * Renew a kicked-off run's open-run entry until the run ends, like the
@@ -41,6 +53,6 @@ export declare function heartbeatOpenRunUntilEnd(session: RunEndCaptureSession,
41
53
  stop: () => void;
42
54
  };
43
55
  /** `null` for an aborted run: someone stopped or steered it, which is not an outcome. */
44
- export declare function runOutcome(reason: RunEndReason, parked: Pick<ParkedTool, 'toolName' | 'toolCallId' | 'approval'> | undefined, errorMessage?: string): FactoryRunOutcome | null;
56
+ export declare function runOutcome(reason: RunEndReason, parked: ParkedTool | undefined, errorMessage?: string): FactoryRunOutcome | null;
45
57
  export {};
46
58
  //# sourceMappingURL=run-watch.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-watch.d.ts","sourceRoot":"","sources":["../../src/tools/run-watch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAI1E,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEtD,KAAK,YAAY,GAAG,OAAO,CAAC,oBAAoB,EAAE;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC,CAAC,QAAQ,CAAC,CAAC;AAEnF,wFAAwF;AACxF,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,gBAAgB;IAC/B,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACxE;AAED,wFAAwF;AACxF,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,EAAE,iBAAiB,EAAE,KAAK,EAAE,IAAI,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAE7F,sFAAsF;AACtF,MAAM,MAAM,qBAAqB,GAAG,CAAC,OAAO,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,IAAI,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N_STALE_MS, heartbeatSessionOpenRun } from "../session/run-audit.js";
2
2
  import { toPersistedErrorIdentity } from "@mastra/core/error";
3
3
  // src/tools/run-watch.ts
4
+ /**
5
+ * Whether a bare yes or no is all a paused tool needs to carry on: its resume data is an
6
+ * object whose `action` is `approved` or `rejected`, and nothing else is required. A
7
+ * question to the person (free text, a choice, a decision plus a required detail) does
8
+ * not fit, and is answered in the session itself.
9
+ */
10
+ function resumesOnDecision(resumeSchema) {
11
+ if (!resumeSchema) return false;
12
+ try {
13
+ const schema = JSON.parse(resumeSchema);
14
+ const actions = schema.properties?.action?.enum;
15
+ const required = Array.isArray(schema.required) ? schema.required : [];
16
+ return Array.isArray(actions) && actions.includes("approved") && actions.includes("rejected") && required.every((field) => field === "action");
17
+ } catch {
18
+ return false;
19
+ }
20
+ }
4
21
  /** How much of a run's error message a `failed` report quotes. */
5
22
  const ERROR_MESSAGE_LENGTH = 400;
6
23
  /**
@@ -10,7 +27,7 @@ const ERROR_MESSAGE_LENGTH = 400;
10
27
  * stopped or steered says nothing, and its window carries into the next run,
11
28
  * so reports the agent made in it still count.
12
29
  */
13
- function observeSessionRunReports(session, report, { onApprovalRequested } = {}) {
30
+ function observeSessionRunReports(session, report, { onApprovalRequested, answersItself } = {}) {
14
31
  let parked;
15
32
  let lastError;
16
33
  let since = /* @__PURE__ */ new Date();
@@ -22,7 +39,8 @@ function observeSessionRunReports(session, report, { onApprovalRequested } = {})
22
39
  parked = {
23
40
  toolName: event.toolName,
24
41
  toolCallId: event.toolCallId,
25
- approval: event.type === "tool_approval_required"
42
+ approval: event.type === "tool_approval_required",
43
+ ...event.type === "tool_suspended" && resumesOnDecision(event.resumeSchema) ? { decision: true } : {}
26
44
  };
27
45
  if (event.type === "tool_approval_required" && onApprovalRequested) settle(onApprovalRequested({
28
46
  toolName: event.toolName,
@@ -44,6 +62,7 @@ function observeSessionRunReports(session, report, { onApprovalRequested } = {})
44
62
  parked = void 0;
45
63
  lastError = void 0;
46
64
  if (!outcome) return;
65
+ if (outcome.status === "blocked" && outcome.toolCallId && answersItself?.(outcome.toolCallId)) return;
47
66
  const runSince = since;
48
67
  since = new Date(Date.now() + 1);
49
68
  settle(report(outcome, runSince));
@@ -92,12 +111,13 @@ function runOutcome(reason, parked, errorMessage) {
92
111
  ...parked ? {
93
112
  toolName: parked.toolName,
94
113
  toolCallId: parked.toolCallId,
95
- ...parked.approval ? { approval: true } : {}
114
+ ...parked.approval ? { approval: true } : {},
115
+ ...parked.decision ? { decision: true } : {}
96
116
  } : {}
97
117
  };
98
118
  default: return { status: "done" };
99
119
  }
100
120
  }
101
- export { heartbeatOpenRunUntilEnd, observeSessionRunReports, runOutcome };
121
+ export { heartbeatOpenRunUntilEnd, observeSessionRunReports, resumesOnDecision, runOutcome };
102
122
 
103
123
  //# sourceMappingURL=run-watch.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-watch.js","names":[],"sources":["../../src/tools/run-watch.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\nimport { toPersistedErrorIdentity } from '@mastra/core/error';\n\nimport { FACTORY_OPEN_RUN_STALE_MS, heartbeatSessionOpenRun } from '../session/run-audit.js';\nimport type { RunEndCaptureSession } from '../session/run-audit.js';\nimport type { FactoryRunOutcome } from './reports.js';\n\ntype RunEndReason = Extract<AgentControllerEvent, { type: 'agent_end' }>['reason'];\n\n/** What a run stopped on: a tool waiting for an answer, or one waiting for approval. */\nexport interface ParkedTool {\n toolName: string;\n toolCallId: string;\n approval: boolean;\n}\n\nexport interface RunReportSession {\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\n/** Reports one run's end; `since` is when the run's window opened. Should not throw. */\nexport type SessionRunEndReport = (outcome: FactoryRunOutcome, since: Date) => Promise<void>;\n\n/** Told when the run holds a tool call for approval; the run stays open meanwhile. */\nexport type SessionApprovalReport = (request: { toolName: string; toolCallId: string; args: unknown }) => Promise<void>;\n\n/** How much of a run's error message a `failed` report quotes. */\nconst ERROR_MESSAGE_LENGTH = 400;\n\n/**\n * Report every run end of a session, however the run started: the board, a\n * typed message, a wake, or a run after a restart. Attached to each Factory\n * session when it is created, so it outlives any one start. A run someone\n * stopped or steered says nothing, and its window carries into the next run,\n * so reports the agent made in it still count.\n */\nexport function observeSessionRunReports(\n session: RunReportSession,\n report: SessionRunEndReport,\n { onApprovalRequested }: { onApprovalRequested?: SessionApprovalReport } = {},\n): () => void {\n let parked: ParkedTool | undefined;\n let lastError: string | undefined;\n let since = new Date();\n const settle = (work: Promise<void>) =>\n void work.catch(error => {\n console.warn('[Factory reports] Unable to report on a session run.', error);\n });\n return session.subscribe(event => {\n if (event.type === 'tool_suspended' || event.type === 'tool_approval_required') {\n parked = {\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n approval: event.type === 'tool_approval_required',\n };\n // An approval gate holds the run open, so it is announced now, not at the run's end.\n if (event.type === 'tool_approval_required' && onApprovalRequested) {\n settle(onApprovalRequested({ toolName: event.toolName, toolCallId: event.toolCallId, args: event.args }));\n }\n return;\n }\n if (event.type === 'error') {\n lastError = toPersistedErrorIdentity(event.error).reason ?? event.error?.message;\n return;\n }\n if (event.type === 'tool_suspension_cancelled' && parked?.toolCallId === event.toolCallId) {\n parked = undefined;\n return;\n }\n if (event.type !== 'agent_end') return;\n const outcome = runOutcome(event.reason, parked, lastError);\n parked = undefined;\n lastError = undefined;\n if (!outcome) return;\n // Move the window now, so a run that starts before this report settles is judged on its own;\n // reports made up to the end, including its last millisecond, belong to the run that ended.\n const runSince = since;\n since = new Date(Date.now() + 1);\n settle(report(outcome, runSince));\n });\n}\n\n/**\n * Renew a kicked-off run's open-run entry until the run ends, like the\n * dispatcher's heartbeat, so no dispatcher starts the role again meanwhile.\n * `endReason` is how that run ended, once it has; `stop` is for a kickoff that fails.\n */\nexport function heartbeatOpenRunUntilEnd(\n session: RunEndCaptureSession,\n kickoffId: string,\n): { endReason: () => RunEndReason; stop: () => void } {\n let endReason: RunEndReason;\n let unsubscribe = () => {};\n const timer = setInterval(\n () => void heartbeatSessionOpenRun(session, kickoffId),\n Math.floor(FACTORY_OPEN_RUN_STALE_MS / 3),\n );\n timer.unref?.();\n let stopped = false;\n const stop = () => {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n unsubscribe();\n };\n unsubscribe = session.subscribe(event => {\n if (event.type !== 'agent_end') return;\n endReason ??= event.reason;\n stop();\n });\n return { endReason: () => endReason, stop };\n}\n\n/** `null` for an aborted run: someone stopped or steered it, which is not an outcome. */\nexport function runOutcome(\n reason: RunEndReason,\n parked: Pick<ParkedTool, 'toolName' | 'toolCallId' | 'approval'> | undefined,\n errorMessage?: string,\n): FactoryRunOutcome | null {\n switch (reason) {\n case 'error': {\n const message = errorMessage?.trim();\n return {\n status: 'failed',\n reason: message\n ? `the run ended in error: ${message.slice(0, ERROR_MESSAGE_LENGTH)}`\n : 'the run ended in error.',\n };\n }\n case 'aborted':\n return null;\n case 'suspended':\n return {\n status: 'blocked',\n ...(parked\n ? {\n toolName: parked.toolName,\n toolCallId: parked.toolCallId,\n ...(parked.approval ? { approval: true } : {}),\n }\n : {}),\n };\n default:\n return { status: 'done' };\n }\n}\n"],"mappings":";;;;AA2BA,MAAM,uBAAuB;;;;;;;;AAS7B,SAAgB,yBACd,SACA,QACA,EAAE,wBAAyE,CAAC,GAChE;CACZ,IAAI;CACJ,IAAI;CACJ,IAAI,wBAAQ,IAAI,KAAK;CACrB,MAAM,UAAU,SACd,KAAK,KAAK,OAAM,UAAS;EACvB,QAAQ,KAAK,wDAAwD,KAAK;CAC5E,CAAC;CACH,OAAO,QAAQ,WAAU,UAAS;EAChC,IAAI,MAAM,SAAS,oBAAoB,MAAM,SAAS,0BAA0B;GAC9E,SAAS;IACP,UAAU,MAAM;IAChB,YAAY,MAAM;IAClB,UAAU,MAAM,SAAS;GAC3B;GAEA,IAAI,MAAM,SAAS,4BAA4B,qBAC7C,OAAO,oBAAoB;IAAE,UAAU,MAAM;IAAU,YAAY,MAAM;IAAY,MAAM,MAAM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W,EAAE,UAAU,KAAK,IAAI,CAAC;GAC9C,IACA,CAAC;EACP;EACF,SACE,OAAO,EAAE,QAAQ,OAAO;CAC5B;AACF"}
1
+ {"version":3,"file":"run-watch.js","names":[],"sources":["../../src/tools/run-watch.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\nimport { toPersistedErrorIdentity } from '@mastra/core/error';\n\nimport { FACTORY_OPEN_RUN_STALE_MS, heartbeatSessionOpenRun } from '../session/run-audit.js';\nimport type { RunEndCaptureSession } from '../session/run-audit.js';\nimport type { FactoryRunOutcome } from './reports.js';\n\ntype RunEndReason = Extract<AgentControllerEvent, { type: 'agent_end' }>['reason'];\n\n/**\n * Whether a bare yes or no is all a paused tool needs to carry on: its resume data is an\n * object whose `action` is `approved` or `rejected`, and nothing else is required. A\n * question to the person (free text, a choice, a decision plus a required detail) does\n * not fit, and is answered in the session itself.\n */\nexport function resumesOnDecision(resumeSchema: string | undefined): boolean {\n if (!resumeSchema) return false;\n try {\n const schema = JSON.parse(resumeSchema) as { properties?: { action?: { enum?: unknown } }; required?: unknown };\n const actions = schema.properties?.action?.enum;\n const required = Array.isArray(schema.required) ? schema.required : [];\n return (\n Array.isArray(actions) &&\n actions.includes('approved') &&\n actions.includes('rejected') &&\n required.every(field => field === 'action')\n );\n } catch {\n return false;\n }\n}\n\n/** What a run stopped on: a tool waiting for an answer, or one waiting for approval. */\nexport interface ParkedTool {\n toolName: string;\n toolCallId: string;\n /** The call has not run yet, and waits for a person to allow it. */\n approval: boolean;\n /** The tool paused itself, and a bare yes or no is all it needs to carry on. */\n decision?: boolean;\n}\n\nexport interface RunReportSession {\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\n/** Reports one run's end; `since` is when the run's window opened. Should not throw. */\nexport type SessionRunEndReport = (outcome: FactoryRunOutcome, since: Date) => Promise<void>;\n\n/** Told when the run holds a tool call for approval; the run stays open meanwhile. */\nexport type SessionApprovalReport = (request: { toolName: string; toolCallId: string; args: unknown }) => Promise<void>;\n\n/** How much of a run's error message a `failed` report quotes. */\nconst ERROR_MESSAGE_LENGTH = 400;\n\n/**\n * Report every run end of a session, however the run started: the board, a\n * typed message, a wake, or a run after a restart. Attached to each Factory\n * session when it is created, so it outlives any one start. A run someone\n * stopped or steered says nothing, and its window carries into the next run,\n * so reports the agent made in it still count.\n */\nexport function observeSessionRunReports(\n session: RunReportSession,\n report: SessionRunEndReport,\n {\n onApprovalRequested,\n answersItself,\n }: {\n onApprovalRequested?: SessionApprovalReport;\n /** Whether the Factory answers this paused call without a person, so its run carries on and nobody needs telling. */\n answersItself?: (toolCallId: string) => boolean;\n } = {},\n): () => void {\n let parked: ParkedTool | undefined;\n let lastError: string | undefined;\n let since = new Date();\n const settle = (work: Promise<void>) =>\n void work.catch(error => {\n console.warn('[Factory reports] Unable to report on a session run.', error);\n });\n return session.subscribe(event => {\n if (event.type === 'tool_suspended' || event.type === 'tool_approval_required') {\n parked = {\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n approval: event.type === 'tool_approval_required',\n ...(event.type === 'tool_suspended' && resumesOnDecision(event.resumeSchema) ? { decision: true } : {}),\n };\n // An approval gate holds the run open, so it is announced now, not at the run's end.\n if (event.type === 'tool_approval_required' && onApprovalRequested) {\n settle(onApprovalRequested({ toolName: event.toolName, toolCallId: event.toolCallId, args: event.args }));\n }\n return;\n }\n if (event.type === 'error') {\n lastError = toPersistedErrorIdentity(event.error).reason ?? event.error?.message;\n return;\n }\n if (event.type === 'tool_suspension_cancelled' && parked?.toolCallId === event.toolCallId) {\n parked = undefined;\n return;\n }\n if (event.type !== 'agent_end') return;\n const outcome = runOutcome(event.reason, parked, lastError);\n parked = undefined;\n lastError = undefined;\n if (!outcome) return;\n // Not an end: the Factory answers the call and the same run carries on in its window.\n if (outcome.status === 'blocked' && outcome.toolCallId && answersItself?.(outcome.toolCallId)) return;\n // Move the window now, so a run that starts before this report settles is judged on its own;\n // reports made up to the end, including its last millisecond, belong to the run that ended.\n const runSince = since;\n since = new Date(Date.now() + 1);\n settle(report(outcome, runSince));\n });\n}\n\n/**\n * Renew a kicked-off run's open-run entry until the run ends, like the\n * dispatcher's heartbeat, so no dispatcher starts the role again meanwhile.\n * `endReason` is how that run ended, once it has; `stop` is for a kickoff that fails.\n */\nexport function heartbeatOpenRunUntilEnd(\n session: RunEndCaptureSession,\n kickoffId: string,\n): { endReason: () => RunEndReason; stop: () => void } {\n let endReason: RunEndReason;\n let unsubscribe = () => {};\n const timer = setInterval(\n () => void heartbeatSessionOpenRun(session, kickoffId),\n Math.floor(FACTORY_OPEN_RUN_STALE_MS / 3),\n );\n timer.unref?.();\n let stopped = false;\n const stop = () => {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n unsubscribe();\n };\n unsubscribe = session.subscribe(event => {\n if (event.type !== 'agent_end') return;\n endReason ??= event.reason;\n stop();\n });\n return { endReason: () => endReason, stop };\n}\n\n/** `null` for an aborted run: someone stopped or steered it, which is not an outcome. */\nexport function runOutcome(\n reason: RunEndReason,\n parked: ParkedTool | undefined,\n errorMessage?: string,\n): FactoryRunOutcome | null {\n switch (reason) {\n case 'error': {\n const message = errorMessage?.trim();\n return {\n status: 'failed',\n reason: message\n ? `the run ended in error: ${message.slice(0, ERROR_MESSAGE_LENGTH)}`\n : 'the run ended in error.',\n };\n }\n case 'aborted':\n return null;\n case 'suspended':\n return {\n status: 'blocked',\n ...(parked\n ? {\n toolName: parked.toolName,\n toolCallId: parked.toolCallId,\n ...(parked.approval ? { approval: true } : {}),\n ...(parked.decision ? { decision: true } : {}),\n }\n : {}),\n };\n default:\n return { status: 'done' };\n }\n}\n"],"mappings":";;;;;;;;;AAeA,SAAgB,kBAAkB,cAA2C;CAC3E,IAAI,CAAC,cAAc,OAAO;CAC1B,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,YAAY;EACtC,MAAM,UAAU,OAAO,YAAY,QAAQ;EAC3C,MAAM,WAAW,MAAM,QAAQ,OAAO,QAAQ,IAAI,OAAO,WAAW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AAK,KAAK,IAAI,IAAI,CAAC;EAC/B,OAAO,OAAO,SAAS,QAAQ,CAAC;CAClC,CAAC;AACH;;;;;;AAOA,SAAgB,yBACd,SACA,WACqD;CACrD,IAAI;CACJ,IAAI,oBAAoB,CAAC;CACzB,MAAM,QAAQ,kBACN,KAAK,wBAAwB,SAAS,SAAS,GACrD,KAAK,MAAM,4BAA4B,CAAC,CAC1C;CACA,MAAM,QAAQ;CACd,IAAI,UAAU;CACd,MAAM,aAAa;EACjB,IAAI,SAAS;EACb,UAAU;EACV,cAAc,KAAK;EACnB,YAAY;CACd;CACA,cAAc,QAAQ,WAAU,UAAS;EACvC,IAAI,MAAM,SAAS,aAAa;EAChC,cAAc,MAAM;EACpB,KAAK;CACP,CAAC;CACD,OAAO;EAAE,iBAAiB;EAAW;CAAK;AAC5C;;AAGA,SAAgB,WACd,QACA,QACA,cAC0B;CAC1B,QAAQ,QAAR;EACE,KAAK,SAAS;GACZ,MAAM,UAAU,cAAc,KAAK;GACnC,OAAO;IACL,QAAQ;IACR,QAAQ,UACJ,2BAA2B,QAAQ,MAAM,GAAG,oBAAoB,MAChE;GACN;EACF;EACA,KAAK,WACH,OAAO;EACT,KAAK,aACH,OAAO;GACL,QAAQ;GACR,GAAI,SACA;IACE,UAAU,OAAO;IACjB,YAAY,OAAO;IACnB,GAAI,OAAO,WAAW,EAAE,UAAU,KAAK,IAAI,CAAC;IAC5C,GAAI,OAAO,WAAW,EAAE,UAAU,KAAK,IAAI,CAAC;GAC9C,IACA,CAAC;EACP;EACF,SACE,OAAO,EAAE,QAAQ,OAAO;CAC5B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"session-tools.d.ts","sourceRoot":"","sources":["../../src/tools/session-tools.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,KAAK,EAAE,gBAAg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