@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
@@ -10,6 +10,26 @@ export interface FactoryApprovalToolDependencies {
10
10
  auditRecorder: AuditRecorder;
11
11
  messaging: () => Promise<FactoryMessaging | null>;
12
12
  }
13
+ /**
14
+ * Approve or decline a tool call a live session waits on, for a caller already allowed
15
+ * to. Any tool can wait this way; with no `toolCallId` the session's only waiting call
16
+ * is answered. The answered run carries on as the session's owner whoever answers: a
17
+ * phase session keeps one identity from kickoff to finish, and a resume never runs with
18
+ * no user.
19
+ */
20
+ export declare function answerParkedCall(deps: Pick<FactoryApprovalToolDependencies, 'messaging'>, input: {
21
+ session: {
22
+ sessionId: string;
23
+ userId: string;
24
+ orgId: string;
25
+ };
26
+ toolCallId?: string;
27
+ decision: 'approve' | 'decline';
28
+ declineReason: string;
29
+ }): Promise<{
30
+ toolCallId: string;
31
+ toolName: string;
32
+ }>;
13
33
  /** Answers a tool call another session holds for approval. Only a signed-in person's turn may answer. */
14
34
  export declare function createFactoryApprovalTools(scope: FactoryToolScope, deps: FactoryApprovalToolDependencies): IntegrationTools;
15
35
  //# sourceMappingURL=approval-tools.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"approval-tools.d.ts","sourceRoot":"","sources":["../../src/tools/approval-tools.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AACxE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,MAAM,WAAW,+BAA+B;IAC9C,QAAQ,EAAE,IAAI,CAAC,0BAA0B,EAAE,gBAAgB,CAAC,CAAC;IAC7D,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,gCAAgC,GAAG,0BAA0B,CAAC,C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AAS,GAAG,SAAS,CAAC;IAChC,aAAa,EAAE,MAAM,CAAC;CACvB,GACA,OAAO,CAAC;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC,CAyDnD;AAED,yGAAyG;AACzG,wBAAgB,0BAA0B,CACxC,KAAK,EAAE,gBAAgB,EACvB,IAAI,EAAE,+BAA+B,GACpC,gBAAgB,CA2ElB"}
@@ -1,16 +1,86 @@
1
+ import { resumesOnDecision } from "./run-watch.js";
1
2
  import { requirePerson } from "./scope.js";
2
3
  import { RequestContext } from "@mastra/core/request-context";
3
4
  import { createTool } from "@mastra/core/tools";
4
5
  import { z } from "zod";
5
6
  // src/tools/approval-tools.ts
7
+ const ALREADY_ANSWERED = "That call was already answered: someone else got there first.";
8
+ function waitingApprovals(live) {
9
+ return [...live.approval.list().map(({ toolCallId, toolName }) => ({
10
+ toolCallId,
11
+ toolName,
12
+ channel: "gate"
13
+ })), ...[...live.displayState.get().pendingSuspensions.values()].filter((suspension) => resumesOnDecision(suspension.resumeSchema)).map(({ toolCallId, toolName }) => ({
14
+ toolCallId,
15
+ toolName,
16
+ channel: "resume"
17
+ }))];
18
+ }
19
+ /**
20
+ * Approve or decline a tool call a live session waits on, for a caller already allowed
21
+ * to. Any tool can wait this way; with no `toolCallId` the session's only waiting call
22
+ * is answered. The answered run carries on as the session's owner whoever answers: a
23
+ * phase session keeps one identity from kickoff to finish, and a resume never runs with
24
+ * no user.
25
+ */
26
+ async function answerParkedCall(deps, input) {
27
+ const { session, decision, declineReason } = input;
28
+ const messaging = await deps.messaging();
29
+ if (!messaging) throw new Error("Answering approvals is not available on this server.");
30
+ const live = await messaging.controller.getSession(session.sessionId);
31
+ const waiting = live ? waitingApprovals(live) : [];
32
+ const matches = input.toolCallId ? waiting.filter((call) => call.toolCallId === input.toolCallId) : waiting;
33
+ const [call] = matches;
34
+ if (!live || !call) throw new Error(input.toolCallId ? "Nothing is waiting on that tool call any more: the run that asked has ended or it was already answered. Message the session with factory_signal_session if it should try again." : "This session is not waiting on an approval. Open it to see what it needs.");
35
+ if (matches.length > 1) throw new Error(`This session waits on ${matches.length} approvals (${matches.map((match) => `${match.toolName}: ${match.toolCallId}`).join(", ")}). Name the toolCallId to answer.`);
36
+ const { toolCallId, toolName } = call;
37
+ const requestContext = new RequestContext();
38
+ requestContext.set("user", {
39
+ workosId: session.userId,
40
+ organizationId: session.orgId
41
+ });
42
+ if (call.channel === "resume") {
43
+ const claim = live.claimToolSuspension(toolCallId);
44
+ if (!claim.accepted) throw new Error(ALREADY_ANSWERED);
45
+ try {
46
+ await live.respondToToolSuspension({
47
+ resumeData: decision === "approve" ? { action: "approved" } : {
48
+ action: "rejected",
49
+ feedback: declineReason
50
+ },
51
+ address: claim.address,
52
+ requestContext
53
+ });
54
+ } finally {
55
+ live.releaseToolResponse(claim.claimKey);
56
+ }
57
+ if (live.suspensions.has(claim.address)) throw new Error(`The answer did not reach ${toolName}: the session could not carry on and still waits on it. Open the session to see why.`);
58
+ return {
59
+ toolCallId,
60
+ toolName
61
+ };
62
+ }
63
+ const result = live.respondToToolApproval({
64
+ decision,
65
+ toolCallId,
66
+ requestContext,
67
+ ...decision === "decline" ? { declineContext: { reason: declineReason } } : {}
68
+ });
69
+ if (!result.accepted) throw new Error(result.reason === "not_pending" ? ALREADY_ANSWERED : `The answer was not accepted (${result.reason}).`);
70
+ return {
71
+ toolCallId,
72
+ toolName
73
+ };
74
+ }
6
75
  /** Answers a tool call another session holds for approval. Only a signed-in person's turn may answer. */
