@mastra/factory 0.12.1-alpha.1 → 0.13.0-alpha.2

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 (71) hide show
  1. package/README.md +10 -0
  2. package/dist/factory.d.ts.map +1 -1
  3. package/dist/factory.js +64 -8
  4. package/dist/factory.js.map +1 -1
  5. package/dist/integrations/github/rules.d.ts.map +1 -1
  6. package/dist/integrations/github/rules.js +26 -2
  7. package/dist/integrations/github/rules.js.map +1 -1
  8. package/dist/routes/attention-providers.d.ts +17 -0
  9. package/dist/routes/attention-providers.d.ts.map +1 -1
  10. package/dist/routes/attention-providers.js +128 -2
  11. package/dist/routes/attention-providers.js.map +1 -1
  12. package/dist/routes/attention.d.ts.map +1 -1
  13. package/dist/routes/attention.js +11 -4
  14. package/dist/routes/attention.js.map +1 -1
  15. package/dist/routes/supervisor.d.ts +23 -0
  16. package/dist/routes/supervisor.d.ts.map +1 -0
  17. package/dist/routes/supervisor.js +34 -0
  18. package/dist/routes/supervisor.js.map +1 -0
  19. package/dist/routes/work-items.d.ts.map +1 -1
  20. package/dist/routes/work-items.js +5 -0
  21. package/dist/routes/work-items.js.map +1 -1
  22. package/dist/rules/defaults.d.ts.map +1 -1
  23. package/dist/rules/defaults.js +4 -2
  24. package/dist/rules/defaults.js.map +1 -1
  25. package/dist/rules/dispatcher.d.ts.map +1 -1
  26. package/dist/rules/dispatcher.js +49 -21
  27. package/dist/rules/dispatcher.js.map +1 -1
  28. package/dist/rules/terminal-cleanup.d.ts +3 -1
  29. package/dist/rules/terminal-cleanup.d.ts.map +1 -1
  30. package/dist/rules/terminal-cleanup.js +5 -0
  31. package/dist/rules/terminal-cleanup.js.map +1 -1
  32. package/dist/rules/transition-service.d.ts +1 -0
  33. package/dist/rules/transition-service.d.ts.map +1 -1
  34. package/dist/rules/transition-service.js +2 -1
  35. package/dist/rules/transition-service.js.map +1 -1
  36. package/dist/rules/types.d.ts +5 -0
  37. package/dist/rules/types.d.ts.map +1 -1
  38. package/dist/rules/types.js.map +1 -1
  39. package/dist/storage/domains/work-items/base.d.ts +36 -1
  40. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  41. package/dist/storage/domains/work-items/base.js +144 -2
  42. package/dist/storage/domains/work-items/base.js.map +1 -1
  43. package/dist/supervisor/health-worker.d.ts +17 -0
  44. package/dist/supervisor/health-worker.d.ts.map +1 -0
  45. package/dist/supervisor/health-worker.js +72 -0
  46. package/dist/supervisor/health-worker.js.map +1 -0
  47. package/dist/supervisor/health.d.ts +81 -0
  48. package/dist/supervisor/health.d.ts.map +1 -0
  49. package/dist/supervisor/health.js +245 -0
  50. package/dist/supervisor/health.js.map +1 -0
  51. package/dist/supervisor/instructions.d.ts +6 -0
  52. package/dist/supervisor/instructions.d.ts.map +1 -0
  53. package/dist/supervisor/instructions.js +64 -0
  54. package/dist/supervisor/instructions.js.map +1 -0
  55. package/dist/supervisor/read-tools.d.ts +41 -0
  56. package/dist/supervisor/read-tools.d.ts.map +1 -0
  57. package/dist/supervisor/read-tools.js +338 -0
  58. package/dist/supervisor/read-tools.js.map +1 -0
  59. package/dist/supervisor/session.d.ts +38 -0
  60. package/dist/supervisor/session.d.ts.map +1 -0
  61. package/dist/supervisor/session.js +63 -0
  62. package/dist/supervisor/session.js.map +1 -0
  63. package/dist/supervisor/write-tools.d.ts +26 -0
  64. package/dist/supervisor/write-tools.d.ts.map +1 -0
  65. package/dist/supervisor/write-tools.js +227 -0
  66. package/dist/supervisor/write-tools.js.map +1 -0
  67. package/dist/workspace.d.ts +3 -0
  68. package/dist/workspace.d.ts.map +1 -1
  69. package/dist/workspace.js +13 -3
  70. package/dist/workspace.js.map +1 -1
  71. package/package.json +3 -3