7
76
  function createFactoryApprovalTools(scope, deps) {
8
77
  return { factory_answer_approval: createTool({
9
78
  id: "factory_answer_approval",
10
79
  description: [
11
- "Approve or decline a tool call a session you follow is waiting on, as you.",
80
+ "Approve or decline a tool call a session you follow is waiting on.",
81
+ "The decision is recorded as yours; the run carries on as the owner of the session that asked.",
12
82
  "A `factory-session` notification of kind `approval` names the session, tool, arguments and toolCallId;",
13
- "a `blocked` notice for a session parked on submit_plan names the toolCallId of the plan to approve or decline.",
83
+ "a `blocked` notice for a session parked on a tool that waits for approval names the toolCallId to approve or decline.",
14
84
  "Answer only what the person in this conversation agreed to; decline with a reason the session will see."
15
85
  ].join(" "),
16
86
  inputSchema: z.object({
@@ -36,33 +106,12 @@ function createFactoryApprovalTools(scope, deps) {
36
106
  sessionId: scope.sessionId
37
107
  })).some((subscription) => subscription.workItemId === binding.workItemId);
38
108
  if (!isOrigin && !follows) throw new Error(`This session doesn't follow session ${sessionId}: follow its work item first, or answer from that session.`);
39
- const messaging = await deps.messaging();
40
- if (!messaging) throw new Error("Answering approvals is not available on this server.");
41
- const live = await messaging.controller.getSession(sessionId);
42
- const parkedPlan = live?.suspensions.resolve({ toolCallId })?.toolName === "submit_plan";
43
- if (!live || !parkedPlan && !live.approval.isArmed({ toolCallId })) throw new Error("Nothing is waiting on that tool call any more: the run that asked has ended or it was already answered. Message the session with factory_signal_session if it should try again.");
44
- if (parkedPlan) {
45
- const requestContext = new RequestContext();
46
- requestContext.set("user", {
47
- workosId: scope.userId,
48
- organizationId: scope.orgId
49
- });
50
- await live.respondToToolSuspension({
51
- resumeData: decision === "approve" ? { action: "approved" } : {
52
- action: "rejected",
53
- feedback: reason ?? "Declined by a session following it."
54
- },
55
- toolCallId,
56
- requestContext
57
- });
58
- } else {
59
- const result = live.respondToToolApproval({
60
- decision,
61
- toolCallId,
62
- ...decision === "decline" ? { declineContext: { reason: reason ?? "Declined by a session following it." } } : {}
63
- });
64
- if (!result.accepted) throw new Error(`The answer was not accepted (${result.reason}).`);
65
- }
109
+ await answerParkedCall(deps, {
110
+ session: row,
111
+ toolCallId,
112
+ decision,
113
+ declineReason: reason ?? "Declined by a session following it."
114
+ });
66
115
  deps.auditRecorder.record({
67
116
  orgId: scope.orgId,
68
117
  actorId: scope.userId,
@@ -92,6 +141,6 @@ function createFactoryApprovalTools(scope, deps) {
92
141
  }
93
142
  }) };
94
143
  }
95
- export { createFactoryApprovalTools };
144
+ export { answerParkedCall, createFactoryApprovalTools };
96
145
 
97
146
  //# sourceMappingURL=approval-tools.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"approval-tools.js","names":[],"sources":["../../src/tools/approval-tools.ts"],"sourcesContent":["import { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../integrations/base.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactoryMessaging } from './messaging-tools.js';\nimport { requirePerson } from './scope.js';\nimport type { FactoryToolScope } from './scope.js';\n\nexport interface FactoryApprovalToolDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n workItems: Pick<WorkItemsStorage, 'findActiveRunBindingForSession' | 'listSessionSubscriptions'>;\n auditRecorder: AuditRecorder;\n messaging: () => Promise<FactoryMessaging | null>;\n}\n\n/** The parts of a live session an answer needs: its open approval gates. */\ninterface ApprovalGateSession {\n approval: { isArmed(filter: { toolCallId: string }): boolean };\n respondToToolApproval(input: {\n decision: 'approve' | 'decline';\n toolCallId: string;\n declineContext?: { reason?: string };\n }): { accepted: true } | { accepted: false; reason: string };\n suspensions: { resolve(filter: { toolCallId: string }): { toolName: string } | undefined };\n respondToToolSuspension(input: {\n resumeData: { action: 'approved' | 'rejected'; feedback?: string };\n toolCallId: string;\n requestContext?: RequestContext;\n }): Promise<void>;\n}\n\n/** Answers a tool call another session holds for approval. Only a signed-in person's turn may answer. */\nexport function createFactoryApprovalTools(\n scope: FactoryToolScope,\n deps: FactoryApprovalToolDependencies,\n): IntegrationTools {\n const answer = createTool({\n id: 'factory_answer_approval',\n description: [\n 'Approve or decline a tool call a session you follow is waiting on, as you.',\n 'A `factory-session` notification of kind `approval` names the session, tool, arguments and toolCallId;',\n 'a `blocked` notice for a session parked on submit_plan names the toolCallId of the plan to approve or decline.',\n 'Answer only what the person in this conversation agreed to; decline with a reason the session will see.',\n ].join(' '),\n inputSchema: z\n .object({\n sessionId: z.string().uuid().describe('The session holding the call, from the approval notice.'),\n toolCallId: z.string().trim().min(1).max(200),\n decision: z.enum(['approve', 'decline']),\n reason: z.string().trim().min(1).max(1000).optional().describe('Why, when declining.'),\n })\n .strict(),\n execute: async ({ sessionId, toolCallId, decision, reason }) => {\n requirePerson(scope, 'answer an approval');\n const row = await deps.sessions.getBySessionId(sessionId);\n if (!row || row.orgId !== scope.orgId || row.factoryProjectId !== scope.factoryProjectId) {\n throw new Error(`Session ${sessionId} was not found in this Factory.`);\n }\n if (row.visibility === 'private' && row.userId !== scope.userId) {\n throw new Error(`Session ${sessionId} is private to its owner.`);\n }\n\n // Only the sessions it reports to may answer it: its origin, or followers of its item.\n const binding = await deps.workItems.findActiveRunBindingForSession({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId,\n });\n const isOrigin = row.originSessionId === scope.sessionId;\n const follows =\n binding !== null &&\n (\n await deps.workItems.listSessionSubscriptions({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId: scope.sessionId,\n })\n ).some(subscription => subscription.workItemId === binding.workItemId);\n if (!isOrigin && !follows) {\n throw new Error(\n `This session doesn't follow session ${sessionId}: follow its work item first, or answer from that session.`,\n );\n }\n\n const messaging = await deps.messaging();\n if (!messaging) throw new Error('Answering approvals is not available on this server.');\n const live = (await messaging.controller.getSession(sessionId)) as ApprovalGateSession | null;\n const parkedPlan = live?.suspensions.resolve({ toolCallId })?.toolName === 'submit_plan';\n if (!live || (!parkedPlan && !live.approval.isArmed({ toolCallId }))) {\n throw new Error(\n 'Nothing is waiting on that tool call any more: the run that asked has ended or it was already answered. ' +\n 'Message the session with factory_signal_session if it should try again.',\n );\n }\n if (parkedPlan) {\n // The resumed run acts for the person answering, so it can resolve their model credentials.\n const requestContext = new RequestContext();\n requestContext.set('user', { workosId: scope.userId, organizationId: scope.orgId });\n await live.respondToToolSuspension({\n resumeData:\n decision === 'approve'\n ? { action: 'approved' }\n : { action: 'rejected', feedback: reason ?? 'Declined by a session following it.' },\n toolCallId,\n requestContext,\n });\n } else {\n const result = live.respondToToolApproval({\n decision,\n toolCallId,\n ...(decision === 'decline'\n ? { declineContext: { reason: reason ?? 'Declined by a session following it.' } }\n : {}),\n });\n if (!result.accepted) throw new Error(`The answer was not accepted (${result.reason}).`);\n }\n\n deps.auditRecorder.record({\n orgId: scope.orgId,\n actorId: scope.userId,\n actorType: 'human',\n ...(scope.actorProfile ? { actorProfile: scope.actorProfile } : {}),\n action: decision === 'approve' ? 'factory.run.approved' : 'factory.run.dismissed',\n factoryProjectId: scope.factoryProjectId,\n targets: [\n { type: 'session', id: sessionId },\n ...(binding ? [{ type: 'work_item' as const, id: binding.workItemId }] : []),\n ],\n metadata: { toolCallId, sessionId, decision, cause: 'factory_tools' },\n });\n return { answered: decision, sessionId, toolCallId };\n },\n });\n\n return { factory_answer_approval: answer };\n}\n"],"mappings":";;;;;;AAoCA,SAAgB,2BACd,OACA,MACkB;CAmGlB,OAAO,EAAE,yBAlGM,WAAW;EACxB,IAAI;EACJ,aAAa;GACX;GACA;GACA;GACA;EACF,CAAC,CAAC,KAAK,GAAG;EACV,aAAa,EACV,OAAO;GACN,WAAW,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS,yDAAyD;GAC/F,YAAY,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;GAC5C,UAAU,EAAE,KAAK,CAAC,WAAW,SAAS,CAAC;GACvC,QAAQ,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAI,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,sBAAsB;EACvF,CAAC,CAAC,CACD,OAAO;EACV,SAAS,OAAO,EAAE,WAAW,YAAY,UAAU,aAAa;GAC9D,cAAc,OAAO,oBAAoB;G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OAAO;IACL,MAAM,SAAS,KAAK,sBAAsB;KACxC;KACA;KACA,GAAI,aAAa,YACb,EAAE,gBAAgB,EAAE,QAAQ,UAAU,sCAAsC,EAAE,IAC9E,CAAC;IACP,CAAC;IACD,IAAI,CAAC,OAAO,UAAU,MAAM,IAAI,MAAM,gCAAgC,OAAO,OAAO,GAAG;GACzF;GAEA,KAAK,cAAc,OAAO;IACxB,OAAO,MAAM;IACb,SAAS,MAAM;IACf,WAAW;IACX,GAAI,MAAM,eAAe,EAAE,cAAc,MAAM,aAAa,IAAI,CAAC;IACjE,QAAQ,aAAa,YAAY,yBAAyB;IAC1D,kBAAkB,MAAM;IACxB,SAAS,CACP;KAAE,MAAM;KAAW,IAAI;IAAU,GACjC,GAAI,UAAU,CAAC;KAAE,MAAM;KAAsB,IAAI,QAAQ;IAAW,CAAC,IAAI,CAAC,CAC5E;IACA,UAAU;KAAE;KAAY;KAAW;KAAU,OAAO;IAAgB;GACtE,CAAC;GACD,OAAO;IAAE,UAAU;IAAU;IAAW;GAAW;EACrD;CACF,CAEuC,EAAE;AAC3C"}
1
+ {"version":3,"file":"approval-tools.js","names":[],"sources":["../../src/tools/approval-tools.ts"],"sourcesContent":["import type { SuspensionAddress } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../integrations/base.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactoryMessaging } from './messaging-tools.js';\nimport { resumesOnDecision } from './run-watch.js';\nimport { requirePerson } from './scope.js';\nimport type { FactoryToolScope } from './scope.js';\n\nexport interface FactoryApprovalToolDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId'>;\n workItems: Pick<WorkItemsStorage, 'findActiveRunBindingForSession' | 'listSessionSubscriptions'>;\n auditRecorder: AuditRecorder;\n messaging: () => Promise<FactoryMessaging | null>;\n}\n\n/** The parts of a live session an answer needs: the calls it waits on, and how each is answered. */\ninterface ApprovalGateSession {\n approval: { list(): Array<{ toolCallId: string; toolName: string }> };\n displayState: {\n get(): { pendingSuspensions: Map<string, { toolCallId: string; toolName: string; resumeSchema?: string }> };\n };\n respondToToolApproval(input: {\n decision: 'approve' | 'decline';\n toolCallId: string;\n requestContext?: RequestContext;\n declineContext?: { reason?: string };\n }): { accepted: true } | { accepted: false; reason: string };\n suspensions: { has(address: SuspensionAddress): boolean };\n /** Takes the right to answer a paused call, so two answers cannot both resume it. */\n claimToolSuspension(\n toolCallId: string,\n ): { accepted: true; address: SuspensionAddress; claimKey: string } | { accepted: false; reason: string };\n releaseToolResponse(claimKey: string): void;\n respondToToolSuspension(input: {\n resumeData: { action: 'approved' | 'rejected'; feedback?: string };\n address: SuspensionAddress;\n requestContext?: RequestContext;\n }): Promise<void>;\n}\n\nconst ALREADY_ANSWERED = 'That call was already answered: someone else got there first.';\n\n/** A tool call waiting for a yes or no, and which of the session's two channels answers it. */\ninterface WaitingApproval {\n toolCallId: string;\n toolName: string;\n /** `gate`: the call has not run yet. `resume`: the tool paused itself to ask. */\n channel: 'gate' | 'resume';\n}\n\nfunction waitingApprovals(live: ApprovalGateSession): WaitingApproval[] {\n return [\n ...live.approval.list().map(({ toolCallId, toolName }) => ({ toolCallId, toolName, channel: 'gate' as const })),\n // Keyed by run address, not tool call id: read the id off each entry.\n ...[...live.displayState.get().pendingSuspensions.values()]\n .filter(suspension => resumesOnDecision(suspension.resumeSchema))\n .map(({ toolCallId, toolName }) => ({ toolCallId, toolName, channel: 'resume' as const })),\n ];\n}\n\n/**\n * Approve or decline a tool call a live session waits on, for a caller already allowed\n * to. Any tool can wait this way; with no `toolCallId` the session's only waiting call\n * is answered. The answered run carries on as the session's owner whoever answers: a\n * phase session keeps one identity from kickoff to finish, and a resume never runs with\n * no user.\n */\nexport async function answerParkedCall(\n deps: Pick<FactoryApprovalToolDependencies, 'messaging'>,\n input: {\n session: { sessionId: string; userId: string; orgId: string };\n toolCallId?: string;\n decision: 'approve' | 'decline';\n declineReason: string;\n },\n): Promise<{ toolCallId: string; toolName: string }> {\n const { session, decision, declineReason } = input;\n const messaging = await deps.messaging();\n if (!messaging) throw new Error('Answering approvals is not available on this server.');\n const live = (await messaging.controller.getSession(session.sessionId)) as ApprovalGateSession | null;\n const waiting = live ? waitingApprovals(live) : [];\n const matches = input.toolCallId ? waiting.filter(call => call.toolCallId === input.toolCallId) : waiting;\n const [call] = matches;\n if (!live || !call) {\n throw new Error(\n input.toolCallId\n ? 'Nothing is waiting on that tool call any more: the run that asked has ended or it was already answered. ' +\n 'Message the session with factory_signal_session if it should try again.'\n : 'This session is not waiting on an approval. Open it to see what it needs.',\n );\n }\n if (matches.length > 1) {\n throw new Error(\n `This session waits on ${matches.length} approvals (${matches.map(match => `${match.toolName}: ${match.toolCallId}`).join(', ')}). Name the toolCallId to answer.`,\n );\n }\n const { toolCallId, toolName } = call;\n const requestContext = new RequestContext();\n requestContext.set('user', { workosId: session.userId, organizationId: session.orgId });\n if (call.channel === 'resume') {\n // Claimed before anything is awaited: of two answers arriving together, one resumes the call.\n const claim = live.claimToolSuspension(toolCallId);\n if (!claim.accepted) throw new Error(ALREADY_ANSWERED);\n try {\n await live.respondToToolSuspension({\n resumeData: decision === 'approve' ? { action: 'approved' } : { action: 'rejected', feedback: declineReason },\n address: claim.address,\n requestContext,\n });\n } finally {\n live.releaseToolResponse(claim.claimKey);\n }\n // A resume that fails to start reports its error to the session and leaves the call waiting.\n if (live.suspensions.has(claim.address)) {\n throw new Error(\n `The answer did not reach ${toolName}: the session could not carry on and still waits on it. Open the session to see why.`,\n );\n }\n return { toolCallId, toolName };\n }\n const result = live.respondToToolApproval({\n decision,\n toolCallId,\n requestContext,\n ...(decision === 'decline' ? { declineContext: { reason: declineReason } } : {}),\n });\n if (!result.accepted) {\n throw new Error(\n result.reason === 'not_pending' ? ALREADY_ANSWERED : `The answer was not accepted (${result.reason}).`,\n );\n }\n return { toolCallId, toolName };\n}\n\n/** Answers a tool call another session holds for approval. Only a signed-in person's turn may answer. */\nexport function createFactoryApprovalTools(\n scope: FactoryToolScope,\n deps: FactoryApprovalToolDependencies,\n): IntegrationTools {\n const answer = createTool({\n id: 'factory_answer_approval',\n description: [\n 'Approve or decline a tool call a session you follow is waiting on.',\n 'The decision is recorded as yours; the run carries on as the owner of the session that asked.',\n 'A `factory-session` notification of kind `approval` names the session, tool, arguments and toolCallId;',\n 'a `blocked` notice for a session parked on a tool that waits for approval names the toolCallId to approve or decline.',\n 'Answer only what the person in this conversation agreed to; decline with a reason the session will see.',\n ].join(' '),\n inputSchema: z\n .object({\n sessionId: z.string().uuid().describe('The session holding the call, from the approval notice.'),\n toolCallId: z.string().trim().min(1).max(200),\n decision: z.enum(['approve', 'decline']),\n reason: z.string().trim().min(1).max(1000).optional().describe('Why, when declining.'),\n })\n .strict(),\n execute: async ({ sessionId, toolCallId, decision, reason }) => {\n requirePerson(scope, 'answer an approval');\n const row = await deps.sessions.getBySessionId(sessionId);\n if (!row || row.orgId !== scope.orgId || row.factoryProjectId !== scope.factoryProjectId) {\n throw new Error(`Session ${sessionId} was not found in this Factory.`);\n }\n if (row.visibility === 'private' && row.userId !== scope.userId) {\n throw new Error(`Session ${sessionId} is private to its owner.`);\n }\n\n // Only the sessions it reports to may answer it: its origin, or followers of its item.\n const binding = await deps.workItems.findActiveRunBindingForSession({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId,\n });\n const isOrigin = row.originSessionId === scope.sessionId;\n const follows =\n binding !== null &&\n (\n await deps.workItems.listSessionSubscriptions({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId: scope.sessionId,\n })\n ).some(subscription => subscription.workItemId === binding.workItemId);\n if (!isOrigin && !follows) {\n throw new Error(\n `This session doesn't follow session ${sessionId}: follow its work item first, or answer from that session.`,\n );\n }\n\n await answerParkedCall(deps, {\n session: row,\n toolCallId,\n decision,\n declineReason: reason ?? 'Declined by a session following it.',\n });\n\n deps.auditRecorder.record({\n orgId: scope.orgId,\n actorId: scope.userId,\n actorType: 'human',\n ...(scope.actorProfile ? { actorProfile: scope.actorProfile } : {}),\n action: decision === 'approve' ? 'factory.run.approved' : 'factory.run.dismissed',\n factoryProjectId: scope.factoryProjectId,\n targets: [\n { type: 'session', id: sessionId },\n ...(binding ? [{ type: 'work_item' as const, id: binding.workItemId }] : []),\n ],\n metadata: { toolCallId, sessionId, decision, cause: 'factory_tools' },\n });\n return { answered: decision, sessionId, toolCallId };\n },\n });\n\n return { factory_answer_approval: answer };\n}\n"],"mappings":";;;;;;AA8CA,MAAM,mBAAmB;AAUzB,SAAS,iBAAiB,MAA8C;CACtE,OAAO,CACL,GAAG,KAAK,SAAS,KAAK,CAAC,CAAC,KAAK,EAAE,YAAY,gBAAgB;EAAE;EAAY;EAAU,SAAS;CAAgB,EAAE,GAE9G,GAAG,CAAC,GAAG,KAAK,aAAa,IAAI,CAAC,CAAC,mBAAmB,OAAO,CAAC,CAAC,CACxD,QAAO,eAAc,kBAAkB,WAAW,YAAY,CAAC,CAAC,CAChE,KAAK,EAAE,YAAY,gBAAgB;EAAE;EAAY;EAAU,SAAS;CAAkB,EAAE,CAC7F;AACF;;;;;;;;AASA,eAAsB,iBACpB,MACA,OAMmD;CACnD,MAAM,EAAE,SAAS,UAAU,kBAAkB;CAC7C,MAAM,YAAY,MAAM,KAAK,UAAU;CACvC,IAAI,CAAC,WAAW,MAAM,IAAI,MAAM,sDAAsD;CACtF,MAAM,OAAQ,MAAM,UAAU,WAAW,WAAW,QAAQ,SAAS;CACrE,MAAM,UAAU,OAAO,iBAAiB,IAAI,IAAI,CAAC;CACjD,MAAM,UAAU,MAAM,aAAa,QAAQ,QAAO,SAAQ,KAAK,eAAe,MAAM,UAAU,IAAI;CAClG,MAAM,CAAC,QAAQ;CACf,IAAI,CAAC,QAAQ,CAAC,MACZ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,MAAM;IACf,WAAW;IACX,GAAI,MAAM,eAAe,EAAE,cAAc,MAAM,aAAa,IAAI,CAAC;IACjE,QAAQ,aAAa,YAAY,yBAAyB;IAC1D,kBAAkB,MAAM;IACxB,SAAS,CACP;KAAE,MAAM;KAAW,IAAI;IAAU,GACjC,GAAI,UAAU,CAAC;KAAE,MAAM;KAAsB,IAAI,QAAQ;IAAW,CAAC,IAAI,CAAC,CAC5E;IACA,UAAU;KAAE;KAAY;KAAW;KAAU,OAAO;IAAgB;GACtE,CAAC;GACD,OAAO;IAAE,UAAU;IAAU;IAAW;GAAW;EACrD;CACF,CAEuC,EAAE;AAC3C"}
@@ -19,7 +19,7 @@ export declare function createAuditEventsTool(scope: FactoryToolScope, deps: Fac
19
19
  actor?: string | undefined;
20
20
  includeAgentRuns?: boolean | undefined;
21
21
  namespace?: "agent" | "board" | "git" | "intake" | "intake_route" | "run" | "sandbox_env" | "session" | "skill" | "work_item" | undefined;
22
- actions?: ("factory.agent.commit" | "factory.agent.pr_opened" | "factory.agent.push" | "factory.agent.signaled" | "factory.board.created" | "factory.board.deleted" | "factory.board.reset" | "factory.board.updated" | "factory.git.commit" | "factory.git.pr_opened" | "factory.git.push" | "factory.intake.binding_updated" | "factory.intake.config_updated" | "factory.intake.label_route_updated" | "factory.intake_route.created" | "factory.intake_route.deleted" | "factory.intake_route.reordered" | "factory.intake_route.updated" | "factory.run.approved" | "factory.run.dismissed" | "factory.run.ended" | "factory.run.queued" | "factory.run.rejected" | "factory.run.retry" | "factory.run.started" | "factory.sandbox_env.deleted" | "factory.sandbox_env.set" | "factory.sandbox_env.updated" | "factory.session.owner_transferred" | "factory.skill.reverted" | "factory.skill.updated" | "factory.work_item.created" | "factory.work_item.deleted" | "factory.work_item.labels_reconciled" | "factory.work_item.stage_moved" | "factory.work_item.transition_rejected" | "factory.work_item.updated")[] | undefined;
22
+ actions?: ("factory.agent.commit" | "factory.agent.pr_opened" | "factory.agent.push" | "factory.agent.signaled" | "factory.board.created" | "factory.board.deleted" | "factory.board.reset" | "factory.board.updated" | "factory.git.commit" | "factory.git.pr_opened" | "factory.git.push" | "factory.intake.binding_updated" | "factory.intake.config_updated" | "factory.intake.label_route_updated" | "factory.intake_route.created" | "factory.intake_route.deleted" | "factory.intake_route.reordered" | "factory.intake_route.rerouted" | "factory.intake_route.updated" | "factory.run.approved" | "factory.run.dismissed" | "factory.run.ended" | "factory.run.queued" | "factory.run.rejected" | "factory.run.retry" | "factory.run.started" | "factory.sandbox_env.deleted" | "factory.sandbox_env.set" | "factory.sandbox_env.updated" | "factory.session.owner_transferred" | "factory.skill.reverted" | "factory.skill.updated" | "factory.work_item.created" | "factory.work_item.deleted" | "factory.work_item.labels_reconciled" | "factory.work_item.stage_moved" | "factory.work_item.transition_rejected" | "factory.work_item.updated")[] | undefined;
23
23
  workItem?: string | undefined;
24
24
  since?: string | undefined;
25
25
  until?: string | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"messaging-tools.d.ts","sourceRoot":"","sources":["../../src/tools/messaging-tools.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAGV,oBAAoB,EAErB,MAAM,4BAA4B,CAAC;AAIpC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AAExE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAM9E,OAAO,KAAK,EAAE,yBAAyB,EAAyB,MAAM,cAAc,CAAC;AAIrF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAGnD,gFAAgF;AAChF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AACpC,eAAO,MAAM,qBAAqB,QAAiB,CAAC;AA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c,CAAC;AAGrF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAGnD,gFAAgF;AAChF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AACpC,eAAO,MAAM,qBAAqB,QAAiB,CAAC;AAyCpD,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,yBAAyB,CAAC;IACtC,aAAa,EAAE,IAAI,CAAC,oBAAoB,EAAE,mBAAmB,GAAG,iBAAiB,CAAC,CAAC;CACpF;AAED,MAAM,WAAW,gCAAgC;IAC/C,QAAQ,EAAE,IAAI,CAAC,0BAA0B,EAAE,gBAAgB,GAAG,cAAc,GAAG,gBAAgB,CAAC,CAAC;IACjG,SAAS,EAAE,IAAI,CACb,gBAAgB,EACd,gCAAgC,GAChC,eAAe,GACf,yBAAyB,GACzB,0BAA0B,GAC1B,iBAAiB,GACjB,yBAAyB,CAC5B,CAAC;IACF,aAAa,EAAE,aAAa,CAAC;IAC7B,mHAAmH;IACnH,SAAS,EAAE,MAAM,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAC;IAClD,sFAAsF;IACtF,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC,YAAY,EAAE,QAAQ,GAAG,UAAU,CAAC,GAAG,SAAS,CAAC;CAC5E;AAgBD,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,gBAAgB,EACvB,IAAI,EAAE,gCAAgC,GACrC,gBAAgB,CAqhBlB"}
@@ -1,5 +1,5 @@
1
+ import { workItemNumber } from "../work-items/card-number.js";
1
2
  import { FACTORY_SESSION_NOTIFICATION_SOURCE, deliverFactorySessionNotification, resolveSessionThread } from "./deliver.js";
2
- import { workItemNumber } from "./read-tools.js";
3
3
  import { reportNotification, workItemReportAttributes, workItemReportRecipients } from "./reports.js";
4
4
  import { requirePerson } from "./scope.js";
5
5
  import { listSideSessions, sessionModel } from "./side-sessions.js";
@@ -1 +1 @@
1
- {"version":3,"file":"messaging-tools.js","names":[],"sources":["../../src/tools/messaging-tools.ts"],"sourcesContent":["/**\n * Messages between Factory sessions. A user session can message any session in\n * its Factory it can see; the receiver answers that exact message. Both\n * directions are `factory-session` notifications on the receiver's stored thread.\n */\n\nimport type {\n NotificationPriority,\n NotificationRecord,\n NotificationsStorage,\n SendNotificationSignalInput,\n} from '@mastra/core/notifications';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../integrations/base.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { SourceControlSession } from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport {\n FACTORY_SESSION_NOTIFICATION_SOURCE,\n deliverFactorySessionNotification,\n resolveSessionThread,\n} from './deliver.js';\nimport type { FactoryDeliveryController, FactoryDeliveryResult } from './deliver.js';\nimport { workItemNumber } from './read-tools.js';\nimport { reportNotification, workItemReportAttributes, workItemReportRecipients } from './reports.js';\nimport { requirePerson } from './scope.js';\nimport type { FactoryToolScope } from './scope.js';\nimport { listSideSessions, sessionModel } from './side-sessions.js';\n\n/** Messages plus replies, per sender session, per target thread, per window. */\nexport const SIGNAL_RATE_LIMIT = 10;\nexport const SIGNAL_RATE_WINDOW_MS = 10 * 60 * 1000;\n/** How many recent `factory-session` notifications on a thread the rate and duplicate checks read. */\nconst RECENT_SCAN = 100;\n/** How often a waiting queue is reconsidered. Delivery still waits for a free slot in the window. */\nconst QUEUE_FLUSH_MS = 1000;\n\n/** A message accepted past the delivery cap, held until the window has a free slot. */\ninterface PendingMessage {\n notification: Omit<SendNotificationSignalInput, 'source'>;\n /** When the sender handed it over. Oldest goes first. */\n acceptedAt: number;\n actor: { actorId: string; actorType: 'human' | 'agent' };\n}\n\ninterface QueuedDelivery extends PendingMessage {\n /** The moment a slot in the window is expected to free. Set once, when it joins the queue. */\n deliverAt: number;\n target: { sessionId: string; threadId: string };\n}\n\n/**\n * Waiting messages, per sender session and target thread, oldest first.\n * Process-local: a restart drops what was still waiting, the same as a message\n * that had not been handed to the tool yet. Delivered messages live in the\n * notification store and are unaffected.\n */\nconst pendingQueues = new Map<string, QueuedDelivery[]>();\nconst flushTimers = new Map<string, ReturnType<typeof setTimeout>>();\n\nconst queueOwners = new WeakMap<object, number>();\nlet nextQueueOwnerId = 0;\n\nconst queueKey = (owner: object, senderSessionId: string, threadId: string): string => {\n let id = queueOwners.get(owner);\n if (id === undefined) {\n nextQueueOwnerId += 1;\n id = nextQueueOwnerId;\n queueOwners.set(owner, id);\n }\n return `${id}\\0${senderSessionId}\\0${threadId}`;\n};\nexport interface FactoryMessaging {\n controller: FactoryDeliveryController;\n notifications: Pick<NotificationsStorage, 'listNotifications' | 'getNotification'>;\n}\n\nexport interface FactoryMessagingToolDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId' | 'listByOrigin' | 'setOriginMuted'>;\n workItems: Pick<\n WorkItemsStorage,\n | 'findActiveRunBindingForSession'\n | 'getForProject'\n | 'hasRunBindingForSession'\n | 'listSessionSubscriptions'\n | 'listRunBindings'\n | 'listWorkItemSubscribers'\n >;\n auditRecorder: AuditRecorder;\n /** The live controller and notifications store; resolved per call because they exist only once the mount is up. */\n messaging: () => Promise<FactoryMessaging | null>;\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\nconst message = z.string().trim().min(1).max(4000);\n\nfunction senderAttributes(scope: FactoryToolScope) {\n return {\n 'from-session': scope.sessionId,\n 'from-thread': scope.threadId,\n 'from-user': scope.userId,\n };\n}\n\nfunction unavailable(result: Extract<FactoryDeliveryResult, { delivered: 'skipped' }>) {\n return new Error(`The session is not available (${result.reason}).`);\n}\n\nexport function createFactoryMessagingTools(\n scope: FactoryToolScope,\n deps: FactoryMessagingToolDependencies,\n): IntegrationTools {\n const requireMessaging = async () => {\n const messaging = await deps.messaging();\n if (!messaging) throw new Error('Session messaging is not available on this server.');\n return messaging;\n };\n // Only a user-session turn the person started is the person's act. Workers\n // (even when someone types into one) and turns nobody signed in started\n // (wakes, webhooks) act as the thread's agent.\n const human = scope.kind === 'user' && scope.interactive;\n const audit = (input: { targetSessionId: string; priority: NotificationPriority; kind: string; delivery: string }) =>\n deps.auditRecorder.record({\n orgId: scope.orgId,\n actorId: human ? scope.userId : `agent:${scope.threadId}`,\n actorType: human ? 'human' : 'agent',\n action: 'factory.agent.signaled',\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'session', id: input.targetSessionId }],\n metadata: {\n targetSessionId: input.targetSessionId,\n priority: input.priority,\n kind: input.kind,\n delivery: input.delivery,\n },\n });\n /** Why this session can't reach `row`, or null when it can: the rule for message targets and reply targets alike. */\n const unreachable = (row: SourceControlSession | null): 'not-found' | 'private' | null => {\n if (!row || row.orgId !== scope.orgId || row.factoryProjectId !== scope.factoryProjectId) return 'not-found';\n if (row.visibility === 'private' && row.userId !== scope.userId) return 'private';\n return null;\n };\n const overRateLimit = (records: NotificationRecord[]) => countedInWindow(records).length >= SIGNAL_RATE_LIMIT;\n /** This session's delivered messages on the thread that still sit inside the window, oldest first. */\n const countedInWindow = (records: NotificationRecord[]): NotificationRecord[] => {\n const since = Date.now() - SIGNAL_RATE_WINDOW_MS;\n return records\n .filter(\n record =>\n // Everything this session sends counts except coalescing progress updates.\n record.kind !== 'progress' &&\n record.kind !== 'stage' &&\n record.attributes?.['from-session'] === scope.sessionId &&\n record.createdAt.getTime() >= since,\n )\n .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\n };\n /**\n * When the next message can be delivered: one window after the oldest message\n * that has to age out to free a slot, given how many are already waiting.\n */\n const nextDeliveryAt = (counted: NotificationRecord[], waiting: number): number => {\n const blocking = counted[counted.length + waiting - SIGNAL_RATE_LIMIT];\n return (blocking ? blocking.createdAt.getTime() : Date.now()) + SIGNAL_RATE_WINDOW_MS;\n };\n const queuedResult = (deliverAt: number) => ({\n delivered: 'queued' as const,\n deliverAt: new Date(deliverAt).toISOString(),\n note: `Queued; it will be delivered at about ${new Date(deliverAt).toISOString()}. Do not send it again.`,\n });\n const recent = (notifications: FactoryMessaging['notifications'], threadId: string) =>\n notifications.listNotifications({ threadId, source: FACTORY_SESSION_NOTIFICATION_SOURCE, limit: RECENT_SCAN });\n\n const actor = (): QueuedDelivery['actor'] => ({\n actorId: human ? scope.userId : `agent:${scope.threadId}`,\n actorType: human ? 'human' : 'agent',\n });\n\n /**\n * Deliver now, or hold until the window has a slot. The cap limits how fast\n * messages are delivered, not whether they are accepted.\n */\n const accept = async (\n messaging: FactoryMessaging,\n target: { sessionId: string; threadId: string },\n notification: Omit<SendNotificationSignalInput, 'source'>,\n ): Promise<\n { notificationId: string; delivered: FactoryDeliveryResult['delivered'] } | ReturnType<typeof queuedResult>\n > => {\n const counted = countedInWindow(await recent(messaging.notifications, target.threadId));\n if (counted.length < SIGNAL_RATE_LIMIT) {\n const result = await deliverFactorySessionNotification({\n controller: messaging.controller,\n sessions: deps.sessions,\n runs: deps.workItems,\n target,\n notification,\n });\n if (result.delivered === 'skipped') throw unavailable(result);\n await audit({\n targetSessionId: target.sessionId,\n priority: notification.priority ?? 'medium',\n kind: notification.kind,\n delivery: result.delivered,\n });\n return { notificationId: result.notificationId, delivered: result.delivered };\n }\n const key = queueKey(deps, scope.sessionId, target.threadId);\n const waiting = pendingQueues.get(key)?.length ?? 0;\n const deliverAt = nextDeliveryAt(counted, waiting);\n enqueue(key, {\n notification,\n acceptedAt: Date.now(),\n actor: actor(),\n deliverAt,\n target,\n });\n return queuedResult(deliverAt);\n };\n\n const enqueue = (key: string, delivery: QueuedDelivery): void => {\n const queue = pendingQueues.get(key) ?? [];\n queue.push(delivery);\n queue.sort((a, b) => a.acceptedAt - b.acceptedAt);\n pendingQueues.set(key, queue);\n scheduleFlush(key);\n };\n\n /**\n * Deliver the oldest waiting message once the window has a free slot, then\n * the next, in the order they were accepted. A target that is gone by then\n * is dropped and recorded, the same way an undeliverable live message is.\n */\n const flush = async (key: string): Promise<void> => {\n flushTimers.delete(key);\n const queue = pendingQueues.get(key);\n if (!queue || queue.length === 0) {\n pendingQueues.delete(key);\n return;\n }\n const messaging = await deps.messaging();\n if (!messaging) {\n scheduleFlush(key);\n return;\n }\n const head = queue[0];\n if (!head || head.deliverAt > Date.now()) {\n scheduleFlush(key);\n return;\n }\n const counted = countedInWindow(await recent(messaging.notifications, head.target.threadId));\n if (counted.length >= SIGNAL_RATE_LIMIT) {\n scheduleFlush(key);\n return;\n }\n queue.shift();\n if (queue.length === 0) pendingQueues.delete(key);\n const result = await deliverFactorySessionNotification({\n controller: messaging.controller,\n sessions: deps.sessions,\n runs: deps.workItems,\n target: head.target,\n notification: head.notification,\n });\n await deps.auditRecorder.record({\n orgId: scope.orgId,\n actorId: head.actor.actorId,\n actorType: head.actor.actorType,\n action: 'factory.agent.signaled',\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'session', id: head.target.sessionId }],\n metadata: {\n targetSessionId: head.target.sessionId,\n priority: head.notification.priority ?? 'medium',\n kind: head.notification.kind,\n delivery: result.delivered === 'skipped' ? 'dropped' : result.delivered,\n ...(result.delivered === 'skipped' ? { reason: result.reason } : {}),\n },\n });\n if (queue.length > 0) scheduleFlush(key);\n };\n\n function scheduleFlush(key: string): void {\n if (flushTimers.has(key)) return;\n if (!pendingQueues.get(key)?.[0]) return;\n const timer = setTimeout(() => {\n flushTimers.delete(key);\n void flush(key).catch(() => {\n // A failed flush leaves the rest of the queue waiting; the next tick retries the head.\n if ((pendingQueues.get(key)?.length ?? 0) > 0) scheduleFlush(key);\n });\n }, QUEUE_FLUSH_MS);\n // Keep the wait on the real clock. A fake clock that jumps the window would\n // skip a timer scheduled for the old deadline, and the message would sit.\n timer.unref?.();\n flushTimers.set(key, timer);\n }\n\n /** On turns nobody signed in started, only sessions working on items this session follows. */\n const followedWorkers = async () => {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n const follows = await deps.workItems.listSessionSubscriptions({ ...project, sessionId: scope.sessionId });\n const bindings = await Promise.all(\n follows.map(follow => deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId, follow.workItemId)),\n );\n const sideSessions = await deps.sessions.listByOrigin({ orgId: scope.orgId, originSessionId: scope.sessionId });\n return new Set([\n ...bindings\n .flat()\n .filter(binding => binding.status === 'active')\n .map(binding => binding.sessionId),\n ...sideSessions.map(session => session.sessionId),\n ]);\n };\n\n const workItemAttribute = async (sessionId: string, orgId: string, factoryProjectId: string) => {\n const binding = await deps.workItems.findActiveRunBindingForSession({ orgId, factoryProjectId, sessionId });\n if (!binding) return {};\n const item = await deps.workItems.getForProject(orgId, factoryProjectId, binding.workItemId);\n if (!item) return {};\n const number = workItemNumber(item);\n return { 'work-item': number === null ? item.id : `#${number}` };\n };\n\n const signal = createTool({\n id: 'factory_signal_session',\n description: [\n 'Send a message to another session in this Factory: a work item role session, or a teammate session you can see.',\n 'Replies come back to this session as `factory-session` notifications with kind `reply` and an `in-reply-to` attribute naming your message.',\n 'Priority `medium` (default) wakes an idle session and waits for a busy one to finish its step; use `urgent` only to make it stop and change course.',\n '`delivered` is `woken` when the session was idle and is now running, `mid-run` when it was already busy and will read the message when its run next checks in.',\n ...(scope.interactive\n ? []\n : ['On this turn you can only message your side sessions and sessions working on items this session follows.']),\n ].join(' '),\n inputSchema: z\n .object({\n sessionId: z.string().trim().min(1).max(200).describe('The session to message.'),\n message: message.describe('What to say. It arrives as-is, so make it self-contained.'),\n priority: z.enum(['low', 'medium', 'high', 'urgent']).default('medium'),\n })\n .strict(),\n execute: async ({ sessionId, message: text, priority }) => {\n if (sessionId === scope.sessionId) throw new Error(\"You can't message your own session.\");\n const row = await deps.sessions.getBySessionId(sessionId);\n const blocked = unreachable(row);\n if (blocked === 'not-found' || !row) throw new Error(`No session ${sessionId} was found in this Factory.`);\n if (blocked === 'private') throw new Error(`Session ${sessionId} is private to its owner.`);\n if (!scope.interactive && !(await followedWorkers()).has(sessionId)) {\n throw new Error(\n `On this turn you can only message this session's side sessions and sessions working on items it follows; ${sessionId} isn't one.`,\n );\n }\n\n const messaging = await requireMessaging();\n const threadId = await resolveSessionThread({\n controller: messaging.controller,\n sessions: deps.sessions,\n workItems: deps.workItems,\n sessionId,\n });\n if (!threadId) throw new Error('The session is not available (thread-not-found).');\n\n return accept(\n messaging,\n { sessionId, threadId },\n {\n kind: 'message',\n priority,\n summary: text,\n payload: { message: text },\n sourceId: scope.sessionId,\n attributes: {\n ...(await workItemAttribute(sessionId, row.orgId, scope.factoryProjectId)),\n ...senderAttributes(scope),\n },\n },\n );\n },\n });\n\n const reply = createTool({\n id: 'factory_message_origin',\n description: [\n 'Answer a message another Factory session sent you, or report on your work.',\n 'With `inReplyTo` (the id of a `factory-session` notification of kind `message`) the answer goes back to the session and thread that sent it; each message can be answered once.',\n 'Without it, the report goes to whoever follows your work: the session that started you, or everyone following your work item.',\n \"Set `status`: `progress` for an update, `blocked` when you need an answer to go on, `done` when finished, `failed` when you can't finish. Send one `done` or `failed` when you finish.\",\n ].join(' '),\n inputSchema: z\n .object({\n message: message.describe('Your answer.'),\n inReplyTo: z\n .string()\n .trim()\n .min(1)\n .max(200)\n .optional()\n .describe('Id of the message notification you are answering.'),\n status: z.enum(['progress', 'blocked', 'done', 'failed']).optional(),\n })\n .strict(),\n execute: async ({ message: text, inReplyTo, status }) => {\n if (!inReplyTo) return report(text, status);\n const messaging = await requireMessaging();\n // Only a message that reached this session's own thread can be answered,\n // and the answer goes where that message came from: never to an address\n // the model supplies.\n const original: NotificationRecord | null = await messaging.notifications.getNotification({\n threadId: scope.threadId,\n id: inReplyTo,\n });\n if (!original || original.source !== FACTORY_SESSION_NOTIFICATION_SOURCE) {\n throw new Error(`No message ${inReplyTo} was sent to this session.`);\n }\n if (original.kind !== 'message') {\n throw new Error(`Only messages can be answered; ${inReplyTo} is a ${original.kind}.`);\n }\n const fromSession = original.attributes?.['from-session'];\n const fromThread = original.attributes?.['from-thread'];\n if (typeof fromSession !== 'string' || typeof fromThread !== 'string' || original.sourceId !== fromSession) {\n throw new Error(`Message ${inReplyTo} doesn't say which session sent it.`);\n }\n // Notification records can be written outside these tools, so the\n // sender they name gets the same checks a message to it would.\n const blocked = unreachable(await deps.sessions.getBySessionId(fromSession));\n if (blocked === 'not-found') throw new Error(`Message ${inReplyTo} didn't come from a session in this Factory.`);\n if (blocked === 'private') {\n throw new Error(`Message ${inReplyTo} came from a private session this session can't answer.`);\n }\n const onSenderThread = await recent(messaging.notifications, fromThread);\n // Replies count toward the same cap as messages, so records written to\n // this session can't turn it into an unlimited high-priority sender.\n const answered = onSenderThread.some(\n record =>\n record.kind === 'reply' &&\n record.attributes?.['in-reply-to'] === inReplyTo &&\n record.attributes?.['from-session'] === scope.sessionId,\n );\n if (answered) throw new Error(`You already answered ${inReplyTo}.`);\n\n return accept(\n messaging,\n { sessionId: fromSession, threadId: fromThread },\n {\n kind: 'reply',\n priority: 'high',\n summary: text,\n payload: { message: text },\n sourceId: scope.sessionId,\n attributes: {\n ...senderAttributes(scope),\n 'in-reply-to': inReplyTo,\n ...(status ? { status } : {}),\n },\n },\n );\n },\n });\n\n /** A report with no message to answer: to the origin, else to the item's followers. */\n async function report(text: string, status: 'progress' | 'blocked' | 'done' | 'failed' | undefined) {\n const sender = { sessionId: scope.sessionId, threadId: scope.threadId, userId: scope.userId };\n let recipients: Array<{ sessionId: string; threadId: string }>;\n let attributes: Record<string, string> = {};\n if (scope.origin) {\n // The origin can mute this side session; the session keeps working, its reports just stop.\n // Blocked reports still go through, since the session cannot go on until the origin answers.\n const row = await deps.sessions.getBySessionId(scope.sessionId);\n if (row?.originMutedAt && status !== 'blocked') {\n return { delivered: 0, recipients: [], muted: true, note: 'Your origin muted your reports; keep working.' };\n }\n recipients = [scope.origin];\n } else {\n const binding = await deps.workItems.findActiveRunBindingForSession({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId: scope.sessionId,\n });\n if (!binding) throw new Error('Nothing started this session; pass inReplyTo to answer a message.');\n recipients = await workItemReportRecipients(deps.workItems, {\n orgId: scope.orgId,\n workItemId: binding.workItemId,\n senderSessionId: scope.sessionId,\n });\n ({ attributes } = await workItemReportAttributes(deps.workItems, {\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n workItemId: binding.workItemId,\n role: binding.role,\n }));\n }\n if (recipients.length === 0) return { delivered: 0, recipients: [] };\n\n const messaging = await requireMessaging();\n const notification = reportNotification({ sender, status, message: text, attributes });\n const results: Array<{\n sessionId: string;\n delivered: FactoryDeliveryResult['delivered'] | 'queued';\n reason?: string;\n deliverAt?: string;\n }> = [];\n for (const recipient of recipients) {\n // Progress replaces itself while unread; anything else can wake a follower, so it counts.\n if (status !== 'progress' && overRateLimit(await recent(messaging.notifications, recipient.threadId))) {\n const counted = countedInWindow(await recent(messaging.notifications, recipient.threadId));\n const key = queueKey(deps, scope.sessionId, recipient.threadId);\n const waiting = pendingQueues.get(key)?.length ?? 0;\n const at = nextDeliveryAt(counted, waiting);\n enqueue(key, {\n notification,\n acceptedAt: Date.now(),\n actor: actor(),\n deliverAt: at,\n target: recipient,\n });\n results.push({\n sessionId: recipient.sessionId,\n delivered: 'queued',\n deliverAt: new Date(at).toISOString(),\n });\n continue;\n }\n const result = await deliverFactorySessionNotification({\n controller: messaging.controller,\n sessions: deps.sessions,\n runs: deps.workItems,\n target: recipient,\n notification,\n });\n results.push({ sessionId: recipient.sessionId, delivered: result.delivered });\n if (result.delivered === 'skipped') continue;\n await audit({\n targetSessionId: recipient.sessionId,\n priority: notification.priority ?? 'high',\n kind: notification.kind,\n delivery: result.delivered,\n });\n }\n const delivered = results.filter(result => result.delivered !== 'skipped' && result.delivered !== 'queued').length;\n const queued = results.filter(result => result.delivered === 'queued').length;\n return {\n delivered,\n recipients: results,\n ...(queued > 0\n ? {\n queued,\n note: 'Queued past the delivery cap. It will be delivered when the window allows. Do not send it again.',\n }\n : {}),\n };\n }\n\n const listSide = createTool({\n id: 'factory_list_side_sessions',\n description: [\n 'List the side sessions this session started with factory_start_session: state (running, parked waiting on an answer, idle), last report, whether you muted it, its model, and the work item it works on.',\n 'Use the session ids with factory_signal_session and factory_switch_session_model. On a turn a person started, also with factory_answer_approval, factory_unsubscribe_session and factory_subscribe_session.',\n ].join(' '),\n inputSchema: z\n .object({\n state: z.enum(['running', 'parked', 'idle']).optional().describe('Only sessions in this state.'),\n muted: z.boolean().optional().describe('true for only muted sessions, false for only unmuted ones.'),\n })\n .strict(),\n execute: async ({ state, muted }) => {\n const messaging = await deps.messaging();\n const sessions = await listSideSessions(\n {\n sessions: deps.sessions,\n workItems: deps.workItems,\n notifications: messaging?.notifications ?? null,\n isRunning: async sessionId => (await messaging?.controller.getSession(sessionId))?.stream.isActive() ?? false,\n isParked: sessionId => deps.liveSessions?.()?.parked(sessionId) !== undefined,\n model: messaging\n ? sessionId => sessionModel(messaging.controller, deps.sessions, deps.workItems, sessionId)\n : undefined,\n },\n scope,\n );\n return {\n sessions: sessions.filter(\n row => (!state || row.state === state) && (muted === undefined || (row.mutedAt !== null) === muted),\n ),\n };\n },\n });\n\n /** A side session this session started, or an error naming why it isn't one. */\n const ownSideSession = async (sessionId: string) => {\n const row = await deps.sessions.getBySessionId(sessionId);\n if (\n !row ||\n row.orgId !== scope.orgId ||\n row.factoryProjectId !== scope.factoryProjectId ||\n row.originSessionId !== scope.sessionId\n ) {\n throw new Error(`Session ${sessionId} is not a side session you started; see factory_list_side_sessions.`);\n }\n return row;\n };\n const sideSessionId = z\n .string()\n .trim()\n .min(1)\n .max(200)\n .describe('The side session, from factory_list_side_sessions.');\n\n const unsubscribe = createTool({\n id: 'factory_unsubscribe_session',\n description:\n \"Mute a side session you started: its reports and run-end notices stop reaching you, but it keeps working. Approval requests and blocked reports still arrive, since the session can't go on without an answer. Undo with factory_subscribe_session. Only on a turn a person started.\",\n inputSchema: z.object({ sessionId: sideSessionId }).strict(),\n execute: async ({ sessionId }) => {\n requirePerson(scope, 'mute a side session');\n const row = await ownSideSession(sessionId);\n if (row.originMutedAt) return { sessionId, muted: true, mutedAt: row.originMutedAt.toISOString() };\n await deps.sessions.setOriginMuted({ sessionId, muted: true });\n const updated = await deps.sessions.getBySessionId(sessionId);\n return { sessionId, muted: true, mutedAt: updated?.originMutedAt?.toISOString() ?? null };\n },\n });\n\n const subscribe = createTool({\n id: 'factory_subscribe_session',\n description:\n 'Unmute a side session you muted with factory_unsubscribe_session, so its reports reach you again. Reports it sent while muted are not replayed. Only on a turn a person started.',\n inputSchema: z.object({ sessionId: sideSessionId }).strict(),\n execute: async ({ sessionId }) => {\n requirePerson(scope, 'unmute a side session');\n const row = await ownSideSession(sessionId);\n if (row.originMutedAt) await deps.sessions.setOriginMuted({ sessionId, muted: false });\n return { sessionId, muted: false };\n },\n });\n\n if (scope.kind === 'worker') return { factory_message_origin: reply };\n return {\n factory_signal_session: signal,\n factory_message_origin: reply,\n factory_list_side_sessions: listSide,\n factory_unsubscribe_session: unsubscribe,\n factory_subscribe_session: subscribe,\n };\n}\n"],"mappings":";;;;;;;;;AAkCA,MAAa,oBAAoB;AACjC,MAAa,wBAAwB;;AAErC,MAAM,cAAc;;AAEpB,MAAM,iBAAiB;;;;;;;AAsBvB,MAAM,gCAAgB,IAAI,IAA8B;AACxD,MAAM,8BAAc,IAAI,IAA2C;AAEnE,MAAM,8BAAc,IAAI,QAAwB;AAChD,IAAI,mBAAmB;AAEvB,MAAM,YAAY,OAAe,iBAAyB,aAA6B;CACrF,IAAI,KAAK,YAAY,IAAI,KAAK;CAC9B,IAAI,OAAO,KAAA,GAAW;EACpB,oBAAoB;EACpB,KAAK;EACL,YAAY,IAAI,OAAO,EAAE;CAC3B;CACA,OAAO,GAAG,GAAG,IAAI,gBAAgB,IAAI;AACvC;AAwBA,MAAM,UAAU,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAI;AAEjD,SAAS,iBAAiB,OA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":"messaging-tools.js","names":[],"sources":["../../src/tools/messaging-tools.ts"],"sourcesContent":["/**\n * Messages between Factory sessions. A user session can message any session in\n * its Factory it can see; the receiver answers that exact message. Both\n * directions are `factory-session` notifications on the receiver's stored thread.\n */\n\nimport type {\n NotificationPriority,\n NotificationRecord,\n NotificationsStorage,\n SendNotificationSignalInput,\n} from '@mastra/core/notifications';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../integrations/base.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { SourceControlSession } from '../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { workItemNumber } from '../work-items/card-number.js';\nimport {\n FACTORY_SESSION_NOTIFICATION_SOURCE,\n deliverFactorySessionNotification,\n resolveSessionThread,\n} from './deliver.js';\nimport type { FactoryDeliveryController, FactoryDeliveryResult } from './deliver.js';\nimport { reportNotification, workItemReportAttributes, workItemReportRecipients } from './reports.js';\nimport { requirePerson } from './scope.js';\nimport type { FactoryToolScope } from './scope.js';\nimport { listSideSessions, sessionModel } from './side-sessions.js';\n\n/** Messages plus replies, per sender session, per target thread, per window. */\nexport const SIGNAL_RATE_LIMIT = 10;\nexport const SIGNAL_RATE_WINDOW_MS = 10 * 60 * 1000;\n/** How many recent `factory-session` notifications on a thread the rate and duplicate checks read. */\nconst RECENT_SCAN = 100;\n/** How often a waiting queue is reconsidered. Delivery still waits for a free slot in the window. */\nconst QUEUE_FLUSH_MS = 1000;\n\n/** A message accepted past the delivery cap, held until the window has a free slot. */\ninterface PendingMessage {\n notification: Omit<SendNotificationSignalInput, 'source'>;\n /** When the sender handed it over. Oldest goes first. */\n acceptedAt: number;\n actor: { actorId: string; actorType: 'human' | 'agent' };\n}\n\ninterface QueuedDelivery extends PendingMessage {\n /** The moment a slot in the window is expected to free. Set once, when it joins the queue. */\n deliverAt: number;\n target: { sessionId: string; threadId: string };\n}\n\n/**\n * Waiting messages, per sender session and target thread, oldest first.\n * Process-local: a restart drops what was still waiting, the same as a message\n * that had not been handed to the tool yet. Delivered messages live in the\n * notification store and are unaffected.\n */\nconst pendingQueues = new Map<string, QueuedDelivery[]>();\nconst flushTimers = new Map<string, ReturnType<typeof setTimeout>>();\n\nconst queueOwners = new WeakMap<object, number>();\nlet nextQueueOwnerId = 0;\n\nconst queueKey = (owner: object, senderSessionId: string, threadId: string): string => {\n let id = queueOwners.get(owner);\n if (id === undefined) {\n nextQueueOwnerId += 1;\n id = nextQueueOwnerId;\n queueOwners.set(owner, id);\n }\n return `${id}\\0${senderSessionId}\\0${threadId}`;\n};\nexport interface FactoryMessaging {\n controller: FactoryDeliveryController;\n notifications: Pick<NotificationsStorage, 'listNotifications' | 'getNotification'>;\n}\n\nexport interface FactoryMessagingToolDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId' | 'listByOrigin' | 'setOriginMuted'>;\n workItems: Pick<\n WorkItemsStorage,\n | 'findActiveRunBindingForSession'\n | 'getForProject'\n | 'hasRunBindingForSession'\n | 'listSessionSubscriptions'\n | 'listRunBindings'\n | 'listWorkItemSubscribers'\n >;\n auditRecorder: AuditRecorder;\n /** The live controller and notifications store; resolved per call because they exist only once the mount is up. */\n messaging: () => Promise<FactoryMessaging | null>;\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\nconst message = z.string().trim().min(1).max(4000);\n\nfunction senderAttributes(scope: FactoryToolScope) {\n return {\n 'from-session': scope.sessionId,\n 'from-thread': scope.threadId,\n 'from-user': scope.userId,\n };\n}\n\nfunction unavailable(result: Extract<FactoryDeliveryResult, { delivered: 'skipped' }>) {\n return new Error(`The session is not available (${result.reason}).`);\n}\n\nexport function createFactoryMessagingTools(\n scope: FactoryToolScope,\n deps: FactoryMessagingToolDependencies,\n): IntegrationTools {\n const requireMessaging = async () => {\n const messaging = await deps.messaging();\n if (!messaging) throw new Error('Session messaging is not available on this server.');\n return messaging;\n };\n // Only a user-session turn the person started is the person's act. Workers\n // (even when someone types into one) and turns nobody signed in started\n // (wakes, webhooks) act as the thread's agent.\n const human = scope.kind === 'user' && scope.interactive;\n const audit = (input: { targetSessionId: string; priority: NotificationPriority; kind: string; delivery: string }) =>\n deps.auditRecorder.record({\n orgId: scope.orgId,\n actorId: human ? scope.userId : `agent:${scope.threadId}`,\n actorType: human ? 'human' : 'agent',\n action: 'factory.agent.signaled',\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'session', id: input.targetSessionId }],\n metadata: {\n targetSessionId: input.targetSessionId,\n priority: input.priority,\n kind: input.kind,\n delivery: input.delivery,\n },\n });\n /** Why this session can't reach `row`, or null when it can: the rule for message targets and reply targets alike. */\n const unreachable = (row: SourceControlSession | null): 'not-found' | 'private' | null => {\n if (!row || row.orgId !== scope.orgId || row.factoryProjectId !== scope.factoryProjectId) return 'not-found';\n if (row.visibility === 'private' && row.userId !== scope.userId) return 'private';\n return null;\n };\n const overRateLimit = (records: NotificationRecord[]) => countedInWindow(records).length >= SIGNAL_RATE_LIMIT;\n /** This session's delivered messages on the thread that still sit inside the window, oldest first. */\n const countedInWindow = (records: NotificationRecord[]): NotificationRecord[] => {\n const since = Date.now() - SIGNAL_RATE_WINDOW_MS;\n return records\n .filter(\n record =>\n // Everything this session sends counts except coalescing progress updates.\n record.kind !== 'progress' &&\n record.kind !== 'stage' &&\n record.attributes?.['from-session'] === scope.sessionId &&\n record.createdAt.getTime() >= since,\n )\n .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\n };\n /**\n * When the next message can be delivered: one window after the oldest message\n * that has to age out to free a slot, given how many are already waiting.\n */\n const nextDeliveryAt = (counted: NotificationRecord[], waiting: number): number => {\n const blocking = counted[counted.length + waiting - SIGNAL_RATE_LIMIT];\n return (blocking ? blocking.createdAt.getTime() : Date.now()) + SIGNAL_RATE_WINDOW_MS;\n };\n const queuedResult = (deliverAt: number) => ({\n delivered: 'queued' as const,\n deliverAt: new Date(deliverAt).toISOString(),\n note: `Queued; it will be delivered at about ${new Date(deliverAt).toISOString()}. Do not send it again.`,\n });\n const recent = (notifications: FactoryMessaging['notifications'], threadId: string) =>\n notifications.listNotifications({ threadId, source: FACTORY_SESSION_NOTIFICATION_SOURCE, limit: RECENT_SCAN });\n\n const actor = (): QueuedDelivery['actor'] => ({\n actorId: human ? scope.userId : `agent:${scope.threadId}`,\n actorType: human ? 'human' : 'agent',\n });\n\n /**\n * Deliver now, or hold until the window has a slot. The cap limits how fast\n * messages are delivered, not whether they are accepted.\n */\n const accept = async (\n messaging: FactoryMessaging,\n target: { sessionId: string; threadId: string },\n notification: Omit<SendNotificationSignalInput, 'source'>,\n ): Promise<\n { notificationId: string; delivered: FactoryDeliveryResult['delivered'] } | ReturnType<typeof queuedResult>\n > => {\n const counted = countedInWindow(await recent(messaging.notifications, target.threadId));\n if (counted.length < SIGNAL_RATE_LIMIT) {\n const result = await deliverFactorySessionNotification({\n controller: messaging.controller,\n sessions: deps.sessions,\n runs: deps.workItems,\n target,\n notification,\n });\n if (result.delivered === 'skipped') throw unavailable(result);\n await audit({\n targetSessionId: target.sessionId,\n priority: notification.priority ?? 'medium',\n kind: notification.kind,\n delivery: result.delivered,\n });\n return { notificationId: result.notificationId, delivered: result.delivered };\n }\n const key = queueKey(deps, scope.sessionId, target.threadId);\n const waiting = pendingQueues.get(key)?.length ?? 0;\n const deliverAt = nextDeliveryAt(counted, waiting);\n enqueue(key, {\n notification,\n acceptedAt: Date.now(),\n actor: actor(),\n deliverAt,\n target,\n });\n return queuedResult(deliverAt);\n };\n\n const enqueue = (key: string, delivery: QueuedDelivery): void => {\n const queue = pendingQueues.get(key) ?? [];\n queue.push(delivery);\n queue.sort((a, b) => a.acceptedAt - b.acceptedAt);\n pendingQueues.set(key, queue);\n scheduleFlush(key);\n };\n\n /**\n * Deliver the oldest waiting message once the window has a free slot, then\n * the next, in the order they were accepted. A target that is gone by then\n * is dropped and recorded, the same way an undeliverable live message is.\n */\n const flush = async (key: string): Promise<void> => {\n flushTimers.delete(key);\n const queue = pendingQueues.get(key);\n if (!queue || queue.length === 0) {\n pendingQueues.delete(key);\n return;\n }\n const messaging = await deps.messaging();\n if (!messaging) {\n scheduleFlush(key);\n return;\n }\n const head = queue[0];\n if (!head || head.deliverAt > Date.now()) {\n scheduleFlush(key);\n return;\n }\n const counted = countedInWindow(await recent(messaging.notifications, head.target.threadId));\n if (counted.length >= SIGNAL_RATE_LIMIT) {\n scheduleFlush(key);\n return;\n }\n queue.shift();\n if (queue.length === 0) pendingQueues.delete(key);\n const result = await deliverFactorySessionNotification({\n controller: messaging.controller,\n sessions: deps.sessions,\n runs: deps.workItems,\n target: head.target,\n notification: head.notification,\n });\n await deps.auditRecorder.record({\n orgId: scope.orgId,\n actorId: head.actor.actorId,\n actorType: head.actor.actorType,\n action: 'factory.agent.signaled',\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'session', id: head.target.sessionId }],\n metadata: {\n targetSessionId: head.target.sessionId,\n priority: head.notification.priority ?? 'medium',\n kind: head.notification.kind,\n delivery: result.delivered === 'skipped' ? 'dropped' : result.delivered,\n ...(result.delivered === 'skipped' ? { reason: result.reason } : {}),\n },\n });\n if (queue.length > 0) scheduleFlush(key);\n };\n\n function scheduleFlush(key: string): void {\n if (flushTimers.has(key)) return;\n if (!pendingQueues.get(key)?.[0]) return;\n const timer = setTimeout(() => {\n flushTimers.delete(key);\n void flush(key).catch(() => {\n // A failed flush leaves the rest of the queue waiting; the next tick retries the head.\n if ((pendingQueues.get(key)?.length ?? 0) > 0) scheduleFlush(key);\n });\n }, QUEUE_FLUSH_MS);\n // Keep the wait on the real clock. A fake clock that jumps the window would\n // skip a timer scheduled for the old deadline, and the message would sit.\n timer.unref?.();\n flushTimers.set(key, timer);\n }\n\n /** On turns nobody signed in started, only sessions working on items this session follows. */\n const followedWorkers = async () => {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n const follows = await deps.workItems.listSessionSubscriptions({ ...project, sessionId: scope.sessionId });\n const bindings = await Promise.all(\n follows.map(follow => deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId, follow.workItemId)),\n );\n const sideSessions = await deps.sessions.listByOrigin({ orgId: scope.orgId, originSessionId: scope.sessionId });\n return new Set([\n ...bindings\n .flat()\n .filter(binding => binding.status === 'active')\n .map(binding => binding.sessionId),\n ...sideSessions.map(session => session.sessionId),\n ]);\n };\n\n const workItemAttribute = async (sessionId: string, orgId: string, factoryProjectId: string) => {\n const binding = await deps.workItems.findActiveRunBindingForSession({ orgId, factoryProjectId, sessionId });\n if (!binding) return {};\n const item = await deps.workItems.getForProject(orgId, factoryProjectId, binding.workItemId);\n if (!item) return {};\n const number = workItemNumber(item);\n return { 'work-item': number === null ? item.id : `#${number}` };\n };\n\n const signal = createTool({\n id: 'factory_signal_session',\n description: [\n 'Send a message to another session in this Factory: a work item role session, or a teammate session you can see.',\n 'Replies come back to this session as `factory-session` notifications with kind `reply` and an `in-reply-to` attribute naming your message.',\n 'Priority `medium` (default) wakes an idle session and waits for a busy one to finish its step; use `urgent` only to make it stop and change course.',\n '`delivered` is `woken` when the session was idle and is now running, `mid-run` when it was already busy and will read the message when its run next checks in.',\n ...(scope.interactive\n ? []\n : ['On this turn you can only message your side sessions and sessions working on items this session follows.']),\n ].join(' '),\n inputSchema: z\n .object({\n sessionId: z.string().trim().min(1).max(200).describe('The session to message.'),\n message: message.describe('What to say. It arrives as-is, so make it self-contained.'),\n priority: z.enum(['low', 'medium', 'high', 'urgent']).default('medium'),\n })\n .strict(),\n execute: async ({ sessionId, message: text, priority }) => {\n if (sessionId === scope.sessionId) throw new Error(\"You can't message your own session.\");\n const row = await deps.sessions.getBySessionId(sessionId);\n const blocked = unreachable(row);\n if (blocked === 'not-found' || !row) throw new Error(`No session ${sessionId} was found in this Factory.`);\n if (blocked === 'private') throw new Error(`Session ${sessionId} is private to its owner.`);\n if (!scope.interactive && !(await followedWorkers()).has(sessionId)) {\n throw new Error(\n `On this turn you can only message this session's side sessions and sessions working on items it follows; ${sessionId} isn't one.`,\n );\n }\n\n const messaging = await requireMessaging();\n const threadId = await resolveSessionThread({\n controller: messaging.controller,\n sessions: deps.sessions,\n workItems: deps.workItems,\n sessionId,\n });\n if (!threadId) throw new Error('The session is not available (thread-not-found).');\n\n return accept(\n messaging,\n { sessionId, threadId },\n {\n kind: 'message',\n priority,\n summary: text,\n payload: { message: text },\n sourceId: scope.sessionId,\n attributes: {\n ...(await workItemAttribute(sessionId, row.orgId, scope.factoryProjectId)),\n ...senderAttributes(scope),\n },\n },\n );\n },\n });\n\n const reply = createTool({\n id: 'factory_message_origin',\n description: [\n 'Answer a message another Factory session sent you, or report on your work.',\n 'With `inReplyTo` (the id of a `factory-session` notification of kind `message`) the answer goes back to the session and thread that sent it; each message can be answered once.',\n 'Without it, the report goes to whoever follows your work: the session that started you, or everyone following your work item.',\n \"Set `status`: `progress` for an update, `blocked` when you need an answer to go on, `done` when finished, `failed` when you can't finish. Send one `done` or `failed` when you finish.\",\n ].join(' '),\n inputSchema: z\n .object({\n message: message.describe('Your answer.'),\n inReplyTo: z\n .string()\n .trim()\n .min(1)\n .max(200)\n .optional()\n .describe('Id of the message notification you are answering.'),\n status: z.enum(['progress', 'blocked', 'done', 'failed']).optional(),\n })\n .strict(),\n execute: async ({ message: text, inReplyTo, status }) => {\n if (!inReplyTo) return report(text, status);\n const messaging = await requireMessaging();\n // Only a message that reached this session's own thread can be answered,\n // and the answer goes where that message came from: never to an address\n // the model supplies.\n const original: NotificationRecord | null = await messaging.notifications.getNotification({\n threadId: scope.threadId,\n id: inReplyTo,\n });\n if (!original || original.source !== FACTORY_SESSION_NOTIFICATION_SOURCE) {\n throw new Error(`No message ${inReplyTo} was sent to this session.`);\n }\n if (original.kind !== 'message') {\n throw new Error(`Only messages can be answered; ${inReplyTo} is a ${original.kind}.`);\n }\n const fromSession = original.attributes?.['from-session'];\n const fromThread = original.attributes?.['from-thread'];\n if (typeof fromSession !== 'string' || typeof fromThread !== 'string' || original.sourceId !== fromSession) {\n throw new Error(`Message ${inReplyTo} doesn't say which session sent it.`);\n }\n // Notification records can be written outside these tools, so the\n // sender they name gets the same checks a message to it would.\n const blocked = unreachable(await deps.sessions.getBySessionId(fromSession));\n if (blocked === 'not-found') throw new Error(`Message ${inReplyTo} didn't come from a session in this Factory.`);\n if (blocked === 'private') {\n throw new Error(`Message ${inReplyTo} came from a private session this session can't answer.`);\n }\n const onSenderThread = await recent(messaging.notifications, fromThread);\n // Replies count toward the same cap as messages, so records written to\n // this session can't turn it into an unlimited high-priority sender.\n const answered = onSenderThread.some(\n record =>\n record.kind === 'reply' &&\n record.attributes?.['in-reply-to'] === inReplyTo &&\n record.attributes?.['from-session'] === scope.sessionId,\n );\n if (answered) throw new Error(`You already answered ${inReplyTo}.`);\n\n return accept(\n messaging,\n { sessionId: fromSession, threadId: fromThread },\n {\n kind: 'reply',\n priority: 'high',\n summary: text,\n payload: { message: text },\n sourceId: scope.sessionId,\n attributes: {\n ...senderAttributes(scope),\n 'in-reply-to': inReplyTo,\n ...(status ? { status } : {}),\n },\n },\n );\n },\n });\n\n /** A report with no message to answer: to the origin, else to the item's followers. */\n async function report(text: string, status: 'progress' | 'blocked' | 'done' | 'failed' | undefined) {\n const sender = { sessionId: scope.sessionId, threadId: scope.threadId, userId: scope.userId };\n let recipients: Array<{ sessionId: string; threadId: string }>;\n let attributes: Record<string, string> = {};\n if (scope.origin) {\n // The origin can mute this side session; the session keeps working, its reports just stop.\n // Blocked reports still go through, since the session cannot go on until the origin answers.\n const row = await deps.sessions.getBySessionId(scope.sessionId);\n if (row?.originMutedAt && status !== 'blocked') {\n return { delivered: 0, recipients: [], muted: true, note: 'Your origin muted your reports; keep working.' };\n }\n recipients = [scope.origin];\n } else {\n const binding = await deps.workItems.findActiveRunBindingForSession({\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId: scope.sessionId,\n });\n if (!binding) throw new Error('Nothing started this session; pass inReplyTo to answer a message.');\n recipients = await workItemReportRecipients(deps.workItems, {\n orgId: scope.orgId,\n workItemId: binding.workItemId,\n senderSessionId: scope.sessionId,\n });\n ({ attributes } = await workItemReportAttributes(deps.workItems, {\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n workItemId: binding.workItemId,\n role: binding.role,\n }));\n }\n if (recipients.length === 0) return { delivered: 0, recipients: [] };\n\n const messaging = await requireMessaging();\n const notification = reportNotification({ sender, status, message: text, attributes });\n const results: Array<{\n sessionId: string;\n delivered: FactoryDeliveryResult['delivered'] | 'queued';\n reason?: string;\n deliverAt?: string;\n }> = [];\n for (const recipient of recipients) {\n // Progress replaces itself while unread; anything else can wake a follower, so it counts.\n if (status !== 'progress' && overRateLimit(await recent(messaging.notifications, recipient.threadId))) {\n const counted = countedInWindow(await recent(messaging.notifications, recipient.threadId));\n const key = queueKey(deps, scope.sessionId, recipient.threadId);\n const waiting = pendingQueues.get(key)?.length ?? 0;\n const at = nextDeliveryAt(counted, waiting);\n enqueue(key, {\n notification,\n acceptedAt: Date.now(),\n actor: actor(),\n deliverAt: at,\n target: recipient,\n });\n results.push({\n sessionId: recipient.sessionId,\n delivered: 'queued',\n deliverAt: new Date(at).toISOString(),\n });\n continue;\n }\n const result = await deliverFactorySessionNotification({\n controller: messaging.controller,\n sessions: deps.sessions,\n runs: deps.workItems,\n target: recipient,\n notification,\n });\n results.push({ sessionId: recipient.sessionId, delivered: result.delivered });\n if (result.delivered === 'skipped') continue;\n await audit({\n targetSessionId: recipient.sessionId,\n priority: notification.priority ?? 'high',\n kind: notification.kind,\n delivery: result.delivered,\n });\n }\n const delivered = results.filter(result => result.delivered !== 'skipped' && result.delivered !== 'queued').length;\n const queued = results.filter(result => result.delivered === 'queued').length;\n return {\n delivered,\n recipients: results,\n ...(queued > 0\n ? {\n queued,\n note: 'Queued past the delivery cap. It will be delivered when the window allows. Do not send it again.',\n }\n : {}),\n };\n }\n\n const listSide = createTool({\n id: 'factory_list_side_sessions',\n description: [\n 'List the side sessions this session started with factory_start_session: state (running, parked waiting on an answer, idle), last report, whether you muted it, its model, and the work item it works on.',\n 'Use the session ids with factory_signal_session and factory_switch_session_model. On a turn a person started, also with factory_answer_approval, factory_unsubscribe_session and factory_subscribe_session.',\n ].join(' '),\n inputSchema: z\n .object({\n state: z.enum(['running', 'parked', 'idle']).optional().describe('Only sessions in this state.'),\n muted: z.boolean().optional().describe('true for only muted sessions, false for only unmuted ones.'),\n })\n .strict(),\n execute: async ({ state, muted }) => {\n const messaging = await deps.messaging();\n const sessions = await listSideSessions(\n {\n sessions: deps.sessions,\n workItems: deps.workItems,\n notifications: messaging?.notifications ?? null,\n isRunning: async sessionId => (await messaging?.controller.getSession(sessionId))?.stream.isActive() ?? false,\n isParked: sessionId => deps.liveSessions?.()?.parked(sessionId) !== undefined,\n model: messaging\n ? sessionId => sessionModel(messaging.controller, deps.sessions, deps.workItems, sessionId)\n : undefined,\n },\n scope,\n );\n return {\n sessions: sessions.filter(\n row => (!state || row.state === state) && (muted === undefined || (row.mutedAt !== null) === muted),\n ),\n };\n },\n });\n\n /** A side session this session started, or an error naming why it isn't one. */\n const ownSideSession = async (sessionId: string) => {\n const row = await deps.sessions.getBySessionId(sessionId);\n if (\n !row ||\n row.orgId !== scope.orgId ||\n row.factoryProjectId !== scope.factoryProjectId ||\n row.originSessionId !== scope.sessionId\n ) {\n throw new Error(`Session ${sessionId} is not a side session you started; see factory_list_side_sessions.`);\n }\n return row;\n };\n const sideSessionId = z\n .string()\n .trim()\n .min(1)\n .max(200)\n .describe('The side session, from factory_list_side_sessions.');\n\n const unsubscribe = createTool({\n id: 'factory_unsubscribe_session',\n description:\n \"Mute a side session you started: its reports and run-end notices stop reaching you, but it keeps working. Approval requests and blocked reports still arrive, since the session can't go on without an answer. Undo with factory_subscribe_session. Only on a turn a person started.\",\n inputSchema: z.object({ sessionId: sideSessionId }).strict(),\n execute: async ({ sessionId }) => {\n requirePerson(scope, 'mute a side session');\n const row = await ownSideSession(sessionId);\n if (row.originMutedAt) return { sessionId, muted: true, mutedAt: row.originMutedAt.toISOString() };\n await deps.sessions.setOriginMuted({ sessionId, muted: true });\n const updated = await deps.sessions.getBySessionId(sessionId);\n return { sessionId, muted: true, mutedAt: updated?.originMutedAt?.toISOString() ?? null };\n },\n });\n\n const subscribe = createTool({\n id: 'factory_subscribe_session',\n description:\n 'Unmute a side session you muted with factory_unsubscribe_session, so its reports reach you again. Reports it sent while muted are not replayed. Only on a turn a person started.',\n inputSchema: z.object({ sessionId: sideSessionId }).strict(),\n execute: async ({ sessionId }) => {\n requirePerson(scope, 'unmute a side session');\n const row = await ownSideSession(sessionId);\n if (row.originMutedAt) await deps.sessions.setOriginMuted({ sessionId, muted: false });\n return { sessionId, muted: false };\n },\n });\n\n if (scope.kind === 'worker') return { factory_message_origin: reply };\n return {\n factory_signal_session: signal,\n factory_message_origin: reply,\n factory_list_side_sessions: listSide,\n factory_unsubscribe_session: unsubscribe,\n factory_subscribe_session: subscribe,\n };\n}\n"],"mappings":";;;;;;;;;AAkCA,MAAa,oBAAoB;AACjC,MAAa,wBAAwB;;AAErC,MAAM,cAAc;;AAEpB,MAAM,iBAAiB;;;;;;;AAsBvB,MAAM,gCAAgB,IAAI,IAA8B;AACxD,MAAM,8BAAc,IAAI,IAA2C;AAEnE,MAAM,8BAAc,IAAI,QAAwB;AAChD,IAAI,mBAAmB;AAEvB,MAAM,YAAY,OAAe,iBAAyB,aAA6B;CACrF,IAAI,KAAK,YAAY,IAAI,KAAK;CAC9B,IAAI,OAAO,KAAA,GAAW;EACpB,oBAAoB;EACpB,KAAK;EACL,YAAY,IAAI,OAAO,EAAE;CAC3B;CACA,OAAO,GAAG,GAAG,IAAI,gBAAgB,IAAI;AACvC;AAwBA,MAAM,UAAU,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CA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B,2BAA2B;CAC7B;AACF"}
@@ -24,8 +24,6 @@ export interface FactoryReadToolDependencies {
24
24
  liveSessions?: () => Pick<LiveSessions, 'parked' | 'parkedIn'> | undefined;
25
25
  }
26
26
  export declare function truncate(text: string, max: number): string;
27
- /** 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. */
28
- export declare function workItemNumber(item: Pick<Card, 'workItem' | 'metadata'>): number | null;
29
27
  export declare function workItemStage(item: Pick<Card, 'stages'>): string;
30
28
  /** A work item id or its card number; anything else can't name an item. */
31
29
  export declare const workItemRefSchema: z.ZodString;
@@ -1 +1 @@
1
- {"version":3,"file":"read-tools.d.ts","sourceRoot":"","sources":["../../src/tools/read-tools.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAUxB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAMhE,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAEhE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AACrE,OAAO,KAAK,EAGV,IAAI,EACJ,gBAAgB,EACjB,MAAM,uCAAuC,CAAC;AAI/C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,eAAO,MAAM,QAAQ,MAAM,CAAC;AAC5B,eAAO,MAAM,SAAS,MAAM,CAAC;AAC7B,eAAO,MAAM,QAAQ,KAAK,CAAC;AAG3B,MAAM,WAAW,2BAA2B;IAC1C,SAAS,EAAE,IAAI,CACb,gBAAgB,EACd,Y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AE,MAAM,OAAO,CAAC,IAAI,CAAC,gBAAgB,EAAE,YAAY,CAAC,GAAG,IAAI,CAAC,CAAC;IACvE,uGAAuG;IACvG,QAAQ,CAAC,EAAE,IAAI,CAAC,0BAA0B,EAAE,6BAA6B,CAAC,CAAC;IAC3E,sFAAsF;IACtF,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC,YAAY,EAAE,QAAQ,GAAG,UAAU,CAAC,GAAG,SAAS,CAAC;CAC5E;AAED,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAE1D;AAQD,wBAAgB,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,GAAG,MAAM,CAEhE;AAED,2EAA2E;AAC3E,eAAO,MAAM,iBAAiB,aAOyB,CAAC;AAExD,+GAA+G;AAC/G,wBAAsB,YAAY,CAChC,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,YAAY,GAAG,eAAe,CAAC,EACjE,KAAK,EAAE,IAAI,CAAC,gBAAgB,EAAE,OAAO,GAAG,kBAAkB,CAAC,EAC3D,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAmBtB;AAQD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,KAAK,CAEnD;AAyFD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,gBAAgB,EAAE,IAAI,EAAE,2BAA2B,GAAG,gBAAgB,CA4PnH"}
@@ -7,7 +7,7 @@ import { decisionRetryable, overtakenDecisionIds } from "../rules/decision-appli
7
7
  import { factoryDispatchFailureMetadata } from "../rules/dispatch-errors.js";
8
8
  import { needsApproval } from "../rules/types.js";
9
9
  import { resolveWorkItemRepository } from "../session/work-item-repository.js";
10
- import "../work-items/create-work-item.js";
10
+ import { workItemNumber } from "../work-items/card-number.js";
11
11
  import { sessionActivity } from "./deliver.js";
12
12
  import { createTool } from "@mastra/core/tools";
13
13
  import { z } from "zod";
@@ -24,11 +24,6 @@ function iso(value) {
24
24
  const date = value instanceof Date ? value : new Date(value);
25
25
  return Number.isFinite(date.getTime()) ? date.toISOString() : null;
26
26
  }
27
- /** 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. */
28
- function workItemNumber(item) {
29
- const number = item.workItem.metadata?.number ?? item.workItem.metadata?.githubIssueNumber ?? item.workItem.metadata?.githubPullRequestNumber ?? item.metadata?.["cardNumber"];
30
- return typeof number === "number" ? number : null;
31
- }
32
27
  function workItemStage(item) {
33
28
  return item.stages.join("+");
34
29
  }
@@ -364,6 +359,6 @@ function createFactoryReadTools(scope, deps) {
364
359
  })
365
360
  };
366
361
  }
367
- export { MAX_ERROR, MAX_LIST, MAX_TEXT, createFactoryReadTools, findWorkItem, truncate, workItemNotFound, workItemNumber, workItemRefSchema, workItemStage };
362
+ export { MAX_ERROR, MAX_LIST, MAX_TEXT, createFactoryReadTools, findWorkItem, truncate, workItemNotFound, workItemRefSchema, workItemStage };
368
363
 
369
364
  //# sourceMappingURL=read-tools.js.map