@@ -0,0 +1,338 @@
1
+ import { FACTORY_RULE_STAGES, factoryRuleStage } from "../rules/types.js";
2
+ import { factoryDispatchFailureMetadata } from "../rules/dispatch-errors.js";
3
+ import { runFactoryHealthCheck } from "./health.js";
4
+ import { createTool } from "@mastra/core/tools";
5
+ import { z } from "zod";
6
+ //#region src/supervisor/read-tools.ts
7
+ const MAX_TEXT = 600;
8
+ const MAX_ERROR = 400;
9
+ const MAX_LIST = 50;
10
+ function truncate(text, max) {
11
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
12
+ }
13
+ function iso(value) {
14
+ if (!value) return null;
15
+ const date = value instanceof Date ? value : new Date(value);
16
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null;
17
+ }
18
+ function itemNumber(item) {
19
+ const number = item.metadata?.number ?? item.metadata?.githubIssueNumber ?? item.metadata?.githubPullRequestNumber;
20
+ return typeof number === "number" ? number : null;
21
+ }
22
+ function itemLabels(item) {
23
+ const labels = item.metadata?.labels;
24
+ return Array.isArray(labels) ? labels.filter((label) => typeof label === "string") : [];
25
+ }
26
+ function summarizeItem(item) {
27
+ return {
28
+ id: item.id,
29
+ number: itemNumber(item),
30
+ title: item.title,
31
+ stage: factoryRuleStage(item.stages) ?? item.stages.join("+"),
32
+ source: item.externalSource ? `${item.externalSource.integrationId}:${item.externalSource.type}` : "manual",
33
+ url: typeof item.metadata?.url === "string" ? item.metadata.url : null,
34
+ triageType: item.triageType,
35
+ acceptedAt: iso(item.acceptedAt),
36
+ autonomyArmedAt: iso(item.autonomyArmedAt),
37
+ parentWorkItemId: item.parentWorkItemId,
38
+ revision: item.revision,
39
+ updatedAt: iso(item.updatedAt)
40
+ };
41
+ }
42
+ function summarizeDecision(decision) {
43
+ const type = typeof decision.decision.type === "string" ? decision.decision.type : "decision";
44
+ const role = typeof decision.decision.role === "string" ? decision.decision.role : null;
45
+ const skill = typeof decision.decision.skillName === "string" ? decision.decision.skillName : null;
46
+ return {
47
+ id: decision.id,
48
+ workItemId: decision.workItemId,
49
+ type,
50
+ role,
51
+ skill,
52
+ status: decision.status,
53
+ attempts: decision.attempts,
54
+ availableAt: iso(decision.availableAt),
55
+ leaseOwner: decision.leaseOwner,
56
+ leaseExpiresAt: iso(decision.leaseExpiresAt),
57
+ failureCode: decision.failureCode,
58
+ failureLabel: decision.failureCode ? factoryDispatchFailureMetadata(decision.failureCode).label : null,
59
+ canRetry: decision.status === "failed" ? factoryDispatchFailureMetadata(decision.failureCode).canRetry : false,
60
+ lastError: decision.lastError ? truncate(decision.lastError, MAX_ERROR) : null,
61
+ approvedBy: decision.approvedBy,
62
+ createdAt: iso(decision.createdAt),
63
+ updatedAt: iso(decision.updatedAt),
64
+ completedAt: iso(decision.completedAt)
65
+ };
66
+ }
67
+ function messageParts(content) {
68
+ if (Array.isArray(content)) return content;
69
+ if (content && typeof content === "object") {
70
+ const parts = content.parts;
71
+ if (Array.isArray(parts)) return parts;
72
+ }
73
+ return [];
74
+ }
75
+ function messageText(message) {
76
+ const content = message.content;
77
+ const parts = messageParts(content);
78
+ const text = [];
79
+ for (const part of parts) if (part && typeof part === "object" && part.type === "text") {
80
+ const value = part.text;
81
+ if (typeof value === "string") text.push(value);
82
+ }
83
+ if (text.length === 0 && typeof content === "string") text.push(content);
84
+ return text.join("\n");
85
+ }
86
+ function messageToolCalls(message) {
87
+ const parts = messageParts(message.content);
88
+ const calls = [];
89
+ for (const rawPart of parts) {
90
+ if (!rawPart || typeof rawPart !== "object") continue;
91
+ const part = rawPart;
92
+ const invocation = part.type === "tool-invocation" && part.toolInvocation && typeof part.toolInvocation === "object" ? part.toolInvocation : typeof part.type === "string" && part.type.startsWith("tool-") ? part : void 0;
93
+ if (!invocation) continue;
94
+ const name = invocation.toolName ?? invocation.name ?? (typeof part.type === "string" ? part.type.slice(5) : null);
95
+ if (typeof name !== "string") continue;
96
+ calls.push({
97
+ tool: name,
98
+ state: typeof invocation.state === "string" ? invocation.state : null
99
+ });
100
+ }
101
+ return calls;
102
+ }
103
+ async function findItem(deps, ref) {
104
+ if (ref.id) return deps.workItems.getForProject(deps.scope.orgId, deps.scope.factoryProjectId, ref.id);
105
+ if (ref.number === void 0) return null;
106
+ const matches = (await deps.workItems.list(deps.scope)).filter((item) => itemNumber(item) === ref.number);
107
+ return matches.find((item) => item.externalSource?.type !== "pull-request") ?? matches[0] ?? null;
108
+ }
109
+ const itemRefSchema = z.object({
110
+ id: z.string().uuid().optional().describe("Work item id."),
111
+ number: z.number().int().positive().optional().describe("Card number as shown on the board, e.g. 22874.")
112
+ }).refine((ref) => ref.id !== void 0 || ref.number !== void 0, { message: "Provide an id or a number." });
113
+ function createFactorySupervisorReadTools(deps) {
114
+ const now = deps.now ?? (() => /* @__PURE__ */ new Date());
115
+ const scope = deps.scope;
116
+ return {
117
+ factory_overview: createTool({
118
+ id: "factory_overview",
119
+ description: "Counts per pipeline stage, decisions by status, active seats, open proposals and held cards for this Factory. Start here for \"what needs me\" questions.",
120
+ inputSchema: z.object({}).strict(),
121
+ execute: async () => {
122
+ const [items, decisions, bindings, pendingStarts] = await Promise.all([
123
+ deps.workItems.list(scope),
124
+ deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId),
125
+ deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId),
126
+ deps.workItems.listPendingStarts(scope.orgId, scope.factoryProjectId)
127
+ ]);
128
+ const stages = Object.fromEntries(FACTORY_RULE_STAGES.map((stage) => [stage, 0]));
129
+ let held = 0;
130
+ for (const item of items) {
131
+ const stage = factoryRuleStage(item.stages);
132
+ if (stage) stages[stage] += 1;
133
+ if (stage === "triage" && item.triageType && item.triageType !== "bug" && !item.acceptedAt) held += 1;
134
+ }
135
+ const decisionsByStatus = {};
136
+ for (const decision of decisions) decisionsByStatus[decision.status] = (decisionsByStatus[decision.status] ?? 0) + 1;
137
+ const activeSeats = bindings.filter((binding) => binding.status === "active");
138
+ const seatsByRole = {};
139
+ for (const seat of activeSeats) seatsByRole[seat.role] = (seatsByRole[seat.role] ?? 0) + 1;
140
+ return {
141
+ checkedAt: now().toISOString(),
142
+ workItems: {
143
+ total: items.length,
144
+ byStage: stages,
145
+ heldForDecision: held
146
+ },
147
+ decisions: decisionsByStatus,
148
+ openProposals: decisions.filter((d) => d.status === "proposed").map(summarizeDecision).slice(0, MAX_LIST),
149
+ failedDecisions: decisions.filter((d) => d.status === "failed").map(summarizeDecision).slice(0, MAX_LIST),
150
+ activeSeats: {
151
+ total: activeSeats.length,
152
+ byRole: seatsByRole
153
+ },
154
+ pendingStarts: pendingStarts.filter((start) => start.status !== "sent").length
155
+ };
156
+ }
157
+ }),
158
+ factory_health_check: createTool({
159
+ id: "factory_health_check",
160
+ description: "Deterministic list of things wrong with this Factory right now (failed or stuck decisions, stalled starts, orphaned or missing seats, proposals and held cards waiting on a person, label drift). Each finding carries evidence and the standard repair. Explain these; do not invent findings that are not listed.",
161
+ inputSchema: z.object({}).strict(),
162
+ execute: async () => runFactoryHealthCheck(deps.workItems, scope, {
163
+ now: now(),
164
+ thresholds: deps.healthThresholds
165
+ })
166
+ }),
167
+ factory_inspect_work_item: createTool({
168
+ id: "factory_inspect_work_item",
169
+ description: "Everything the Factory knows about one card: row, stage history, seats (run bindings), decisions with errors, recent audit events, recent feed comments, linked parent/children and last observed labels. Use for \"why is #N in this state\".",
170
+ inputSchema: itemRefSchema,
171
+ execute: async (ref) => {
172
+ const item = await findItem(deps, ref);
173
+ if (!item) throw new Error(`No work item matches ${ref.id ?? `#${ref.number}`} in this Factory.`);
174
+ const [decisions, bindings, audit, feed, all] = await Promise.all([
175
+ deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId),
176
+ deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId, item.id),
177
+ deps.audit.list({
178
+ orgId: scope.orgId,
179
+ factoryProjectId: scope.factoryProjectId,
180
+ limit: 200
181
+ }),
182
+ deps.comments.listRecent({
183
+ ...scope,
184
+ workItemId: item.id,
185
+ limit: 10
186
+ }),
187
+ deps.workItems.list(scope)
188
+ ]);
189
+ const parent = item.parentWorkItemId ? all.find((candidate) => candidate.id === item.parentWorkItemId) : void 0;
190
+ const children = all.filter((candidate) => candidate.parentWorkItemId === item.id);
191
+ return {
192
+ item: summarizeItem(item),
193
+ labels: itemLabels(item),
194
+ stageHistory: item.stageHistory.map((entry) => ({
195
+ stage: entry.stage,
196
+ enteredAt: entry.enteredAt,
197
+ exitedAt: entry.exitedAt ?? null,
198
+ by: entry.by
199
+ })),
200
+ sessions: Object.entries(item.sessions).map(([role, ref]) => ({
201
+ role,
202
+ sessionId: ref.sessionId,
203
+ threadId: ref.threadId,
204
+ branch: ref.branch,
205
+ startedBy: ref.startedBy
206
+ })),
207
+ seats: bindings.map((binding) => ({
208
+ id: binding.id,
209
+ role: binding.role,
210
+ status: binding.status,
211
+ sessionId: binding.sessionId,
212
+ threadId: binding.threadId,
213
+ createdAt: iso(binding.createdAt),
214
+ revokedAt: iso(binding.revokedAt)
215
+ })),
216
+ decisions: decisions.filter((decision) => decision.workItemId === item.id).map(summarizeDecision).slice(-50),
217
+ audit: audit.events.filter((event) => event.targets.some((target) => target.type === "work_item" && target.id === item.id)).slice(0, 25).map((event) => ({
218
+ id: event.id,
219
+ action: event.action,
220
+ actorId: event.actorId,
221
+ actorType: event.actorType,
222
+ occurredAt: iso(event.occurredAt),
223
+ metadata: event.metadata
224
+ })),
225
+ feed: feed.map((comment) => ({
226
+ id: comment.id,
227
+ kind: comment.kind,
228
+ author: comment.author,
229
+ occurredAt: iso(comment.occurredAt),
230
+ body: truncate(comment.body, MAX_TEXT)
231
+ })),
232
+ parent: parent ? summarizeItem(parent) : null,
233
+ children: children.map(summarizeItem)
234
+ };
235
+ }
236
+ }),
237
+ factory_list_attention: createTool({
238
+ id: "factory_list_attention",
239
+ description: "Failed decisions grouped by failure code and error text, so a batch of cards that broke the same way reads as one incident. Also lists proposals waiting on a person and terminal cards that still hold seats.",
240
+ inputSchema: z.object({ limit: z.number().int().min(1).max(MAX_LIST).default(25) }).strict(),
241
+ execute: async ({ limit }) => {
242
+ const [decisions, items] = await Promise.all([deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId), deps.workItems.list(scope)]);
243
+ const itemsById = new Map(items.map((item) => [item.id, item]));
244
+ const groups = /* @__PURE__ */ new Map();
245
+ for (const decision of decisions) {
246
+ if (decision.status !== "failed") continue;
247
+ const error = truncate(decision.lastError ?? "", 160);
248
+ const key = `${decision.failureCode ?? "unknown"}|${error}`;
249
+ const group = groups.get(key) ?? {
250
+ failureCode: decision.failureCode ?? "unknown",
251
+ error,
252
+ decisions: []
253
+ };
254
+ group.decisions.push(decision);
255
+ groups.set(key, group);
256
+ }
257
+ return {
258
+ incidents: [...groups.values()].sort((a, b) => b.decisions.length - a.decisions.length).slice(0, limit).map((group) => ({
259
+ failureCode: group.failureCode,
260
+ failureLabel: factoryDispatchFailureMetadata(group.decisions[0].failureCode).label,
261
+ error: group.error,
262
+ count: group.decisions.length,
263
+ firstFailedAt: iso(new Date(group.decisions.reduce((earliest, decision) => Math.min(earliest, decision.updatedAt.getTime()), Infinity))),
264
+ lastFailedAt: iso(new Date(group.decisions.reduce((latest, decision) => Math.max(latest, decision.updatedAt.getTime()), -Infinity))),
265
+ decisions: group.decisions.slice(0, limit).map((decision) => {
266
+ const item = decision.workItemId ? itemsById.get(decision.workItemId) : void 0;
267
+ return {
268
+ id: decision.id,
269
+ workItemId: decision.workItemId,
270
+ number: item ? itemNumber(item) : null,
271
+ title: item?.title ?? null,
272
+ attempts: decision.attempts
273
+ };
274
+ })
275
+ })),
276
+ proposals: decisions.filter((d) => d.status === "proposed").slice(0, limit).map(summarizeDecision)
277
+ };
278
+ }
279
+ }),
280
+ factory_read_session: createTool({
281
+ id: "factory_read_session",
282
+ description: "The most recent turns of a card's shared agent thread: who spoke, when, the text (truncated) and which tools were called. Use to see what a worker actually did. Give a work item (id or number) or a threadId.",
283
+ inputSchema: z.object({
284
+ id: z.string().uuid().optional(),
285
+ number: z.number().int().positive().optional(),
286
+ threadId: z.string().min(1).optional(),
287
+ limit: z.number().int().min(1).max(40).default(20)
288
+ }).strict().refine((ref) => ref.id !== void 0 || ref.number !== void 0 || ref.threadId !== void 0, { message: "Provide a work item id, a number, or a threadId." }),
289
+ execute: async ({ limit, ...ref }) => {
290
+ if (!deps.messageReader) throw new Error("Session transcripts are not available on this deployment.");
291
+ let threadId = ref.threadId;
292
+ let resourceId;
293
+ if (!threadId) {
294
+ const item = await findItem(deps, ref);
295
+ if (!item) throw new Error(`No work item matches ${ref.id ?? `#${ref.number}`} in this Factory.`);
296
+ const session = Object.values(item.sessions)[0];
297
+ if (!session) return {
298
+ threadId: null,
299
+ item: summarizeItem(item),
300
+ turns: []
301
+ };
302
+ threadId = session.threadId;
303
+ resourceId = session.sessionId;
304
+ } else {
305
+ const binding = (await deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId)).find((candidate) => candidate.threadId === threadId);
306
+ if (!binding) throw new Error(`Thread ${threadId} is not bound to a card in this Factory.`);
307
+ resourceId = binding.resourceId;
308
+ }
309
+ const page = await deps.messageReader.listMessages({
310
+ threadId,
311
+ ...resourceId ? { resourceId } : {},
312
+ page: 0,
313
+ perPage: limit,
314
+ orderBy: {
315
+ field: "createdAt",
316
+ direction: "DESC"
317
+ }
318
+ });
319
+ const turns = [...page.messages].reverse().map((message) => ({
320
+ id: message.id,
321
+ role: message.role,
322
+ createdAt: iso(message.createdAt),
323
+ text: truncate(messageText(message), MAX_TEXT),
324
+ tools: messageToolCalls(message)
325
+ }));
326
+ return {
327
+ threadId,
328
+ hasOlder: page.hasMore,
329
+ turns
330
+ };
331
+ }
332
+ })
333
+ };
334
+ }
335
+ //#endregion
336
+ export { createFactorySupervisorReadTools };
337
+
338
+ //# sourceMappingURL=read-tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-tools.js","names":[],"sources":["../../src/supervisor/read-tools.ts"],"sourcesContent":["/**\n * Supervisor read surface. Every tool is bounded (hard row caps, truncated\n * text) and answers with ids a person can click on the board, so the model\n * can explain a card's state without ever touching the database itself.\n */\n\nimport type { MastraDBMessage } from '@mastra/core/agent/message-list';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { factoryDispatchFailureMetadata } from '../rules/dispatch-errors.js';\nimport { FACTORY_RULE_STAGES, factoryRuleStage } from '../rules/types.js';\nimport type { FactoryRuleStage } from '../rules/types.js';\nimport type { AuditStorage } from '../storage/domains/audit/base.js';\nimport type { WorkItemCommentsStorage } from '../storage/domains/comments/base.js';\nimport type {\n FactoryDeferredDecisionRecord,\n WorkItemRow,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport type { FactoryHealthReport, FactoryHealthThresholds } from './health.js';\nimport { runFactoryHealthCheck } from './health.js';\n\nexport interface SupervisorScope {\n orgId: string;\n factoryProjectId: string;\n}\n\nexport interface SupervisorMessageReader {\n listMessages(input: {\n threadId: string;\n resourceId?: string;\n page: number;\n perPage: number;\n orderBy: { field: 'createdAt'; direction: 'ASC' | 'DESC' };\n }): Promise<{ messages: MastraDBMessage[]; hasMore: boolean }>;\n}\n\nexport interface SupervisorReadDependencies {\n scope: SupervisorScope;\n workItems: WorkItemsStorage;\n comments: WorkItemCommentsStorage;\n audit: AuditStorage;\n messageReader?: SupervisorMessageReader;\n healthThresholds?: FactoryHealthThresholds;\n now?: () => Date;\n}\n\nconst MAX_TEXT = 600;\nconst MAX_ERROR = 400;\nconst MAX_LIST = 50;\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n\nfunction iso(value: Date | string | null | undefined): string | null {\n if (!value) return null;\n const date = value instanceof Date ? value : new Date(value);\n return Number.isFinite(date.getTime()) ? date.toISOString() : null;\n}\n\nfunction itemNumber(item: WorkItemRow): number | null {\n const number = item.metadata?.number ?? item.metadata?.githubIssueNumber ?? item.metadata?.githubPullRequestNumber;\n return typeof number === 'number' ? number : null;\n}\n\nfunction itemLabels(item: WorkItemRow): string[] {\n const labels = item.metadata?.labels;\n return Array.isArray(labels) ? labels.filter((label): label is string => typeof label === 'string') : [];\n}\n\nfunction summarizeItem(item: WorkItemRow) {\n return {\n id: item.id,\n number: itemNumber(item),\n title: item.title,\n stage: factoryRuleStage(item.stages) ?? item.stages.join('+'),\n source: item.externalSource ? `${item.externalSource.integrationId}:${item.externalSource.type}` : 'manual',\n url: typeof item.metadata?.url === 'string' ? item.metadata.url : null,\n triageType: item.triageType,\n acceptedAt: iso(item.acceptedAt),\n autonomyArmedAt: iso(item.autonomyArmedAt),\n parentWorkItemId: item.parentWorkItemId,\n revision: item.revision,\n updatedAt: iso(item.updatedAt),\n };\n}\n\nfunction summarizeDecision(decision: FactoryDeferredDecisionRecord) {\n const type = typeof decision.decision.type === 'string' ? decision.decision.type : 'decision';\n const role = typeof decision.decision.role === 'string' ? decision.decision.role : null;\n const skill = typeof decision.decision.skillName === 'string' ? decision.decision.skillName : null;\n return {\n id: decision.id,\n workItemId: decision.workItemId,\n type,\n role,\n skill,\n status: decision.status,\n attempts: decision.attempts,\n availableAt: iso(decision.availableAt),\n leaseOwner: decision.leaseOwner,\n leaseExpiresAt: iso(decision.leaseExpiresAt),\n failureCode: decision.failureCode,\n failureLabel: decision.failureCode ? factoryDispatchFailureMetadata(decision.failureCode).label : null,\n canRetry: decision.status === 'failed' ? factoryDispatchFailureMetadata(decision.failureCode).canRetry : false,\n lastError: decision.lastError ? truncate(decision.lastError, MAX_ERROR) : null,\n approvedBy: decision.approvedBy,\n createdAt: iso(decision.createdAt),\n updatedAt: iso(decision.updatedAt),\n completedAt: iso(decision.completedAt),\n };\n}\n\nfunction messageParts(content: unknown): unknown[] {\n if (Array.isArray(content)) return content;\n if (content && typeof content === 'object') {\n const parts = (content as { parts?: unknown }).parts;\n if (Array.isArray(parts)) return parts;\n }\n return [];\n}\n\nfunction messageText(message: MastraDBMessage): string {\n const content: unknown = message.content;\n const parts = messageParts(content);\n const text: string[] = [];\n for (const part of parts) {\n if (part && typeof part === 'object' && (part as { type?: unknown }).type === 'text') {\n const value = (part as { text?: unknown }).text;\n if (typeof value === 'string') text.push(value);\n }\n }\n if (text.length === 0 && typeof content === 'string') text.push(content);\n return text.join('\\n');\n}\n\nfunction messageToolCalls(message: MastraDBMessage): Array<{ tool: string; state: string | null }> {\n const parts = messageParts(message.content);\n const calls: Array<{ tool: string; state: string | null }> = [];\n for (const rawPart of parts) {\n if (!rawPart || typeof rawPart !== 'object') continue;\n const part = rawPart as Record<string, unknown>;\n const invocation =\n part.type === 'tool-invocation' && part.toolInvocation && typeof part.toolInvocation === 'object'\n ? (part.toolInvocation as Record<string, unknown>)\n : typeof part.type === 'string' && part.type.startsWith('tool-')\n ? part\n : undefined;\n if (!invocation) continue;\n const name = invocation.toolName ?? invocation.name ?? (typeof part.type === 'string' ? part.type.slice(5) : null);\n if (typeof name !== 'string') continue;\n calls.push({ tool: name, state: typeof invocation.state === 'string' ? invocation.state : null });\n }\n return calls;\n}\n\nasync function findItem(\n deps: SupervisorReadDependencies,\n ref: { id?: string; number?: number },\n): Promise<WorkItemRow | null> {\n if (ref.id) return deps.workItems.getForProject(deps.scope.orgId, deps.scope.factoryProjectId, ref.id);\n if (ref.number === undefined) return null;\n const items = await deps.workItems.list(deps.scope);\n const matches = items.filter(item => itemNumber(item) === ref.number);\n // Issue and PR numbers share a space on GitHub; prefer the Work-board card.\n return matches.find(item => item.externalSource?.type !== 'pull-request') ?? matches[0] ?? null;\n}\n\nconst itemRefSchema = z\n .object({\n id: z.string().uuid().optional().describe('Work item id.'),\n number: z.number().int().positive().optional().describe('Card number as shown on the board, e.g. 22874.'),\n })\n .refine(ref => ref.id !== undefined || ref.number !== undefined, { message: 'Provide an id or a number.' });\n\nexport function createFactorySupervisorReadTools(deps: SupervisorReadDependencies): IntegrationTools {\n const now = deps.now ?? (() => new Date());\n const scope = deps.scope;\n\n return {\n factory_overview: createTool({\n id: 'factory_overview',\n description:\n 'Counts per pipeline stage, decisions by status, active seats, open proposals and held cards for this Factory. Start here for \"what needs me\" questions.',\n inputSchema: z.object({}).strict(),\n execute: async () => {\n const [items, decisions, bindings, pendingStarts] = await Promise.all([\n deps.workItems.list(scope),\n deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId),\n deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId),\n deps.workItems.listPendingStarts(scope.orgId, scope.factoryProjectId),\n ]);\n const stages = Object.fromEntries(FACTORY_RULE_STAGES.map(stage => [stage, 0])) as Record<\n FactoryRuleStage,\n number\n >;\n let held = 0;\n for (const item of items) {\n const stage = factoryRuleStage(item.stages);\n if (stage) stages[stage] += 1;\n if (stage === 'triage' && item.triageType && item.triageType !== 'bug' && !item.acceptedAt) held += 1;\n }\n const decisionsByStatus: Record<string, number> = {};\n for (const decision of decisions) {\n decisionsByStatus[decision.status] = (decisionsByStatus[decision.status] ?? 0) + 1;\n }\n const activeSeats = bindings.filter(binding => binding.status === 'active');\n const seatsByRole: Record<string, number> = {};\n for (const seat of activeSeats) seatsByRole[seat.role] = (seatsByRole[seat.role] ?? 0) + 1;\n return {\n checkedAt: now().toISOString(),\n workItems: { total: items.length, byStage: stages, heldForDecision: held },\n decisions: decisionsByStatus,\n openProposals: decisions\n .filter(d => d.status === 'proposed')\n .map(summarizeDecision)\n .slice(0, MAX_LIST),\n failedDecisions: decisions\n .filter(d => d.status === 'failed')\n .map(summarizeDecision)\n .slice(0, MAX_LIST),\n activeSeats: { total: activeSeats.length, byRole: seatsByRole },\n pendingStarts: pendingStarts.filter(start => start.status !== 'sent').length,\n };\n },\n }),\n\n factory_health_check: createTool({\n id: 'factory_health_check',\n description:\n 'Deterministic list of things wrong with this Factory right now (failed or stuck decisions, stalled starts, orphaned or missing seats, proposals and held cards waiting on a person, label drift). Each finding carries evidence and the standard repair. Explain these; do not invent findings that are not listed.',\n inputSchema: z.object({}).strict(),\n execute: async (): Promise<FactoryHealthReport> =>\n runFactoryHealthCheck(deps.workItems, scope, { now: now(), thresholds: deps.healthThresholds }),\n }),\n\n factory_inspect_work_item: createTool({\n id: 'factory_inspect_work_item',\n description:\n 'Everything the Factory knows about one card: row, stage history, seats (run bindings), decisions with errors, recent audit events, recent feed comments, linked parent/children and last observed labels. Use for \"why is #N in this state\".',\n inputSchema: itemRefSchema,\n execute: async ref => {\n const item = await findItem(deps, ref);\n if (!item) throw new Error(`No work item matches ${ref.id ?? `#${ref.number}`} in this Factory.`);\n const [decisions, bindings, audit, feed, all] = await Promise.all([\n deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId),\n deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId, item.id),\n deps.audit.list({ orgId: scope.orgId, factoryProjectId: scope.factoryProjectId, limit: 200 }),\n deps.comments.listRecent({ ...scope, workItemId: item.id, limit: 10 }),\n deps.workItems.list(scope),\n ]);\n const parent = item.parentWorkItemId\n ? all.find(candidate => candidate.id === item.parentWorkItemId)\n : undefined;\n const children = all.filter(candidate => candidate.parentWorkItemId === item.id);\n return {\n item: summarizeItem(item),\n labels: itemLabels(item),\n stageHistory: item.stageHistory.map(entry => ({\n stage: entry.stage,\n enteredAt: entry.enteredAt,\n exitedAt: entry.exitedAt ?? null,\n by: entry.by,\n })),\n sessions: Object.entries(item.sessions).map(([role, ref]) => ({\n role,\n sessionId: ref.sessionId,\n threadId: ref.threadId,\n branch: ref.branch,\n startedBy: ref.startedBy,\n })),\n seats: bindings.map(binding => ({\n id: binding.id,\n role: binding.role,\n status: binding.status,\n sessionId: binding.sessionId,\n threadId: binding.threadId,\n createdAt: iso(binding.createdAt),\n revokedAt: iso(binding.revokedAt),\n })),\n decisions: decisions\n .filter(decision => decision.workItemId === item.id)\n .map(summarizeDecision)\n .slice(-MAX_LIST),\n audit: audit.events\n .filter(event => event.targets.some(target => target.type === 'work_item' && target.id === item.id))\n .slice(0, 25)\n .map(event => ({\n id: event.id,\n action: event.action,\n actorId: event.actorId,\n actorType: event.actorType,\n occurredAt: iso(event.occurredAt),\n metadata: event.metadata,\n })),\n feed: feed.map(comment => ({\n id: comment.id,\n kind: comment.kind,\n author: comment.author,\n occurredAt: iso(comment.occurredAt),\n body: truncate(comment.body, MAX_TEXT),\n })),\n parent: parent ? summarizeItem(parent) : null,\n children: children.map(summarizeItem),\n };\n },\n }),\n\n factory_list_attention: createTool({\n id: 'factory_list_attention',\n description:\n 'Failed decisions grouped by failure code and error text, so a batch of cards that broke the same way reads as one incident. Also lists proposals waiting on a person and terminal cards that still hold seats.',\n inputSchema: z.object({ limit: z.number().int().min(1).max(MAX_LIST).default(25) }).strict(),\n execute: async ({ limit }) => {\n const [decisions, items] = await Promise.all([\n deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId),\n deps.workItems.list(scope),\n ]);\n const itemsById = new Map(items.map(item => [item.id, item]));\n const groups = new Map<\n string,\n { failureCode: string; error: string; decisions: FactoryDeferredDecisionRecord[] }\n >();\n for (const decision of decisions) {\n if (decision.status !== 'failed') continue;\n const error = truncate(decision.lastError ?? '', 160);\n const key = `${decision.failureCode ?? 'unknown'}|${error}`;\n const group = groups.get(key) ?? { failureCode: decision.failureCode ?? 'unknown', error, decisions: [] };\n group.decisions.push(decision);\n groups.set(key, group);\n }\n const incidents = [...groups.values()]\n .sort((a, b) => b.decisions.length - a.decisions.length)\n .slice(0, limit)\n .map(group => ({\n failureCode: group.failureCode,\n failureLabel: factoryDispatchFailureMetadata(group.decisions[0]!.failureCode).label,\n error: group.error,\n count: group.decisions.length,\n firstFailedAt: iso(\n new Date(\n group.decisions.reduce(\n (earliest, decision) => Math.min(earliest, decision.updatedAt.getTime()),\n Infinity,\n ),\n ),\n ),\n lastFailedAt: iso(\n new Date(\n group.decisions.reduce((latest, decision) => Math.max(latest, decision.updatedAt.getTime()), -Infinity),\n ),\n ),\n decisions: group.decisions.slice(0, limit).map(decision => {\n const item = decision.workItemId ? itemsById.get(decision.workItemId) : undefined;\n return {\n id: decision.id,\n workItemId: decision.workItemId,\n number: item ? itemNumber(item) : null,\n title: item?.title ?? null,\n attempts: decision.attempts,\n };\n }),\n }));\n return {\n incidents,\n proposals: decisions\n .filter(d => d.status === 'proposed')\n .slice(0, limit)\n .map(summarizeDecision),\n };\n },\n }),\n\n factory_read_session: createTool({\n id: 'factory_read_session',\n description:\n \"The most recent turns of a card's shared agent thread: who spoke, when, the text (truncated) and which tools were called. Use to see what a worker actually did. Give a work item (id or number) or a threadId.\",\n inputSchema: z\n .object({\n id: z.string().uuid().optional(),\n number: z.number().int().positive().optional(),\n threadId: z.string().min(1).optional(),\n limit: z.number().int().min(1).max(40).default(20),\n })\n .strict()\n .refine(ref => ref.id !== undefined || ref.number !== undefined || ref.threadId !== undefined, {\n message: 'Provide a work item id, a number, or a threadId.',\n }),\n execute: async ({ limit, ...ref }) => {\n if (!deps.messageReader) throw new Error('Session transcripts are not available on this deployment.');\n let threadId = ref.threadId;\n let resourceId: string | undefined;\n if (!threadId) {\n const item = await findItem(deps, ref);\n if (!item) throw new Error(`No work item matches ${ref.id ?? `#${ref.number}`} in this Factory.`);\n const session = Object.values(item.sessions)[0];\n if (!session) return { threadId: null, item: summarizeItem(item), turns: [] };\n threadId = session.threadId;\n resourceId = session.sessionId;\n } else {\n // A thread the caller named must still belong to a card in this Factory.\n const bindings = await deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId);\n const binding = bindings.find(candidate => candidate.threadId === threadId);\n if (!binding) throw new Error(`Thread ${threadId} is not bound to a card in this Factory.`);\n resourceId = binding.resourceId;\n }\n const page = await deps.messageReader.listMessages({\n threadId,\n ...(resourceId ? { resourceId } : {}),\n page: 0,\n perPage: limit,\n orderBy: { field: 'createdAt', direction: 'DESC' },\n });\n const turns = [...page.messages].reverse().map(message => ({\n id: message.id,\n role: message.role,\n createdAt: iso(message.createdAt),\n text: truncate(messageText(message), MAX_TEXT),\n tools: messageToolCalls(message),\n }));\n return { threadId, hasOlder: page.hasMore, turns };\n },\n }),\n };\n}\n"],"mappings":";;;;;;AAiDA,MAAM,WAAW;AACjB,MAAM,YAAY;AAClB,MAAM,WAAW;AAEjB,SAAS,SAAS,MAAc,KAAqB;CACnD,OAAO,KAAK,SAAS,MAAM,GAAG,KAAK,MAAM,GAAG,MAAM,CAAC,EAAE,KAAK;AAC5D;AAEA,SAAS,IAAI,OAAwD;CAC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AC;KAC7C,IAAI,CAAC,SAAS,OAAO;MAAE,UAAU;MAAM,MAAM,cAAc,IAAI;MAAG,OAAO,CAAC;KAAE;KAC5E,WAAW,QAAQ;KACnB,aAAa,QAAQ;IACvB,OAAO;KAGL,MAAM,WAAU,MADO,KAAK,UAAU,gBAAgB,MAAM,OAAO,MAAM,gBAAgB,EAAA,CAChE,MAAK,cAAa,UAAU,aAAa,QAAQ;KAC1E,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,UAAU,SAAS,yCAAyC;KAC1F,aAAa,QAAQ;IACvB;IACA,MAAM,OAAO,MAAM,KAAK,cAAc,aAAa;KACjD;KACA,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;KACnC,MAAM;KACN,SAAS;KACT,SAAS;MAAE,OAAO;MAAa,WAAW;KAAO;IACnD,CAAC;IACD,MAAM,QAAQ,CAAC,GAAG,KAAK,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC,KAAI,aAAY;KACzD,IAAI,QAAQ;KACZ,MAAM,QAAQ;KACd,WAAW,IAAI,QAAQ,SAAS;KAChC,MAAM,SAAS,YAAY,OAAO,GAAG,QAAQ;KAC7C,OAAO,iBAAiB,OAAO;IACjC,EAAE;IACF,OAAO;KAAE;KAAU,UAAU,KAAK;KAAS;IAAM;GACnD;EACF,CAAC;CACH;AACF"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The supervisor session: one per factory, addressed by a self-describing
3
+ * resourceId so a restarted server can recover its scope without a lookup
4
+ * table. The session has no repository, no sandbox and no work-item seat —
5
+ * its tools talk to storage directly.
6
+ */
7
+ import type { MastraCodeState } from '@mastra/code-sdk/schema';
8
+ import type { AgentController } from '@mastra/core/agent-controller';
9
+ import type { RequestContext } from '@mastra/core/request-context';
10
+ import type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';
11
+ import type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';
12
+ import type { SupervisorScope } from './read-tools.js';
13
+ type FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;
14
+ export declare function supervisorResourceId(factoryProjectId: string): string;
15
+ /** The supervisor thread shares the session's id: one thread per factory. */
16
+ export declare function supervisorThreadId(factoryProjectId: string): string;
17
+ export declare function parseSupervisorResourceId(resourceId: string | undefined | null): string | null;
18
+ /**
19
+ * Scope a request to a supervisor session the caller is allowed to drive:
20
+ * the resourceId must name a project, and the caller's org must own it.
21
+ * Anything else yields null and the supervisor tools stay unregistered.
22
+ */
23
+ export declare function resolveSupervisorScope(options: {
24
+ requestContext: RequestContext | undefined;
25
+ projects: Pick<FactoryProjectsStorage, 'get'>;
26
+ }): Promise<SupervisorScope | null>;
27
+ /**
28
+ * Session-start hook: stamp the owning project onto a supervisor session and
29
+ * apply the factory's default model and memory settings. Runs on every
30
+ * (re)creation so a restarted server heals the in-memory state. Sessions
31
+ * that are not supervisors are left untouched.
32
+ */
33
+ export declare function hydrateSupervisorSession(session: FactorySession, deps: {
34
+ projects: Pick<FactoryProjectsStorage, 'getById'>;
35
+ memorySettings?: MemorySettingsStorage;
36
+ }): Promise<void>;
37
+ export {};
38
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/supervisor/session.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAiC,MAAM,+BAA+B,CAAC;AACpG,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAInE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AACxF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAIvD,KAAK,cAAc,GAAG,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;AAE7F,wBAAgB,oBAAoB,CAAC,gBAAgB,EAAE,MAAM,GAAG,MAAM,CAErE;AAED,6EAA6E;AAC7E,wBAAgB,kBAAkB,CAAC,gBAAgB,EAAE,MAAM,GAAG,MAAM,CAEnE;AAED,wBAAgB,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CAI9F;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAAC,OAAO,EAAE;IACpD,cAAc,EAAE,cAAc,GAAG,SAAS,CAAC;IAC3C,QAAQ,EAAE,IAAI,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;CAC/C,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAWlC;AAED;;;;;GAKG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,cAAc,EACvB,IAAI,EAAE;IAAE,QAAQ,EAAE,IAAI,CAAC,sBAAsB,EAAE,SAAS,CAAC,CAAC;IAAC,cAAc,CAAC,EAAE,qBAAqB,CAAA;CAAE,GAClG,OAAO,CAAC,IAAI,CAAC,CAef"}
@@ -0,0 +1,63 @@
1
+ import { getFactoryAuthOrgId, getFactoryAuthUserFromContext } from "../auth.js";
2
+ import { hydrateFactorySession } from "../session/factory-session.js";
3
+ //#region src/supervisor/session.ts
4
+ const RESOURCE_PREFIX = "factory-supervisor:";
5
+ function supervisorResourceId(factoryProjectId) {
6
+ return `${RESOURCE_PREFIX}${factoryProjectId}`;
7
+ }
8
+ /** The supervisor thread shares the session's id: one thread per factory. */
9
+ function supervisorThreadId(factoryProjectId) {
10
+ return supervisorResourceId(factoryProjectId);
11
+ }
12
+ function parseSupervisorResourceId(resourceId) {
13
+ if (!resourceId?.startsWith(RESOURCE_PREFIX)) return null;
14
+ const factoryProjectId = resourceId.slice(19);
15
+ return factoryProjectId.length > 0 ? factoryProjectId : null;
16
+ }
17
+ /**
18
+ * Scope a request to a supervisor session the caller is allowed to drive:
19
+ * the resourceId must name a project, and the caller's org must own it.
20
+ * Anything else yields null and the supervisor tools stay unregistered.
21
+ */
22
+ async function resolveSupervisorScope(options) {
23
+ const { requestContext } = options;
24
+ if (!requestContext || typeof requestContext.get !== "function") return null;
25
+ const factoryProjectId = parseSupervisorResourceId(requestContext.get("controller")?.resourceId);
26
+ if (!factoryProjectId) return null;
27
+ const orgId = getFactoryAuthOrgId(getFactoryAuthUserFromContext(requestContext));
28
+ if (!orgId) return null;
29
+ if (!await options.projects.get({
30
+ orgId,
31
+ id: factoryProjectId
32
+ })) return null;
33
+ return {
34
+ orgId,
35
+ factoryProjectId
36
+ };
37
+ }
38
+ /**
39
+ * Session-start hook: stamp the owning project onto a supervisor session and
40
+ * apply the factory's default model and memory settings. Runs on every
41
+ * (re)creation so a restarted server heals the in-memory state. Sessions
42
+ * that are not supervisors are left untouched.
43
+ */
44
+ async function hydrateSupervisorSession(session, deps) {
45
+ const factoryProjectId = parseSupervisorResourceId(session.identity.getResourceId());
46
+ if (!factoryProjectId) return;
47
+ const project = await deps.projects.getById({ id: factoryProjectId });
48
+ if (!project) return;
49
+ await session.state.set({
50
+ factoryProjectId,
51
+ factoryOrgId: project.orgId
52
+ });
53
+ await hydrateFactorySession(session, {
54
+ orgId: project.orgId,
55
+ factoryProjectId,
56
+ defaultModelId: project.defaultModelId ?? void 0,
57
+ memorySettings: deps.memorySettings
58
+ });
59
+ }
60
+ //#endregion
61
+ export { hydrateSupervisorSession, parseSupervisorResourceId, resolveSupervisorScope, supervisorResourceId, supervisorThreadId };
62
+
63
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","names":[],"sources":["../../src/supervisor/session.ts"],"sourcesContent":["/**\n * The supervisor session: one per factory, addressed by a self-describing\n * resourceId so a restarted server can recover its scope without a lookup\n * table. The session has no repository, no sandbox and no work-item seat —\n * its tools talk to storage directly.\n */\n\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController, AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport { getFactoryAuthOrgId, getFactoryAuthUserFromContext } from '../auth.js';\nimport { hydrateFactorySession } from '../session/factory-session.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SupervisorScope } from './read-tools.js';\n\nconst RESOURCE_PREFIX = 'factory-supervisor:';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\nexport function supervisorResourceId(factoryProjectId: string): string {\n return `${RESOURCE_PREFIX}${factoryProjectId}`;\n}\n\n/** The supervisor thread shares the session's id: one thread per factory. */\nexport function supervisorThreadId(factoryProjectId: string): string {\n return supervisorResourceId(factoryProjectId);\n}\n\nexport function parseSupervisorResourceId(resourceId: string | undefined | null): string | null {\n if (!resourceId?.startsWith(RESOURCE_PREFIX)) return null;\n const factoryProjectId = resourceId.slice(RESOURCE_PREFIX.length);\n return factoryProjectId.length > 0 ? factoryProjectId : null;\n}\n\n/**\n * Scope a request to a supervisor session the caller is allowed to drive:\n * the resourceId must name a project, and the caller's org must own it.\n * Anything else yields null and the supervisor tools stay unregistered.\n */\nexport async function resolveSupervisorScope(options: {\n requestContext: RequestContext | undefined;\n projects: Pick<FactoryProjectsStorage, 'get'>;\n}): Promise<SupervisorScope | null> {\n const { requestContext } = options;\n if (!requestContext || typeof requestContext.get !== 'function') return null;\n const context = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const factoryProjectId = parseSupervisorResourceId(context?.resourceId);\n if (!factoryProjectId) return null;\n const orgId = getFactoryAuthOrgId(getFactoryAuthUserFromContext(requestContext));\n if (!orgId) return null;\n const project = await options.projects.get({ orgId, id: factoryProjectId });\n if (!project) return null;\n return { orgId, factoryProjectId };\n}\n\n/**\n * Session-start hook: stamp the owning project onto a supervisor session and\n * apply the factory's default model and memory settings. Runs on every\n * (re)creation so a restarted server heals the in-memory state. Sessions\n * that are not supervisors are left untouched.\n */\nexport async function hydrateSupervisorSession(\n session: FactorySession,\n deps: { projects: Pick<FactoryProjectsStorage, 'getById'>; memorySettings?: MemorySettingsStorage },\n): Promise<void> {\n const factoryProjectId = parseSupervisorResourceId(session.identity.getResourceId());\n if (!factoryProjectId) return;\n const project = await deps.projects.getById({ id: factoryProjectId });\n if (!project) return;\n await session.state.set({\n factoryProjectId,\n factoryOrgId: project.orgId,\n });\n await hydrateFactorySession(session, {\n orgId: project.orgId,\n factoryProjectId,\n defaultModelId: project.defaultModelId ?? undefined,\n memorySettings: deps.memorySettings,\n });\n}\n"],"mappings":";;;AAiBA,MAAM,kBAAkB;AAIxB,SAAgB,qBAAqB,kBAAkC;CACrE,OAAO,GAAG,kBAAkB;AAC9B;;AAGA,SAAgB,mBAAmB,kBAAkC;CACnE,OAAO,qBAAqB,gBAAgB;AAC9C;AAEA,SAAgB,0BAA0B,YAAsD;CAC9F,IAAI,CAAC,YAAY,WAAW,eAAe,GAAG,OAAO;CACrD,MAAM,mBAAmB,WAAW,MAAM,EAAsB;CAChE,OAAO,iBAAiB,SAAS,IAAI,mBAAmB;AAC1D;;;;;;AAOA,eAAsB,uBAAuB,SAGT;CAClC,MAAM,EAAE,mBAAmB;CAC3B,IAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,YAAY,OAAO;CAExE,MAAM,mBAAmB,0BADT,eAAe,IAAI,YACsB,CAAC,EAAE,UAAU;CACtE,IAAI,CAAC,kBAAkB,OAAO;CAC9B,MAAM,QAAQ,oBAAoB,8BAA8B,cAAc,CAAC;CAC/E,IAAI,CAAC,OAAO,OAAO;CAEnB,IAAI,CAAC,MADiB,QAAQ,SAAS,IAAI;EAAE;EAAO,IAAI;CAAiB,CAAC,GAC5D,OAAO;CACrB,OAAO;EAAE;EAAO;CAAiB;AACnC;;;;;;;AAQA,eAAsB,yBACpB,SACA,MACe;CACf,MAAM,mBAAmB,0BAA0B,QAAQ,SAAS,cAAc,CAAC;CACnF,IAAI,CAAC,kBAAkB;CACvB,MAAM,UAAU,MAAM,KAAK,SAAS,QAAQ,EAAE,IAAI,iBAAiB,CAAC;CACpE,IAAI,CAAC,SAAS;CACd,MAAM,QAAQ,MAAM,IAAI;EACtB;EACA,cAAc,QAAQ;CACxB,CAAC;CACD,MAAM,sBAAsB,SAAS;EACnC,OAAO,QAAQ;EACf;EACA,gBAAgB,QAAQ,kBAAkB,KAAA;EAC1C,gBAAgB,KAAK;CACvB,CAAC;AACH"}
@@ -0,0 +1,26 @@
1
+ import type { IntegrationTools } from '../integrations/base.js';
2
+ import type { FactoryTransitionService } from '../rules/transition-service.js';
3
+ import type { AuditStorage } from '../storage/domains/audit/base.js';
4
+ import type { WorkItemRow, WorkItemsStorage } from '../storage/domains/work-items/base.js';
5
+ import type { SupervisorScope } from './read-tools.js';
6
+ interface SupervisorWriteDependencies {
7
+ scope: SupervisorScope;
8
+ userId: string;
9
+ workItems: WorkItemsStorage;
10
+ audit: AuditStorage;
11
+ transitionService: FactoryTransitionService;
12
+ reconcileAcceptanceLabels?: (input: {
13
+ orgId: string;
14
+ factoryProjectId: string;
15
+ item: WorkItemRow;
16
+ }) => Promise<void>;
17
+ signalSession?: (input: {
18
+ sessionId: string;
19
+ message: string;
20
+ userId: string;
21
+ }) => Promise<unknown>;
22
+ now?: () => Date;
23
+ }
24
+ export declare function createFactorySupervisorWriteTools(deps: SupervisorWriteDependencies): IntegrationTools;
25
+ export {};
26
+ //# sourceMappingURL=write-tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write-tools.d.ts","sourceRoot":"","sources":["../../src/supervisor/write-tools.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAE/E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AACrE,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAC3F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEvD,UAAU,2BAA2B;IACnC,KAAK,EAAE,eAAe,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,gBAAgB,CAAC;IAC5B,KAAK,EAAE,YAAY,CAAC;IACpB,iBAAiB,EAAE,wBAAwB,CAAC;IAC5C,yBAAyB,CAAC,EAAE,CAAC,KAAK,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,gBAAgB,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,WAAW,CAAA;KAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACrH,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACpG,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;CAClB;AAED,wBAAgB,iCAAiC,CAAC,IAAI,EAAE,2BAA2B,GAAG,gBAAgB,CA4LrG"}