@mastra/factory 0.29.0-alpha.5 → 0.29.0-alpha.6

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 (183) hide show
  1. package/README.md +55 -31
  2. package/dist/boards/semantics.d.ts.map +1 -1
  3. package/dist/boards/semantics.js +7 -1
  4. package/dist/boards/semantics.js.map +1 -1
  5. package/dist/factory.d.ts +10 -0
  6. package/dist/factory.d.ts.map +1 -1
  7. package/dist/factory.js +98 -41
  8. package/dist/factory.js.map +1 -1
  9. package/dist/integrations/github/issue-intake.d.ts +15 -0
  10. package/dist/integrations/github/issue-intake.d.ts.map +1 -0
  11. package/dist/integrations/github/issue-intake.js +50 -0
  12. package/dist/integrations/github/issue-intake.js.map +1 -0
  13. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  14. package/dist/integrations/github/issue-reconciler.js +10 -1
  15. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  16. package/dist/integrations/github/rules.d.ts +2 -0
  17. package/dist/integrations/github/rules.d.ts.map +1 -1
  18. package/dist/integrations/github/rules.js +3 -0
  19. package/dist/integrations/github/rules.js.map +1 -1
  20. package/dist/integrations/platform/connect/routes.d.ts +43 -1
  21. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  22. package/dist/integrations/platform/connect/routes.js +82 -7
  23. package/dist/integrations/platform/connect/routes.js.map +1 -1
  24. package/dist/integrations/platform/connect/session-tools.d.ts +12 -0
  25. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -1
  26. package/dist/integrations/platform/connect/session-tools.js +28 -10
  27. package/dist/integrations/platform/connect/session-tools.js.map +1 -1
  28. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
  29. package/dist/integrations/platform/vanta/integration.js +3 -3
  30. package/dist/integrations/platform/vanta/integration.js.map +1 -1
  31. package/dist/integrations/vanta/sync.d.ts +9 -0
  32. package/dist/integrations/vanta/sync.d.ts.map +1 -1
  33. package/dist/integrations/vanta/sync.js +10 -1
  34. package/dist/integrations/vanta/sync.js.map +1 -1
  35. package/dist/routes/board-snapshot.d.ts +5 -5
  36. package/dist/routes/board-snapshot.d.ts.map +1 -1
  37. package/dist/routes/board-snapshot.js +10 -14
  38. package/dist/routes/board-snapshot.js.map +1 -1
  39. package/dist/routes/config.d.ts +11 -2
  40. package/dist/routes/config.d.ts.map +1 -1
  41. package/dist/routes/config.js +242 -75
  42. package/dist/routes/config.js.map +1 -1
  43. package/dist/routes/contracts.d.ts +43 -14
  44. package/dist/routes/contracts.d.ts.map +1 -1
  45. package/dist/routes/contracts.js +27 -17
  46. package/dist/routes/contracts.js.map +1 -1
  47. package/dist/routes/custom-endpoint-url.d.ts +8 -0
  48. package/dist/routes/custom-endpoint-url.d.ts.map +1 -0
  49. package/dist/routes/custom-endpoint-url.js +45 -0
  50. package/dist/routes/custom-endpoint-url.js.map +1 -0
  51. package/dist/routes/custom-provider-source.d.ts +24 -8
  52. package/dist/routes/custom-provider-source.d.ts.map +1 -1
  53. package/dist/routes/custom-provider-source.js +93 -43
  54. package/dist/routes/custom-provider-source.js.map +1 -1
  55. package/dist/routes/intake.d.ts +6 -0
  56. package/dist/routes/intake.d.ts.map +1 -1
  57. package/dist/routes/intake.js +20 -0
  58. package/dist/routes/intake.js.map +1 -1
  59. package/dist/routes/project-sessions.d.ts +15 -3
  60. package/dist/routes/project-sessions.d.ts.map +1 -1
  61. package/dist/routes/project-sessions.js +56 -14
  62. package/dist/routes/project-sessions.js.map +1 -1
  63. package/dist/routes/projects.d.ts +6 -1
  64. package/dist/routes/projects.d.ts.map +1 -1
  65. package/dist/routes/projects.js +19 -3
  66. package/dist/routes/projects.js.map +1 -1
  67. package/dist/routes/provider-credentials.d.ts +10 -1
  68. package/dist/routes/provider-credentials.d.ts.map +1 -1
  69. package/dist/routes/provider-credentials.js +13 -16
  70. package/dist/routes/provider-credentials.js.map +1 -1
  71. package/dist/routes/session-rows.d.ts +1 -1
  72. package/dist/routes/session-rows.d.ts.map +1 -1
  73. package/dist/routes/session-rows.js +38 -42
  74. package/dist/routes/session-rows.js.map +1 -1
  75. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  76. package/dist/routes/source-control-sessions.js +4 -4
  77. package/dist/routes/source-control-sessions.js.map +1 -1
  78. package/dist/routes/surface.d.ts +3 -0
  79. package/dist/routes/surface.d.ts.map +1 -1
  80. package/dist/routes/surface.js +20 -7
  81. package/dist/routes/surface.js.map +1 -1
  82. package/dist/routes/tenant-credentials.d.ts.map +1 -1
  83. package/dist/routes/tenant-credentials.js +4 -4
  84. package/dist/routes/tenant-credentials.js.map +1 -1
  85. package/dist/routes/work-items.d.ts +9 -3
  86. package/dist/routes/work-items.d.ts.map +1 -1
  87. package/dist/routes/work-items.js +39 -16
  88. package/dist/routes/work-items.js.map +1 -1
  89. package/dist/rules/binding-context.d.ts +5 -0
  90. package/dist/rules/binding-context.d.ts.map +1 -1
  91. package/dist/rules/binding-context.js +51 -5
  92. package/dist/rules/binding-context.js.map +1 -1
  93. package/dist/rules/dispatcher.d.ts.map +1 -1
  94. package/dist/rules/dispatcher.js +2 -1
  95. package/dist/rules/dispatcher.js.map +1 -1
  96. package/dist/rules/start-coordinator.d.ts.map +1 -1
  97. package/dist/rules/start-coordinator.js +2 -7
  98. package/dist/rules/start-coordinator.js.map +1 -1
  99. package/dist/sandbox/session-retirement.d.ts +6 -0
  100. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  101. package/dist/sandbox/session-retirement.js +17 -0
  102. package/dist/sandbox/session-retirement.js.map +1 -1
  103. package/dist/session/factory-session.d.ts.map +1 -1
  104. package/dist/session/factory-session.js +2 -1
  105. package/dist/session/factory-session.js.map +1 -1
  106. package/dist/session/live-sessions.d.ts +6 -1
  107. package/dist/session/live-sessions.d.ts.map +1 -1
  108. package/dist/session/live-sessions.js +4 -0
  109. package/dist/session/live-sessions.js.map +1 -1
  110. package/dist/session/run-audit.d.ts +1 -1
  111. package/dist/session/run-audit.d.ts.map +1 -1
  112. package/dist/session/run-audit.js.map +1 -1
  113. package/dist/session/session-row-status.d.ts +3 -3
  114. package/dist/session/session-row-status.js +4 -4
  115. package/dist/session/session-row-status.js.map +1 -1
  116. package/dist/session/session-row-view.d.ts +3 -4
  117. package/dist/session/session-row-view.d.ts.map +1 -1
  118. package/dist/session/session-row-view.js +14 -21
  119. package/dist/session/session-row-view.js.map +1 -1
  120. package/dist/session/session-rows.d.ts +22 -8
  121. package/dist/session/session-rows.d.ts.map +1 -1
  122. package/dist/session/session-rows.js +158 -83
  123. package/dist/session/session-rows.js.map +1 -1
  124. package/dist/session/session-unloader.d.ts +101 -0
  125. package/dist/session/session-unloader.d.ts.map +1 -0
  126. package/dist/session/session-unloader.js +278 -0
  127. package/dist/session/session-unloader.js.map +1 -0
  128. package/dist/session/work-item-repository.d.ts +5 -1
  129. package/dist/session/work-item-repository.d.ts.map +1 -1
  130. package/dist/session/work-item-repository.js +39 -15
  131. package/dist/session/work-item-repository.js.map +1 -1
  132. package/dist/session-list-changes.d.ts +9 -0
  133. package/dist/session-list-changes.d.ts.map +1 -0
  134. package/dist/session-list-changes.js +54 -0
  135. package/dist/session-list-changes.js.map +1 -0
  136. package/dist/storage/announced-lists.d.ts +14 -0
  137. package/dist/storage/announced-lists.d.ts.map +1 -0
  138. package/dist/storage/announced-lists.js +78 -0
  139. package/dist/storage/announced-lists.js.map +1 -0
  140. package/dist/storage/domains/boards/base.d.ts +1 -1
  141. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  142. package/dist/storage/domains/boards/base.js +27 -9
  143. package/dist/storage/domains/boards/base.js.map +1 -1
  144. package/dist/storage/domains/custom-providers/base.d.ts +62 -19
  145. package/dist/storage/domains/custom-providers/base.d.ts.map +1 -1
  146. package/dist/storage/domains/custom-providers/base.js +131 -100
  147. package/dist/storage/domains/custom-providers/base.js.map +1 -1
  148. package/dist/storage/domains/intake/base.d.ts +25 -7
  149. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  150. package/dist/storage/domains/intake/base.js +83 -19
  151. package/dist/storage/domains/intake/base.js.map +1 -1
  152. package/dist/storage/domains/source-control/base.d.ts +8 -0
  153. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  154. package/dist/storage/domains/source-control/base.js +110 -64
  155. package/dist/storage/domains/source-control/base.js.map +1 -1
  156. package/dist/storage/domains/source-control/inmemory.d.ts +4 -0
  157. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  158. package/dist/storage/domains/source-control/inmemory.js +8 -5
  159. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  160. package/dist/storage/domains/work-items/base.d.ts +9 -1
  161. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  162. package/dist/storage/domains/work-items/base.js +43 -11
  163. package/dist/storage/domains/work-items/base.js.map +1 -1
  164. package/dist/tools/read-tools.d.ts +9 -2
  165. package/dist/tools/read-tools.d.ts.map +1 -1
  166. package/dist/tools/read-tools.js +57 -12
  167. package/dist/tools/read-tools.js.map +1 -1
  168. package/dist/tools/session-tools.d.ts +0 -13
  169. package/dist/tools/session-tools.d.ts.map +1 -1
  170. package/dist/tools/session-tools.js +127 -336
  171. package/dist/tools/session-tools.js.map +1 -1
  172. package/dist/tools/work-item-tools.d.ts.map +1 -1
  173. package/dist/tools/work-item-tools.js +91 -23
  174. package/dist/tools/work-item-tools.js.map +1 -1
  175. package/dist/work-items/card-reference.d.ts +21 -0
  176. package/dist/work-items/card-reference.d.ts.map +1 -0
  177. package/dist/work-items/card-reference.js +58 -0
  178. package/dist/work-items/card-reference.js.map +1 -0
  179. package/package.json +8 -8
  180. package/dist/storage/probed-list.d.ts +0 -11
  181. package/dist/storage/probed-list.d.ts.map +0 -1
  182. package/dist/storage/probed-list.js +0 -52
  183. package/dist/storage/probed-list.js.map +0 -1
@@ -0,0 +1,278 @@
1
+ // src/session/session-unloader.ts
2
+ /**
3
+ * Whether the session's sandbox runs a process its process manager tracks, such as a dev server
4
+ * the agent started. The handle lives in this process: a reloaded session gets a new sandbox
5
+ * object that no longer lists it, so the agent could neither read its output nor stop it.
6
+ * Only a running sandbox is asked, because listing would start a stopped one. Rejects when
7
+ * the sandbox cannot be asked.
8
+ */
9
+ async function hasRunningProcess(session) {
10
+ const sandbox = session.getWorkspace?.()?.sandbox;
11
+ if (sandbox?.status !== "running" || !sandbox.processes) return false;
12
+ return (await sandbox.processes.list()).some((process) => process.running);
13
+ }
14
+ /**
15
+ * Whether a session holds work only this process can finish: a run in flight, or a tool
16
+ * parked on an answer. Both live in memory, so a session holding work must stay loaded.
17
+ */
18
+ function sessionHoldsWork(session) {
19
+ return session.suspensions.hasPending() || session.run.isRunning();
20
+ }
21
+ const DEFAULT_IDLE_SESSION_UNLOAD_MS = 18e5;
22
+ const DEFAULT_IDLE_SESSION_SWEEP_INTERVAL_MS = 6e4;
23
+ /**
24
+ * Unloads controller sessions this process no longer needs, so their in-memory state (display
25
+ * state, workspace, bus) can be collected. The controller keeps every session it creates until
26
+ * the host deletes it; unloading is that delete, which keeps the thread, its messages, the
27
+ * session row and the sandbox VM. The next request, run or wake for the session creates it
28
+ * again from storage, as after a restart.
29
+ *
30
+ * A session is never unloaded while it runs, holds a parked tool, or has an event stream open:
31
+ * all three exist only in this process. Membership comes from the controller's notifications,
32
+ * so a session this process never loaded (another replica's) is never touched.
33
+ */
34
+ var SessionUnloader = class {
35
+ #controller;
36
+ #invalidateSession;
37
+ #settle;
38
+ #idleMs;
39
+ #sweepIntervalMs;
40
+ #now;
41
+ #warn;
42
+ #byId = /* @__PURE__ */ new Map();
43
+ /** Streams opened before the session finished loading, counted until it is tracked. */
44
+ #pendingWatchers = /* @__PURE__ */ new Map();
45
+ #unsubscribes = [];
46
+ #timer;
47
+ #sweeping;
48
+ constructor(options) {
49
+ this.#controller = options.controller;
50
+ this.#invalidateSession = options.invalidateSession ?? (() => {});
51
+ this.#settle = options.settle ?? (async () => {});
52
+ this.#idleMs = options.idleMs ?? 18e5;
53
+ this.#sweepIntervalMs = options.sweepIntervalMs ?? 6e4;
54
+ if (!Number.isFinite(this.#idleMs) || this.#idleMs < 0) throw new Error(`idleSessionUnload.idleMs must be a non-negative number of milliseconds, got ${this.#idleMs}`);
55
+ if (!Number.isFinite(this.#sweepIntervalMs) || this.#sweepIntervalMs <= 0) throw new Error(`idleSessionUnload.sweepIntervalMs must be a positive number of milliseconds, got ${this.#sweepIntervalMs}`);
56
+ this.#now = options.now ?? Date.now;
57
+ this.#warn = options.warn ?? ((message, details) => console.warn(`[Mastra Factory] ${message}`, details));
58
+ this.#unsubscribes.push(this.#controller.onSessionCreated((session) => this.#track(session)), this.#controller.onSessionDeleted((session) => this.#untrack(session)));
59
+ }
60
+ #track(session) {
61
+ const id = session.identity.getId();
62
+ this.#byId.get(id)?.unsubscribe();
63
+ const tracked = {
64
+ session,
65
+ lastActiveAt: this.#now(),
66
+ watchers: this.#pendingWatchers.get(id) ?? 0,
67
+ unloadWhenIdle: false,
68
+ unloading: false,
69
+ unsubscribe: () => {}
70
+ };
71
+ this.#pendingWatchers.delete(id);
72
+ tracked.unsubscribe = session.subscribe((event) => {
73
+ tracked.lastActiveAt = this.#now();
74
+ if (event.type === "agent_start") tracked.unloadWhenIdle = false;
75
+ });
76
+ this.#byId.set(id, tracked);
77
+ }
78
+ #untrack(session) {
79
+ const id = session.identity.getId();
80
+ const tracked = this.#byId.get(id);
81
+ if (tracked?.session !== session) return;
82
+ tracked.unsubscribe();
83
+ this.#byId.delete(id);
84
+ if (tracked.watchers > 0) this.#pendingWatchers.set(id, tracked.watchers);
85
+ }
86
+ /** Start sweeping. With a non-positive `idleMs` the sweep only unloads released sessions. */
87
+ start() {
88
+ if (this.#timer) return;
89
+ this.#timer = setInterval(() => void this.sweep(), this.#sweepIntervalMs);
90
+ this.#timer.unref?.();
91
+ }
92
+ async stop() {
93
+ if (this.#timer) clearInterval(this.#timer);
94
+ this.#timer = void 0;
95
+ for (const unsubscribe of this.#unsubscribes.splice(0)) unsubscribe();
96
+ for (const tracked of this.#byId.values()) tracked.unsubscribe();
97
+ this.#byId.clear();
98
+ this.#pendingWatchers.clear();
99
+ await this.#sweeping;
100
+ }
101
+ /** Whether the session is loaded in this process. */
102
+ isLoaded(sessionId) {
103
+ return this.#byId.has(sessionId);
104
+ }
105
+ /** Mark activity that reaches the session without an event, such as a request addressing it. */
106
+ touch(sessionId) {
107
+ const tracked = this.#byId.get(sessionId);
108
+ if (tracked) tracked.lastActiveAt = this.#now();
109
+ }
110
+ /** Count an open event stream on the session; call the returned function when it closes. */
111
+ watch(sessionId) {
112
+ const tracked = this.#byId.get(sessionId);
113
+ if (tracked) tracked.watchers += 1;
114
+ else this.#pendingWatchers.set(sessionId, (this.#pendingWatchers.get(sessionId) ?? 0) + 1);
115
+ let released = false;
116
+ return () => {
117
+ if (released) return;
118
+ released = true;
119
+ const current = this.#byId.get(sessionId);
120
+ if (current && current.watchers > 0) {
121
+ current.watchers -= 1;
122
+ current.lastActiveAt = this.#now();
123
+ return;
124
+ }
125
+ const pending = (this.#pendingWatchers.get(sessionId) ?? 0) - 1;
126
+ if (pending > 0) this.#pendingWatchers.set(sessionId, pending);
127
+ else this.#pendingWatchers.delete(sessionId);
128
+ };
129
+ }
130
+ /**
131
+ * Unload the session now its sandbox was stopped or released. A session still holding work, or
132
+ * followed by an open stream, is unloaded on the first sweep after it goes idle instead, unless
133
+ * it starts a new run first.
134
+ */
135
+ async unloadReleased(sessionId) {
136
+ const tracked = this.#byId.get(sessionId);
137
+ if (!tracked) return "not-loaded";
138
+ const idleSince = tracked.lastActiveAt;
139
+ tracked.unloadWhenIdle = true;
140
+ if (!this.#inUse(tracked)) {
141
+ if (await this.#unload(tracked, () => !this.#inUse(tracked) && tracked.lastActiveAt === idleSince)) return "unloaded";
142
+ if (this.#byId.get(sessionId) !== tracked) return "not-loaded";
143
+ }
144
+ return "deferred";
145
+ }
146
+ /** Unload every session idle past `idleMs`, and every released one now idle. Resolves how many were unloaded. */
147
+ sweep() {
148
+ this.#sweeping ??= this.#sweep().finally(() => {
149
+ this.#sweeping = void 0;
150
+ });
151
+ return this.#sweeping;
152
+ }
153
+ async #sweep() {
154
+ const now = this.#now();
155
+ const due = [];
156
+ for (const tracked of this.#byId.values()) {
157
+ if (tracked.unloading) continue;
158
+ if (this.#inUse(tracked)) {
159
+ tracked.lastActiveAt = now;
160
+ continue;
161
+ }
162
+ const idleFor = now - tracked.lastActiveAt;
163
+ if (tracked.unloadWhenIdle || this.#idleMs > 0 && idleFor >= this.#idleMs) due.push({
164
+ tracked,
165
+ idleSince: tracked.lastActiveAt
166
+ });
167
+ }
168
+ let unloaded = 0;
169
+ for (const { tracked, idleSince } of due) {
170
+ if (!tracked.unloadWhenIdle && await this.#runsProcess(tracked.session)) {
171
+ if (tracked.lastActiveAt === idleSince) tracked.lastActiveAt = this.#now();
172
+ continue;
173
+ }
174
+ const stillIdle = () => !this.#inUse(tracked) && tracked.lastActiveAt === idleSince;
175
+ if (await this.#unload(tracked, stillIdle)) unloaded += 1;
176
+ }
177
+ return unloaded;
178
+ }
179
+ /** A sandbox that cannot be asked counts as running one: unloading would lose the handle for good. */
180
+ async #runsProcess(session) {
181
+ try {
182
+ return await hasRunningProcess(session);
183
+ } catch (error) {
184
+ this.#warn("Factory session kept loaded: its sandbox processes could not be listed", {
185
+ sessionId: session.identity.getId(),
186
+ error: error instanceof Error ? error.message : String(error)
187
+ });
188
+ return true;
189
+ }
190
+ }
191
+ #inUse(tracked) {
192
+ return tracked.watchers > 0 || tracked.session.stream.isActive() || sessionHoldsWork(tracked.session);
193
+ }
194
+ async #unload(tracked, stillIdle) {
195
+ const sessionId = tracked.session.identity.getId();
196
+ if (tracked.unloading || this.#byId.get(sessionId) !== tracked || !stillIdle()) return false;
197
+ tracked.unloading = true;
198
+ try {
199
+ await this.#settle(tracked.session);
200
+ if (this.#byId.get(sessionId) !== tracked || !stillIdle()) return false;
201
+ await this.#invalidateSession(sessionId);
202
+ if (this.#byId.get(sessionId) !== tracked || !stillIdle()) return false;
203
+ return await this.#controller.deleteSession({ sessionId });
204
+ } catch (error) {
205
+ this.#warn("Factory session unload failed", {
206
+ sessionId,
207
+ error: error instanceof Error ? error.message : String(error)
208
+ });
209
+ return false;
210
+ } finally {
211
+ tracked.unloading = false;
212
+ }
213
+ }
214
+ };
215
+ const SESSION_PATH = /\/agent-controller\/[^/]+\/sessions\/([^/]+)/;
216
+ const SESSION_STREAM_PATH = /\/agent-controller\/[^/]+\/sessions\/[^/]+\/stream\/?$/;
217
+ function decodeSegment(segment) {
218
+ try {
219
+ return decodeURIComponent(segment);
220
+ } catch {
221
+ return segment;
222
+ }
223
+ }
224
+ /** The same body, calling `onClose` once when it ends, errors, or the reader cancels it. */
225
+ function closingWith(body, onClose) {
226
+ const reader = body.getReader();
227
+ return new ReadableStream({
228
+ async pull(controller) {
229
+ try {
230
+ const { done, value } = await reader.read();
231
+ if (done) {
232
+ onClose();
233
+ controller.close();
234
+ return;
235
+ }
236
+ controller.enqueue(value);
237
+ } catch (error) {
238
+ onClose();
239
+ controller.error(error);
240
+ }
241
+ },
242
+ async cancel(reason) {
243
+ onClose();
244
+ await reader.cancel(reason);
245
+ }
246
+ });
247
+ }
248
+ /**
249
+ * Reports controller session requests to the unloader: every request addressing a session counts
250
+ * as activity, and an open event stream keeps the session loaded until it closes.
251
+ */
252
+ function createSessionActivityMiddleware(unloader) {
253
+ return async (c, next) => {
254
+ const sessions = unloader();
255
+ const match = sessions ? SESSION_PATH.exec(c.req.path) : null;
256
+ if (!sessions || !match) return next();
257
+ const sessionId = decodeSegment(match[1]);
258
+ sessions.touch(sessionId);
259
+ if (c.req.method !== "GET" || !SESSION_STREAM_PATH.test(c.req.path)) return next();
260
+ const release = sessions.watch(sessionId);
261
+ c.req.raw.signal.addEventListener("abort", release, { once: true });
262
+ try {
263
+ await next();
264
+ } catch (error) {
265
+ release();
266
+ throw error;
267
+ }
268
+ const body = c.res.body;
269
+ if (!body || !c.res.ok) {
270
+ release();
271
+ return;
272
+ }
273
+ c.res = new Response(closingWith(body, release), c.res);
274
+ };
275
+ }
276
+ export { DEFAULT_IDLE_SESSION_SWEEP_INTERVAL_MS, DEFAULT_IDLE_SESSION_UNLOAD_MS, SessionUnloader, createSessionActivityMiddleware, sessionHoldsWork };
277
+
278
+ //# sourceMappingURL=session-unloader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-unloader.js","names":[],"sources":["../../src/session/session-unloader.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\nimport type { MiddlewareHandler } from 'hono';\n\n/** The slice of a live session the unloader reads: its id, its run, its parked tools, and its events. */\nexport interface UnloadableSession {\n readonly identity: { getId(): string };\n readonly run: { isRunning(): boolean };\n readonly stream: { isActive(): boolean };\n readonly suspensions: { hasPending(): boolean };\n getWorkspace?(): UnloadableWorkspace | undefined;\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\ninterface UnloadableWorkspace {\n readonly sandbox?: {\n readonly status?: string;\n readonly processes?: { list(): Promise<Array<{ running: boolean }>> };\n };\n}\n\n/**\n * Whether the session's sandbox runs a process its process manager tracks, such as a dev server\n * the agent started. The handle lives in this process: a reloaded session gets a new sandbox\n * object that no longer lists it, so the agent could neither read its output nor stop it.\n * Only a running sandbox is asked, because listing would start a stopped one. Rejects when\n * the sandbox cannot be asked.\n */\nasync function hasRunningProcess(session: UnloadableSession): Promise<boolean> {\n const sandbox = session.getWorkspace?.()?.sandbox;\n if (sandbox?.status !== 'running' || !sandbox.processes) return false;\n return (await sandbox.processes.list()).some(process => process.running);\n}\n\nexport interface UnloadableController {\n onSessionCreated(listener: (session: UnloadableSession) => void): () => void;\n onSessionDeleted(listener: (session: UnloadableSession) => void): () => void;\n deleteSession(input: { sessionId: string }): Promise<boolean>;\n}\n\n/**\n * Whether a session holds work only this process can finish: a run in flight, or a tool\n * parked on an answer. Both live in memory, so a session holding work must stay loaded.\n */\nexport function sessionHoldsWork(session: Pick<UnloadableSession, 'run' | 'suspensions'>): boolean {\n return session.suspensions.hasPending() || session.run.isRunning();\n}\n\nexport interface IdleSessionUnloadOptions {\n /**\n * How long a session goes without activity before it is unloaded. Default: 30 minutes.\n * `0` turns the idle sweep off while still unloading sessions whose sandbox Factory stops.\n */\n idleMs?: number;\n /** How often idle sessions are looked for. Default: 1 minute. */\n sweepIntervalMs?: number;\n}\n\nexport const DEFAULT_IDLE_SESSION_UNLOAD_MS = 30 * 60_000;\nexport const DEFAULT_IDLE_SESSION_SWEEP_INTERVAL_MS = 60_000;\n\nexport interface SessionUnloaderOptions extends IdleSessionUnloadOptions {\n controller: UnloadableController;\n /** Drops what Factory keeps for the session outside the controller: its workspaces and sandbox handle. */\n invalidateSession?: (sessionId: string) => Promise<void> | void;\n /** Resolves once writes Factory makes through the session after a run, such as its run-end audit, are done. */\n settle?: (session: UnloadableSession) => Promise<void>;\n now?: () => number;\n warn?: (message: string, details: Record<string, unknown>) => void;\n}\n\ninterface TrackedSession {\n session: UnloadableSession;\n lastActiveAt: number;\n /** Open event streams (a browser tab following the session). */\n watchers: number;\n /** Its sandbox was released while it still held work: unload once it is idle. */\n unloadWhenIdle: boolean;\n unloading: boolean;\n unsubscribe: () => void;\n}\n\nexport type SessionUnloadResult = 'unloaded' | 'deferred' | 'not-loaded';\n\n/**\n * Unloads controller sessions this process no longer needs, so their in-memory state (display\n * state, workspace, bus) can be collected. The controller keeps every session it creates until\n * the host deletes it; unloading is that delete, which keeps the thread, its messages, the\n * session row and the sandbox VM. The next request, run or wake for the session creates it\n * again from storage, as after a restart.\n *\n * A session is never unloaded while it runs, holds a parked tool, or has an event stream open:\n * all three exist only in this process. Membership comes from the controller's notifications,\n * so a session this process never loaded (another replica's) is never touched.\n */\nexport class SessionUnloader {\n readonly #controller: UnloadableController;\n readonly #invalidateSession: (sessionId: string) => Promise<void> | void;\n readonly #settle: (session: UnloadableSession) => Promise<void>;\n readonly #idleMs: number;\n readonly #sweepIntervalMs: number;\n readonly #now: () => number;\n readonly #warn: NonNullable<SessionUnloaderOptions['warn']>;\n readonly #byId = new Map<string, TrackedSession>();\n /** Streams opened before the session finished loading, counted until it is tracked. */\n readonly #pendingWatchers = new Map<string, number>();\n readonly #unsubscribes: Array<() => void> = [];\n #timer: ReturnType<typeof setInterval> | undefined;\n #sweeping: Promise<number> | undefined;\n\n constructor(options: SessionUnloaderOptions) {\n this.#controller = options.controller;\n this.#invalidateSession = options.invalidateSession ?? (() => {});\n this.#settle = options.settle ?? (async () => {});\n this.#idleMs = options.idleMs ?? DEFAULT_IDLE_SESSION_UNLOAD_MS;\n this.#sweepIntervalMs = options.sweepIntervalMs ?? DEFAULT_IDLE_SESSION_SWEEP_INTERVAL_MS;\n if (!Number.isFinite(this.#idleMs) || this.#idleMs < 0) {\n throw new Error(`idleSessionUnload.idleMs must be a non-negative number of milliseconds, got ${this.#idleMs}`);\n }\n if (!Number.isFinite(this.#sweepIntervalMs) || this.#sweepIntervalMs <= 0) {\n throw new Error(\n `idleSessionUnload.sweepIntervalMs must be a positive number of milliseconds, got ${this.#sweepIntervalMs}`,\n );\n }\n this.#now = options.now ?? Date.now;\n this.#warn = options.warn ?? ((message, details) => console.warn(`[Mastra Factory] ${message}`, details));\n this.#unsubscribes.push(\n this.#controller.onSessionCreated(session => this.#track(session)),\n this.#controller.onSessionDeleted(session => this.#untrack(session)),\n );\n }\n\n #track(session: UnloadableSession): void {\n const id = session.identity.getId();\n this.#byId.get(id)?.unsubscribe();\n const tracked: TrackedSession = {\n session,\n lastActiveAt: this.#now(),\n watchers: this.#pendingWatchers.get(id) ?? 0,\n unloadWhenIdle: false,\n unloading: false,\n unsubscribe: () => {},\n };\n this.#pendingWatchers.delete(id);\n tracked.unsubscribe = session.subscribe(event => {\n tracked.lastActiveAt = this.#now();\n // A new run means someone is using the session again.\n if (event.type === 'agent_start') tracked.unloadWhenIdle = false;\n });\n this.#byId.set(id, tracked);\n }\n\n #untrack(session: UnloadableSession): void {\n const id = session.identity.getId();\n const tracked = this.#byId.get(id);\n if (tracked?.session !== session) return;\n tracked.unsubscribe();\n this.#byId.delete(id);\n // Streams still open on the deleted session follow whichever session takes its id next.\n if (tracked.watchers > 0) this.#pendingWatchers.set(id, tracked.watchers);\n }\n\n /** Start sweeping. With a non-positive `idleMs` the sweep only unloads released sessions. */\n start(): void {\n if (this.#timer) return;\n this.#timer = setInterval(() => void this.sweep(), this.#sweepIntervalMs);\n this.#timer.unref?.();\n }\n\n async stop(): Promise<void> {\n if (this.#timer) clearInterval(this.#timer);\n this.#timer = undefined;\n for (const unsubscribe of this.#unsubscribes.splice(0)) unsubscribe();\n for (const tracked of this.#byId.values()) tracked.unsubscribe();\n this.#byId.clear();\n this.#pendingWatchers.clear();\n await this.#sweeping;\n }\n\n /** Whether the session is loaded in this process. */\n isLoaded(sessionId: string): boolean {\n return this.#byId.has(sessionId);\n }\n\n /** Mark activity that reaches the session without an event, such as a request addressing it. */\n touch(sessionId: string): void {\n const tracked = this.#byId.get(sessionId);\n if (tracked) tracked.lastActiveAt = this.#now();\n }\n\n /** Count an open event stream on the session; call the returned function when it closes. */\n watch(sessionId: string): () => void {\n const tracked = this.#byId.get(sessionId);\n if (tracked) tracked.watchers += 1;\n else this.#pendingWatchers.set(sessionId, (this.#pendingWatchers.get(sessionId) ?? 0) + 1);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = this.#byId.get(sessionId);\n if (current && current.watchers > 0) {\n current.watchers -= 1;\n current.lastActiveAt = this.#now();\n return;\n }\n const pending = (this.#pendingWatchers.get(sessionId) ?? 0) - 1;\n if (pending > 0) this.#pendingWatchers.set(sessionId, pending);\n else this.#pendingWatchers.delete(sessionId);\n };\n }\n\n /**\n * Unload the session now its sandbox was stopped or released. A session still holding work, or\n * followed by an open stream, is unloaded on the first sweep after it goes idle instead, unless\n * it starts a new run first.\n */\n async unloadReleased(sessionId: string): Promise<SessionUnloadResult> {\n const tracked = this.#byId.get(sessionId);\n if (!tracked) return 'not-loaded';\n const idleSince = tracked.lastActiveAt;\n // Marked before the unload awaits, so a run starting meanwhile still cancels the release.\n tracked.unloadWhenIdle = true;\n if (!this.#inUse(tracked)) {\n // Anything that touched the session since, such as its run's end, leaves it to the sweep.\n if (await this.#unload(tracked, () => !this.#inUse(tracked) && tracked.lastActiveAt === idleSince)) {\n return 'unloaded';\n }\n if (this.#byId.get(sessionId) !== tracked) return 'not-loaded';\n }\n return 'deferred';\n }\n\n /** Unload every session idle past `idleMs`, and every released one now idle. Resolves how many were unloaded. */\n sweep(): Promise<number> {\n this.#sweeping ??= this.#sweep().finally(() => {\n this.#sweeping = undefined;\n });\n return this.#sweeping;\n }\n\n async #sweep(): Promise<number> {\n const now = this.#now();\n const due: Array<{ tracked: TrackedSession; idleSince: number }> = [];\n for (const tracked of this.#byId.values()) {\n if (tracked.unloading) continue;\n if (this.#inUse(tracked)) {\n // The idle clock starts once the work ends, not when the work started.\n tracked.lastActiveAt = now;\n continue;\n }\n const idleFor = now - tracked.lastActiveAt;\n if (tracked.unloadWhenIdle || (this.#idleMs > 0 && idleFor >= this.#idleMs)) {\n due.push({ tracked, idleSince: tracked.lastActiveAt });\n }\n }\n let unloaded = 0;\n for (const { tracked, idleSince } of due) {\n // A released session's sandbox was stopped with it; an idle one may still run a process.\n if (!tracked.unloadWhenIdle && (await this.#runsProcess(tracked.session))) {\n // Looked at again once another idle timeout has passed, not on every sweep.\n if (tracked.lastActiveAt === idleSince) tracked.lastActiveAt = this.#now();\n continue;\n }\n // Anything that touched the session since it was picked keeps it.\n const stillIdle = () => !this.#inUse(tracked) && tracked.lastActiveAt === idleSince;\n if (await this.#unload(tracked, stillIdle)) unloaded += 1;\n }\n return unloaded;\n }\n\n /** A sandbox that cannot be asked counts as running one: unloading would lose the handle for good. */\n async #runsProcess(session: UnloadableSession): Promise<boolean> {\n try {\n return await hasRunningProcess(session);\n } catch (error) {\n this.#warn('Factory session kept loaded: its sandbox processes could not be listed', {\n sessionId: session.identity.getId(),\n error: error instanceof Error ? error.message : String(error),\n });\n return true;\n }\n }\n\n #inUse(tracked: TrackedSession): boolean {\n return tracked.watchers > 0 || tracked.session.stream.isActive() || sessionHoldsWork(tracked.session);\n }\n\n async #unload(tracked: TrackedSession, stillIdle: () => boolean): Promise<boolean> {\n const sessionId = tracked.session.identity.getId();\n if (tracked.unloading || this.#byId.get(sessionId) !== tracked || !stillIdle()) return false;\n tracked.unloading = true;\n try {\n // Deleting the session unbinds its thread, so writes still going through it would fail.\n await this.#settle(tracked.session);\n if (this.#byId.get(sessionId) !== tracked || !stillIdle()) return false;\n // Factory's caches go first: a request racing the unload then rebuilds them for the\n // session it gets, instead of having them dropped from under it.\n await this.#invalidateSession(sessionId);\n if (this.#byId.get(sessionId) !== tracked || !stillIdle()) return false;\n return await this.#controller.deleteSession({ sessionId });\n } catch (error) {\n this.#warn('Factory session unload failed', {\n sessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\n } finally {\n tracked.unloading = false;\n }\n }\n}\n\nconst SESSION_PATH = /\\/agent-controller\\/[^/]+\\/sessions\\/([^/]+)/;\nconst SESSION_STREAM_PATH = /\\/agent-controller\\/[^/]+\\/sessions\\/[^/]+\\/stream\\/?$/;\n\nfunction decodeSegment(segment: string): string {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n}\n\n/** The same body, calling `onClose` once when it ends, errors, or the reader cancels it. */\nfunction closingWith(body: ReadableStream<Uint8Array>, onClose: () => void): ReadableStream<Uint8Array> {\n const reader = body.getReader();\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n onClose();\n controller.close();\n return;\n }\n controller.enqueue(value);\n } catch (error) {\n onClose();\n controller.error(error);\n }\n },\n async cancel(reason) {\n onClose();\n await reader.cancel(reason);\n },\n });\n}\n\n/**\n * Reports controller session requests to the unloader: every request addressing a session counts\n * as activity, and an open event stream keeps the session loaded until it closes.\n */\nexport function createSessionActivityMiddleware(unloader: () => SessionUnloader | undefined): MiddlewareHandler {\n return async (c, next) => {\n const sessions = unloader();\n const match = sessions ? SESSION_PATH.exec(c.req.path) : null;\n if (!sessions || !match) return next();\n const sessionId = decodeSegment(match[1]!);\n sessions.touch(sessionId);\n if (c.req.method !== 'GET' || !SESSION_STREAM_PATH.test(c.req.path)) return next();\n\n const release = sessions.watch(sessionId);\n c.req.raw.signal.addEventListener('abort', release, { once: true });\n try {\n await next();\n } catch (error) {\n release();\n throw error;\n }\n const body = c.res.body;\n if (!body || !c.res.ok) {\n release();\n return;\n }\n c.res = new Response(closingWith(body, release), c.res);\n };\n}\n"],"mappings":";;;;;;;;AA2BA,eAAe,kBAAkB,SAA8C;CAC7E,MAAM,UAAU,QAAQ,eAAe,CAAC,EAAE;CAC1C,IAAI,SAAS,WAAW,aAAa,CAAC,QAAQ,WAAW,OAAO;CAChE,QAAQ,MAAM,QAAQ,UAAU,KAAK,EAAA,CAAG,MAAK,YAAW,QAAQ,OAAO;AACzE;;;;;AAYA,SAAgB,iBAAiB,SAAkE;CACjG,OAAO,QAAQ,YAAY,WAAW,KAAK,QAAQ,IAAI,UAAU;AACnE;AAYA,MAAa,iCAAiC;AAC9C,MAAa,yCAAyC;;;;;;;;;;;;AAoCtD,IAAa,kBAAb,MAA6B;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA,wBAAiB,IAAI,IAA4B;;CAEjD,mCAA4B,IAAI,IAAoB;CACpD,gBAA4C,CAAC;CAC7C;CACA;CAEA,YAAY,SAAiC;EAC3C,KAAK,cAAc,QAAQ;EAC3B,KAAK,qBAAqB,QAAQ,4BAA4B,CAAC;EAC/D,KAAK,UAAU,QAAQ,WAAW,YAAY,CAAC;EAC/C,KAAK,UAAU,QAAQ,UAAA;EACvB,KAAK,mBAAmB,QAAQ,mBAAA;EAChC,IAAI,CAAC,OAAO,SAAS,KAAK,OAAO,KAAK,KAAK,UAAU,GACnD,MAAM,IAAI,MAAM,+EAA+E,KAAK,SAAS;EAE/G,IAAI,CAAC,OAAO,SAAS,KAAK,gBAAgB,KAAK,KAAK,oBAAoB,GACtE,MAAM,IAAI,MACR,oFAAoF,KAAK,kB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MAAM,QAAQ,WAAW,aAAa,KAAK,EAAE,IAAI,IAAI,IAAI;EACzD,IAAI,CAAC,YAAY,CAAC,OAAO,OAAO,KAAK;EACrC,MAAM,YAAY,cAAc,MAAM,EAAG;EACzC,SAAS,MAAM,SAAS;EACxB,IAAI,EAAE,IAAI,WAAW,SAAS,CAAC,oBAAoB,KAAK,EAAE,IAAI,IAAI,GAAG,OAAO,KAAK;EAEjF,MAAM,UAAU,SAAS,MAAM,SAAS;EACxC,EAAE,IAAI,IAAI,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAClE,IAAI;GACF,MAAM,KAAK;EACb,SAAS,OAAO;GACd,QAAQ;GACR,MAAM;EACR;EACA,MAAM,OAAO,EAAE,IAAI;EACnB,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,IAAI;GACtB,QAAQ;GACR;EACF;EACA,EAAE,MAAM,IAAI,SAAS,YAAY,MAAM,OAAO,GAAG,EAAE,GAAG;CACxD;AACF"}
@@ -1,3 +1,4 @@
1
+ import type { IntakeStorage } from '../storage/domains/intake/base.js';
1
2
  import type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';
2
3
  import type { Card } from '../storage/domains/work-items/base.js';
3
4
  export type WorkItemRepositoryResolution = {
@@ -16,7 +17,9 @@ export declare function resolveWorkItemRepository(args: {
16
17
  orgId: string;
17
18
  factoryProjectId: string;
18
19
  item: Pick<Card, 'metadata'> & {
19
- workItem: Pick<Card['workItem'], 'metadata'>;
20
+ workItem: Pick<Card['workItem'], 'metadata'> & {
21
+ url?: string | null;
22
+ };
20
23
  };
21
24
  linearRepositoryMap?: Record<string, string>;
22
25
  }): Promise<WorkItemRepositoryResolution>;
@@ -46,6 +49,7 @@ export type RunRepositoryResolution = {
46
49
  export declare function resolveRunRepository(args: Parameters<typeof resolveWorkItemRepository>[0] & {
47
50
  boundProjectRepositoryId?: string;
48
51
  }): Promise<RunRepositoryResolution>;
52
+ export declare function resolveRunRepositoryFromIntake(intake: Pick<IntakeStorage, 'getConfig'> | undefined, args: Omit<Parameters<typeof resolveRunRepository>[0], 'linearRepositoryMap'>): Promise<RunRepositoryResolution>;
49
53
  /** Card metadata recording the `repository` a run chose for a card that named none. */
50
54
  export declare const REPOSITORY_CHOICE_KEY = "repositoryChoice";
51
55
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"work-item-repository.d.ts","sourceRoot":"","sources":["../../src/session/work-item-repository.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAC5F,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AAGlE,MAAM,MAAM,4BAA4B,GACpC;IAAE,MAAM,EAAE,UAAU,CAAC;IAAC,mBAAmB,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GACjE;IAAE,MAAM,EAAE,UAAU,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GACpC;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,UAAU,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAkFlD,wBAAsB,yBAAyB,CAAC,IAAI,EAAE;IACpD,aAAa,EAAE,0BAA0B,CAAC;IAC1C,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,GAAG;QAAE,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC,CAAA;KAAE,CAAC;IAChF,mBAAmB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC9C,GAAG,OAAO,CAAC,4BAA4B,CAAC,CA4CxC;AAED,MAAM,MAAM,uBAAuB,GAC/B;IACE,MAAM,EAAE,UAAU,CAAC;IACnB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb;;;O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O,oBAAoB,CAAC,CAAC,CAAC,CAAC,EAAE,qBAAqB,CAAC,GAC5E,OAAO,CAAC,uBAAuB,CAAC,CAGlC;AAED,uFAAuF;AACvF,eAAO,MAAM,qBAAqB,qBAAqB,CAAC;AAExD;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAIzF;AAID,iFAAiF;AACjF,wBAAgB,wBAAwB,CACtC,UAAU,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE;QAAE,YAAY,EAAE,MAAM,EAAE,CAAA;KAAE,CAAA;CAAE,EAClE,OAAO,EAAE,MAAM,GACd,MAAM,CASR;AAED,wBAAgB,0BAA0B,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAEvE"}
@@ -31,19 +31,21 @@ async function listLinkedRepositories(args) {
31
31
  }
32
32
  return linked;
33
33
  }
34
+ const PROVIDER_REPOSITORY_IDS = /* @__PURE__ */ new Map([["github", {
35
+ key: "githubRepositoryId",
36
+ label: "GitHub"
37
+ }], ["gitlab", {
38
+ key: "gitlabProjectId",
39
+ label: "GitLab"
40
+ }]]);
34
41
  function getExternalRepositoryId(integrationId, metadata) {
35
- let id;
36
- switch (integrationId) {
37
- case "github":
38
- id = metadata.githubRepositoryId;
39
- break;
40
- case "gitlab":
41
- id = metadata.gitlabProjectId;
42
- break;
43
- default: return;
44
- }
42
+ const provider = PROVIDER_REPOSITORY_IDS.get(integrationId);
43
+ const id = provider ? metadata[provider.key] : void 0;
45
44
  return id == null ? void 0 : String(id);
46
45
  }
46
+ function otherProviderLabel(integrationId, metadata) {
47
+ for (const [id, provider] of PROVIDER_REPOSITORY_IDS) if (id !== integrationId && metadata[provider.key] != null) return provider.label;
48
+ }
47
49
  /**
48
50
  * The one link among `matches` a run can use. A repository can be linked more
49
51
  * than once (a provider-app reinstall adds a second link for the same slug),
@@ -66,6 +68,10 @@ function resolvedRepository(repository) {
66
68
  slug: repository.slug
67
69
  };
68
70
  }
71
+ const PROVIDER_ITEM_URL = /^https?:\/\/[^/]+\/(.+?)(?:\/-)?\/(?:issues|pull|merge_requests)\/\d+(?:[/?#]|$)/;
72
+ function repositoryNameFromUrl(url) {
73
+ return url ? PROVIDER_ITEM_URL.exec(url)?.[1] : void 0;
74
+ }
69
75
  async function resolveWorkItemRepository(args) {
70
76
  const { sourceControl, item, linearRepositoryMap } = args;
71
77
  const metadata = item.workItem.metadata ?? {};
@@ -78,6 +84,11 @@ async function resolveWorkItemRepository(args) {
78
84
  const match = pickLink(linked.filter((repository) => repository.externalId === externalRepositorySignal));
79
85
  if (match) return resolvedRepository(match);
80
86
  }
87
+ const otherProvider = externalRepositorySignal === void 0 ? otherProviderLabel(sourceControl.integrationId, metadata) : void 0;
88
+ if (otherProvider !== void 0) return {
89
+ status: "unlinked",
90
+ hint: `This card comes from ${otherProvider}, and no ${otherProvider} repository is linked to this Factory.`
91
+ };
81
92
  if (repositorySignal) {
82
93
  const match = findRepositoryBySlug(linked, repositorySignal);
83
94
  return match ? resolvedRepository(match) : {
@@ -85,10 +96,13 @@ async function resolveWorkItemRepository(args) {
85
96
  hint: `Repository ${repositorySignal} is not linked to this Factory.`
86
97
  };
87
98
  }
88
- if (externalRepositorySignal !== void 0) return {
89
- status: "unlinked",
90
- hint: `Source-control repository ${externalRepositorySignal} is not linked to this Factory.`
91
- };
99
+ if (externalRepositorySignal !== void 0) {
100
+ const name = repositoryNameFromUrl(item.workItem.url);
101
+ return {
102
+ status: "unlinked",
103
+ hint: name ? `Repository ${name} is not linked to this Factory.` : `Source-control repository ${externalRepositorySignal} is not linked to this Factory.`
104
+ };
105
+ }
92
106
  if (mappedRepository) {
93
107
  const match = findRepositoryBySlug(linked, mappedRepository);
94
108
  return match ? resolvedRepository(match) : {
@@ -162,6 +176,16 @@ async function resolveRunRepository(args) {
162
176
  unnamed
163
177
  };
164
178
  }
179
+ async function resolveRunRepositoryFromIntake(intake, args) {
180
+ const intakeConfig = await intake?.getConfig({
181
+ orgId: args.orgId,
182
+ integrationIds: ["linear"]
183
+ });
184
+ return resolveRunRepository({
185
+ ...args,
186
+ linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject
187
+ });
188
+ }
165
189
  /** Card metadata recording the `repository` a run chose for a card that named none. */
166
190
  const REPOSITORY_CHOICE_KEY = "repositoryChoice";
167
191
  /**
@@ -186,6 +210,6 @@ function runRepositoryInstruction(repository, ownSlug) {
186
210
  function isRunRepositoryInstruction(instruction) {
187
211
  return instruction.startsWith("Target repository: ") || instruction.startsWith(UNNAMED_REPOSITORY_INSTRUCTION);
188
212
  }
189
- export { REPOSITORY_CHOICE_KEY, isRunRepositoryInstruction, repositoryChosenByRun, resolveRunRepository, resolveWorkItemRepository, runRepositoryInstruction };
213
+ export { REPOSITORY_CHOICE_KEY, isRunRepositoryInstruction, repositoryChosenByRun, resolveRunRepository, resolveRunRepositoryFromIntake, resolveWorkItemRepository, runRepositoryInstruction };
190
214
 
191
215
  //# sourceMappingURL=work-item-repository.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"work-item-repository.js","names":[],"sources":["../../src/session/work-item-repository.ts"],"sourcesContent":["import { SourceControlConnectionNotFoundError } from '../storage/domains/source-control/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { Card } from '../storage/domains/work-items/base.js';\nimport { resolveEnvironmentRepositories } from './environment-repositories.js';\n\nexport type WorkItemRepositoryResolution =\n | { status: 'resolved'; projectRepositoryId: string; slug: string }\n | { status: 'unlinked'; hint: string }\n | { status: 'ambiguous'; candidates: string[] };\n\ninterface LinkedRepository {\n projectRepositoryId: string;\n externalId: string;\n slug: string;\n inEnvironment: boolean;\n}\n\nasync function listLinkedRepositories(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n}): Promise<LinkedRepository[]> {\n const { sourceControl, orgId, factoryProjectId } = args;\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n const linked: LinkedRepository[] = [];\n\n for (const connection of connections.filter(candidate => candidate.integrationId === sourceControl.integrationId)) {\n try {\n const projectRepositories = await sourceControl.projectRepositories.list({ orgId, connectionId: connection.id });\n const repositories = await Promise.all(\n projectRepositories.map(async projectRepository => ({\n projectRepository,\n repository: await sourceControl.repositories.get({ orgId, id: projectRepository.repositoryId }),\n })),\n );\n for (const { projectRepository, repository } of repositories) {\n if (repository) {\n linked.push({\n projectRepositoryId: projectRepository.id,\n externalId: repository.externalId,\n slug: repository.slug,\n inEnvironment: projectRepository.inEnvironment,\n });\n }\n }\n } catch (error) {\n if (!(error instanceof SourceControlConnectionNotFoundError)) throw error;\n // A stale provider connection must not hide healthy linked repositories.\n }\n }\n\n return linked;\n}\n\nfunction getExternalRepositoryId(integrationId: string, metadata: Record<string, unknown>): string | undefined {\n let id: unknown;\n switch (integrationId) {\n case 'github':\n id = metadata.githubRepositoryId;\n break;\n case 'gitlab':\n id = metadata.gitlabProjectId;\n break;\n default:\n return undefined;\n }\n return id == null ? undefined : String(id);\n}\n\n/**\n * The one link among `matches` a run can use. A repository can be linked more\n * than once (a provider-app reinstall adds a second link for the same slug),\n * but only one of those links is in the environment, and only an environment\n * link can start a session, so it wins over its out-of-environment duplicates.\n */\nfunction pickLink(matches: LinkedRepository[]): LinkedRepository | undefined {\n if (matches.length === 1) return matches[0];\n const inEnvironment = matches.filter(repository => repository.inEnvironment);\n return inEnvironment.length === 1 ? inEnvironment[0] : undefined;\n}\n\nfunction findRepositoryBySlug(repositories: LinkedRepository[], slug: string) {\n const matches = repositories.filter(repository => repository.slug === slug);\n return pickLink(matches) ?? matches[0];\n}\n\nfunction resolvedRepository(repository: LinkedRepository): WorkItemRepositoryResolution {\n return { status: 'resolved', projectRepositoryId: repository.projectRepositoryId, slug: repository.slug };\n}\n\nexport async function resolveWorkItemRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n item: Pick<Card, 'metadata'> & { workItem: Pick<Card['workItem'], 'metadata'> };\n linearRepositoryMap?: Record<string, string>;\n}): Promise<WorkItemRepositoryResolution> {\n const { sourceControl, item, linearRepositoryMap } = args;\n const metadata = item.workItem.metadata ?? {};\n const linked = await listLinkedRepositories(args);\n const repositorySignal = typeof item.metadata?.repository === 'string' ? item.metadata.repository : undefined;\n const externalRepositorySignal = getExternalRepositoryId(sourceControl.integrationId, metadata);\n const linearProjectId = typeof metadata.linearProjectId === 'string' ? metadata.linearProjectId : undefined;\n const mappedRepository = linearProjectId ? linearRepositoryMap?.[linearProjectId] : undefined;\n\n // The provider id survives repository renames, so it outranks a possibly stale slug.\n if (externalRepositorySignal !== undefined) {\n const match = pickLink(linked.filter(repository => repository.externalId === externalRepositorySignal));\n if (match) return resolvedRepository(match);\n }\n\n if (repositorySignal) {\n const match = findRepositoryBySlug(linked, repositorySignal);\n return match\n ? resolvedRepository(match)\n : { status: 'unlinked', hint: `Repository ${repositorySignal} is not linked to this Factory.` };\n }\n\n if (externalRepositorySignal !== undefined) {\n return {\n status: 'unlinked',\n hint: `Source-control repository ${externalRepositorySignal} is not linked to this Factory.`,\n };\n }\n\n if (mappedRepository) {\n const match = findRepositoryBySlug(linked, mappedRepository);\n return match\n ? resolvedRepository(match)\n : { status: 'unlinked', hint: `Mapped repository ${mappedRepository} is not linked to this Factory.` };\n }\n\n const candidates = [...new Set(linked.map(repository => repository.slug))].sort();\n if (candidates.length === 0) {\n return { status: 'unlinked', hint: 'This Factory has no linked source-control repositories.' };\n }\n // Every link shares the one slug here, so prefer the environment link among them.\n const onlyRepository = candidates.length === 1 ? (pickLink(linked) ?? linked[0]) : undefined;\n if (onlyRepository) return resolvedRepository(onlyRepository);\n return { status: 'ambiguous', candidates };\n}\n\nexport type RunRepositoryResolution =\n | {\n status: 'resolved';\n projectRepositoryId: string;\n slug: string;\n /**\n * Set when the card names no repository: the sandbox repositories its\n * agent chooses among. The run is filed under `slug` until it does.\n */\n unnamed?: { repositories: string[] };\n }\n | { status: 'unlinked'; hint: string };\n\n/**\n * Where a run on `item` is filed. A card that names its repository resolves\n * exactly as {@link resolveWorkItemRepository} does. A card that names none\n * among several repositories is not refused: the sandbox holds every\n * environment repository, so the run stays in `boundProjectRepositoryId` (the\n * session already working on the card) or else in the environment's first\n * repository, and its agent determines which repository the card belongs to.\n */\nexport async function resolveRunRepository(\n args: Parameters<typeof resolveWorkItemRepository>[0] & { boundProjectRepositoryId?: string },\n): Promise<RunRepositoryResolution> {\n const resolution = await resolveWorkItemRepository(args);\n if (resolution.status !== 'ambiguous') return resolution;\n const { sourceControl, orgId, factoryProjectId, boundProjectRepositoryId } = args;\n const environment = await resolveEnvironmentRepositories({ sourceControl, orgId, factoryProjectId });\n const unnamed = { repositories: environment.map(entry => entry.repository.slug) };\n if (boundProjectRepositoryId !== undefined) {\n const link = await sourceControl.projectRepositories.get({ orgId, id: boundProjectRepositoryId });\n const linked = link && (await sourceControl.repositories.get({ orgId, id: link.repositoryId }));\n const currentLinks = link\n ? await sourceControl.projectRepositories.list({ orgId, connectionId: link.connectionId })\n : [];\n if (\n !linked ||\n !resolution.candidates.includes(linked.slug) ||\n !currentLinks.some(candidate => candidate.id === boundProjectRepositoryId)\n ) {\n return { status: 'unlinked', hint: 'The existing session repository is not linked to this Factory.' };\n }\n return { status: 'resolved', projectRepositoryId: boundProjectRepositoryId, slug: linked.slug, unnamed };\n }\n const primary = environment[0];\n if (!primary) {\n return { status: 'unlinked', hint: 'None of the repositories linked to this Factory is in its environment.' };\n }\n return { status: 'resolved', projectRepositoryId: primary.link.id, slug: primary.repository.slug, unnamed };\n}\n\n/** Card metadata recording the `repository` a run chose for a card that named none. */\nexport const REPOSITORY_CHOICE_KEY = 'repositoryChoice';\n\n/**\n * Whether a run recorded `slug` as the card's repository. Every role session\n * on the card was filed before it named a repository, so under another one;\n * they may keep working on the card, in `slug`. A repository set any other\n * way (intake, a person) no longer matches the recorded choice and still\n * refuses a session filed elsewhere.\n */\nexport function repositoryChosenByRun(item: Pick<Card, 'metadata'>, slug: string): boolean {\n const choice = item.metadata?.[REPOSITORY_CHOICE_KEY];\n if (typeof choice !== 'object' || choice === null) return false;\n return item.metadata?.repository === slug && (choice as Record<string, unknown>).slug === slug;\n}\n\nconst UNNAMED_REPOSITORY_INSTRUCTION = 'This card names no repository.';\n\n/** The plugin instruction telling a run's agent which repository it works in. */\nexport function runRepositoryInstruction(\n repository: { slug: string; unnamed?: { repositories: string[] } },\n ownSlug: string,\n): string {\n if (repository.unnamed) {\n return `${UNNAMED_REPOSITORY_INSTRUCTION} This session's sandbox holds ${repository.unnamed.repositories.join(', ')}. Before editing files, determine from the card which of them it belongs to and work in that repository's checkout; pass it as \\`repository\\` to the source_control_* tools (they default to ${ownSlug}). The first push or change request records it on the card. If the card belongs to none of them, stop and say so.`;\n }\n const elsewhere =\n repository.slug === ownSlug\n ? ''\n : ` This session is filed under ${ownSlug}, so pass \\`repository: ${repository.slug}\\` to the source_control_* tools.`;\n return `Target repository: ${repository.slug}. Before editing files or creating a pull request, verify this session's checkout matches the target repository.${elsewhere}`;\n}\n\nexport function isRunRepositoryInstruction(instruction: string): boolean {\n return instruction.startsWith('Target repository: ') || instruction.startsWith(UNNAMED_REPOSITORY_INSTRUCTION);\n}\n"],"mappings":";;;AAiBA,eAAe,uBAAuB,MAIN;CAC9B,MAAM,EAAE,eAAe,OAAO,qBAAqB;CACnD,MAAM,cAAc,MAAM,cAAc,YAAY,KAAK;EAAE;EAAO;CAAiB,CAAC;CACpF,MAAM,SAA6B,CAAC;CAEpC,KAAK,MAAM,cAAc,YAAY,QAAO,cAAa,UAAU,kBAAkB,cAAc,aAAa,GAC9G,IAAI;EACF,MAAM,sBAAsB,MAAM,cAAc,oBAAoB,KAAK;GAAE;GAAO,cAAc,WAAW;EAAG,CAAC;EAC/G,MAAM,eAAe,MAAM,QAAQ,IACjC,oBAAoB,IAAI,OAAM,uBAAsB;GAClD;GACA,YAAY,MAAM,cAAc,aAA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AACjK;AAEA,SAAgB,2BAA2B,aAA8B;CACvE,OAAO,YAAY,WAAW,qBAAqB,KAAK,YAAY,WAAW,8BAA8B;AAC/G"}
1
+ {"version":3,"file":"work-item-repository.js","names":[],"sources":["../../src/session/work-item-repository.ts"],"sourcesContent":["import type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport { SourceControlConnectionNotFoundError } from '../storage/domains/source-control/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { Card } from '../storage/domains/work-items/base.js';\nimport { resolveEnvironmentRepositories } from './environment-repositories.js';\n\nexport type WorkItemRepositoryResolution =\n | { status: 'resolved'; projectRepositoryId: string; slug: string }\n | { status: 'unlinked'; hint: string }\n | { status: 'ambiguous'; candidates: string[] };\n\ninterface LinkedRepository {\n projectRepositoryId: string;\n externalId: string;\n slug: string;\n inEnvironment: boolean;\n}\n\nasync function listLinkedRepositories(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n}): Promise<LinkedRepository[]> {\n const { sourceControl, orgId, factoryProjectId } = args;\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n const linked: LinkedRepository[] = [];\n\n for (const connection of connections.filter(candidate => candidate.integrationId === sourceControl.integrationId)) {\n try {\n const projectRepositories = await sourceControl.projectRepositories.list({ orgId, connectionId: connection.id });\n const repositories = await Promise.all(\n projectRepositories.map(async projectRepository => ({\n projectRepository,\n repository: await sourceControl.repositories.get({ orgId, id: projectRepository.repositoryId }),\n })),\n );\n for (const { projectRepository, repository } of repositories) {\n if (repository) {\n linked.push({\n projectRepositoryId: projectRepository.id,\n externalId: repository.externalId,\n slug: repository.slug,\n inEnvironment: projectRepository.inEnvironment,\n });\n }\n }\n } catch (error) {\n if (!(error instanceof SourceControlConnectionNotFoundError)) throw error;\n // A stale provider connection must not hide healthy linked repositories.\n }\n }\n\n return linked;\n}\n\nconst PROVIDER_REPOSITORY_IDS = new Map([\n ['github', { key: 'githubRepositoryId', label: 'GitHub' }],\n ['gitlab', { key: 'gitlabProjectId', label: 'GitLab' }],\n]);\n\nfunction getExternalRepositoryId(integrationId: string, metadata: Record<string, unknown>): string | undefined {\n const provider = PROVIDER_REPOSITORY_IDS.get(integrationId);\n const id = provider ? metadata[provider.key] : undefined;\n return id == null ? undefined : String(id);\n}\n\nfunction otherProviderLabel(integrationId: string, metadata: Record<string, unknown>): string | undefined {\n for (const [id, provider] of PROVIDER_REPOSITORY_IDS) {\n if (id !== integrationId && metadata[provider.key] != null) return provider.label;\n }\n return undefined;\n}\n\n/**\n * The one link among `matches` a run can use. A repository can be linked more\n * than once (a provider-app reinstall adds a second link for the same slug),\n * but only one of those links is in the environment, and only an environment\n * link can start a session, so it wins over its out-of-environment duplicates.\n */\nfunction pickLink(matches: LinkedRepository[]): LinkedRepository | undefined {\n if (matches.length === 1) return matches[0];\n const inEnvironment = matches.filter(repository => repository.inEnvironment);\n return inEnvironment.length === 1 ? inEnvironment[0] : undefined;\n}\n\nfunction findRepositoryBySlug(repositories: LinkedRepository[], slug: string) {\n const matches = repositories.filter(repository => repository.slug === slug);\n return pickLink(matches) ?? matches[0];\n}\n\nfunction resolvedRepository(repository: LinkedRepository): WorkItemRepositoryResolution {\n return { status: 'resolved', projectRepositoryId: repository.projectRepositoryId, slug: repository.slug };\n}\n\nconst PROVIDER_ITEM_URL = /^https?:\\/\\/[^/]+\\/(.+?)(?:\\/-)?\\/(?:issues|pull|merge_requests)\\/\\d+(?:[/?#]|$)/;\n\nfunction repositoryNameFromUrl(url: string | null | undefined): string | undefined {\n return url ? PROVIDER_ITEM_URL.exec(url)?.[1] : undefined;\n}\n\nexport async function resolveWorkItemRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n item: Pick<Card, 'metadata'> & { workItem: Pick<Card['workItem'], 'metadata'> & { url?: string | null } };\n linearRepositoryMap?: Record<string, string>;\n}): Promise<WorkItemRepositoryResolution> {\n const { sourceControl, item, linearRepositoryMap } = args;\n const metadata = item.workItem.metadata ?? {};\n const linked = await listLinkedRepositories(args);\n const repositorySignal = typeof item.metadata?.repository === 'string' ? item.metadata.repository : undefined;\n const externalRepositorySignal = getExternalRepositoryId(sourceControl.integrationId, metadata);\n const linearProjectId = typeof metadata.linearProjectId === 'string' ? metadata.linearProjectId : undefined;\n const mappedRepository = linearProjectId ? linearRepositoryMap?.[linearProjectId] : undefined;\n\n // The provider id survives repository renames, so it outranks a possibly stale slug.\n if (externalRepositorySignal !== undefined) {\n const match = pickLink(linked.filter(repository => repository.externalId === externalRepositorySignal));\n if (match) return resolvedRepository(match);\n }\n\n const otherProvider =\n externalRepositorySignal === undefined ? otherProviderLabel(sourceControl.integrationId, metadata) : undefined;\n if (otherProvider !== undefined) {\n return {\n status: 'unlinked',\n hint: `This card comes from ${otherProvider}, and no ${otherProvider} repository is linked to this Factory.`,\n };\n }\n\n if (repositorySignal) {\n const match = findRepositoryBySlug(linked, repositorySignal);\n return match\n ? resolvedRepository(match)\n : { status: 'unlinked', hint: `Repository ${repositorySignal} is not linked to this Factory.` };\n }\n\n if (externalRepositorySignal !== undefined) {\n const name = repositoryNameFromUrl(item.workItem.url);\n return {\n status: 'unlinked',\n hint: name\n ? `Repository ${name} is not linked to this Factory.`\n : `Source-control repository ${externalRepositorySignal} is not linked to this Factory.`,\n };\n }\n\n if (mappedRepository) {\n const match = findRepositoryBySlug(linked, mappedRepository);\n return match\n ? resolvedRepository(match)\n : { status: 'unlinked', hint: `Mapped repository ${mappedRepository} is not linked to this Factory.` };\n }\n\n const candidates = [...new Set(linked.map(repository => repository.slug))].sort();\n if (candidates.length === 0) {\n return { status: 'unlinked', hint: 'This Factory has no linked source-control repositories.' };\n }\n // Every link shares the one slug here, so prefer the environment link among them.\n const onlyRepository = candidates.length === 1 ? (pickLink(linked) ?? linked[0]) : undefined;\n if (onlyRepository) return resolvedRepository(onlyRepository);\n return { status: 'ambiguous', candidates };\n}\n\nexport type RunRepositoryResolution =\n | {\n status: 'resolved';\n projectRepositoryId: string;\n slug: string;\n /**\n * Set when the card names no repository: the sandbox repositories its\n * agent chooses among. The run is filed under `slug` until it does.\n */\n unnamed?: { repositories: string[] };\n }\n | { status: 'unlinked'; hint: string };\n\n/**\n * Where a run on `item` is filed. A card that names its repository resolves\n * exactly as {@link resolveWorkItemRepository} does. A card that names none\n * among several repositories is not refused: the sandbox holds every\n * environment repository, so the run stays in `boundProjectRepositoryId` (the\n * session already working on the card) or else in the environment's first\n * repository, and its agent determines which repository the card belongs to.\n */\nexport async function resolveRunRepository(\n args: Parameters<typeof resolveWorkItemRepository>[0] & { boundProjectRepositoryId?: string },\n): Promise<RunRepositoryResolution> {\n const resolution = await resolveWorkItemRepository(args);\n if (resolution.status !== 'ambiguous') return resolution;\n const { sourceControl, orgId, factoryProjectId, boundProjectRepositoryId } = args;\n const environment = await resolveEnvironmentRepositories({ sourceControl, orgId, factoryProjectId });\n const unnamed = { repositories: environment.map(entry => entry.repository.slug) };\n if (boundProjectRepositoryId !== undefined) {\n const link = await sourceControl.projectRepositories.get({ orgId, id: boundProjectRepositoryId });\n const linked = link && (await sourceControl.repositories.get({ orgId, id: link.repositoryId }));\n const currentLinks = link\n ? await sourceControl.projectRepositories.list({ orgId, connectionId: link.connectionId })\n : [];\n if (\n !linked ||\n !resolution.candidates.includes(linked.slug) ||\n !currentLinks.some(candidate => candidate.id === boundProjectRepositoryId)\n ) {\n return { status: 'unlinked', hint: 'The existing session repository is not linked to this Factory.' };\n }\n return { status: 'resolved', projectRepositoryId: boundProjectRepositoryId, slug: linked.slug, unnamed };\n }\n const primary = environment[0];\n if (!primary) {\n return { status: 'unlinked', hint: 'None of the repositories linked to this Factory is in its environment.' };\n }\n return { status: 'resolved', projectRepositoryId: primary.link.id, slug: primary.repository.slug, unnamed };\n}\n\nexport async function resolveRunRepositoryFromIntake(\n intake: Pick<IntakeStorage, 'getConfig'> | undefined,\n args: Omit<Parameters<typeof resolveRunRepository>[0], 'linearRepositoryMap'>,\n): Promise<RunRepositoryResolution> {\n const intakeConfig = await intake?.getConfig({ orgId: args.orgId, integrationIds: ['linear'] });\n return resolveRunRepository({ ...args, linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject });\n}\n\n/** Card metadata recording the `repository` a run chose for a card that named none. */\nexport const REPOSITORY_CHOICE_KEY = 'repositoryChoice';\n\n/**\n * Whether a run recorded `slug` as the card's repository. Every role session\n * on the card was filed before it named a repository, so under another one;\n * they may keep working on the card, in `slug`. A repository set any other\n * way (intake, a person) no longer matches the recorded choice and still\n * refuses a session filed elsewhere.\n */\nexport function repositoryChosenByRun(item: Pick<Card, 'metadata'>, slug: string): boolean {\n const choice = item.metadata?.[REPOSITORY_CHOICE_KEY];\n if (typeof choice !== 'object' || choice === null) return false;\n return item.metadata?.repository === slug && (choice as Record<string, unknown>).slug === slug;\n}\n\nconst UNNAMED_REPOSITORY_INSTRUCTION = 'This card names no repository.';\n\n/** The plugin instruction telling a run's agent which repository it works in. */\nexport function runRepositoryInstruction(\n repository: { slug: string; unnamed?: { repositories: string[] } },\n ownSlug: string,\n): string {\n if (repository.unnamed) {\n return `${UNNAMED_REPOSITORY_INSTRUCTION} This session's sandbox holds ${repository.unnamed.repositories.join(', ')}. Before editing files, determine from the card which of them it belongs to and work in that repository's checkout; pass it as \\`repository\\` to the source_control_* tools (they default to ${ownSlug}). The first push or change request records it on the card. If the card belongs to none of them, stop and say so.`;\n }\n const elsewhere =\n repository.slug === ownSlug\n ? ''\n : ` This session is filed under ${ownSlug}, so pass \\`repository: ${repository.slug}\\` to the source_control_* tools.`;\n return `Target repository: ${repository.slug}. Before editing files or creating a pull request, verify this session's checkout matches the target repository.${elsewhere}`;\n}\n\nexport function isRunRepositoryInstruction(instruction: string): boolean {\n return instruction.startsWith('Target repository: ') || instruction.startsWith(UNNAMED_REPOSITORY_INSTRUCTION);\n}\n"],"mappings":";;;AAkBA,eAAe,uBAAuB,MAIN;CAC9B,MAAM,EAAE,eAAe,OAAO,qBAAqB;CACnD,MAAM,cAA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CACvE,OAAO,YAAY,WAAW,qBAAqB,KAAK,YAAY,WAAW,8BAA8B;AAC/G"}
@@ -0,0 +1,9 @@
1
+ import type { PubSub } from '@mastra/core/events';
2
+ import type { SourceControlStorage } from './storage/domains/source-control/base.js';
3
+ import type { WorkItemsStorage } from './storage/domains/work-items/base.js';
4
+ export declare const SESSION_LIST_CHANGES_TOPIC = "factory.session-list-changes";
5
+ export declare function shareSessionListChanges(pubsub: PubSub, storage: {
6
+ sourceControl: Pick<SourceControlStorage, 'projectSessions'>;
7
+ workItems: Pick<WorkItemsStorage, 'projectSubscriptions'>;
8
+ }): Promise<() => Promise<void>>;
9
+ //# sourceMappingURL=session-list-changes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-list-changes.d.ts","sourceRoot":"","sources":["../src/session-list-changes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAKjE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAE7E,eAAO,MAAM,0BAA0B,iCAAiC,CAAC;AAIzE,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,MAAM,EACd,OAAO,EAAE;IACP,aAAa,EAAE,IAAI,CAAC,oBAAoB,EAAE,iBAAiB,CAAC,CAAC;IAC7D,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,sBAAsB,CAAC,CAAC;CAC3D,GACA,OAAO,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,CAoD9B"}
@@ -0,0 +1,54 @@
1
+ import { touchFeed } from "./feed-events.js";
2
+ import { withAck } from "@mastra/core/events";
3
+ // src/session-list-changes.ts
4
+ const SESSION_LIST_CHANGES_TOPIC = "factory.session-list-changes";
5
+ async function shareSessionListChanges(pubsub, storage) {
6
+ const origin = globalThis.crypto.randomUUID();
7
+ const lists = {
8
+ sessions: storage.sourceControl.projectSessions,
9
+ follows: storage.workItems.projectSubscriptions
10
+ };
11
+ const stopAnnouncing = Object.keys(lists).map((list) => lists[list].onAnnounced((scope) => {
12
+ pubsub.publish(SESSION_LIST_CHANGES_TOPIC, {
13
+ type: "factory.session-list.changed",
14
+ runId: origin,
15
+ data: {
16
+ list,
17
+ orgId: scope.orgId,
18
+ factoryProjectId: scope.factoryProjectId
19
+ }
20
+ }).catch((error) => {
21
+ console.warn("[Factory] Failed to publish a session list change", {
22
+ factoryProjectId: scope.factoryProjectId,
23
+ error: error instanceof Error ? error.message : String(error)
24
+ });
25
+ });
26
+ touchFeed(pubsub, scope);
27
+ }));
28
+ const stopPublishing = () => {
29
+ for (const stop of stopAnnouncing) stop();
30
+ };
31
+ const onEvent = withAck(async (event) => {
32
+ if (event.runId === origin) return;
33
+ const { list, orgId, factoryProjectId } = event.data ?? {};
34
+ if ((list === "sessions" || list === "follows") && typeof orgId === "string" && typeof factoryProjectId === "string") lists[list].changed({
35
+ orgId,
36
+ factoryProjectId
37
+ });
38
+ });
39
+ try {
40
+ await pubsub.subscribe(SESSION_LIST_CHANGES_TOPIC, onEvent, { startFrom: "latest" });
41
+ } catch (error) {
42
+ console.warn(`[factory] subscribing to session list changes failed; the sidebar reads sessions and follows from the database on every request: ${error instanceof Error ? error.message : error}`);
43
+ return async () => stopPublishing();
44
+ }
45
+ for (const list of Object.values(lists)) list.trustAnnouncements();
46
+ return async () => {
47
+ for (const list of Object.values(lists)) list.distrustAnnouncements();
48
+ stopPublishing();
49
+ await pubsub.unsubscribe(SESSION_LIST_CHANGES_TOPIC, onEvent);
50
+ };
51
+ }
52
+ export { SESSION_LIST_CHANGES_TOPIC, shareSessionListChanges };
53
+
54
+ //# sourceMappingURL=session-list-changes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-list-changes.js","names":[],"sources":["../src/session-list-changes.ts"],"sourcesContent":["import type { EventCallback, PubSub } from '@mastra/core/events';\nimport { withAck } from '@mastra/core/events';\n\nimport { touchFeed } from './feed-events.js';\nimport type { AnnouncedLists, ProjectListScope } from './storage/announced-lists.js';\nimport type { SourceControlStorage } from './storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from './storage/domains/work-items/base.js';\n\nexport const SESSION_LIST_CHANGES_TOPIC = 'factory.session-list-changes';\n\ntype ListName = 'sessions' | 'follows';\n\nexport async function shareSessionListChanges(\n pubsub: PubSub,\n storage: {\n sourceControl: Pick<SourceControlStorage, 'projectSessions'>;\n workItems: Pick<WorkItemsStorage, 'projectSubscriptions'>;\n },\n): Promise<() => Promise<void>> {\n const origin = globalThis.crypto.randomUUID();\n const lists: Record<ListName, AnnouncedLists<unknown>> = {\n sessions: storage.sourceControl.projectSessions,\n follows: storage.workItems.projectSubscriptions,\n };\n const stopAnnouncing = (Object.keys(lists) as ListName[]).map(list =>\n lists[list].onAnnounced(scope => {\n pubsub\n .publish(SESSION_LIST_CHANGES_TOPIC, {\n type: 'factory.session-list.changed',\n runId: origin,\n data: { list, orgId: scope.orgId, factoryProjectId: scope.factoryProjectId },\n })\n .catch((error: unknown) => {\n console.warn('[Factory] Failed to publish a session list change', {\n factoryProjectId: scope.factoryProjectId,\n error: error instanceof Error ? error.message : String(error),\n });\n });\n touchFeed(pubsub, scope);\n }),\n );\n const stopPublishing = () => {\n for (const stop of stopAnnouncing) stop();\n };\n const onEvent: EventCallback = withAck(async event => {\n if (event.runId === origin) return;\n const { list, orgId, factoryProjectId } = (event.data ?? {}) as Partial<ProjectListScope & { list: string }>;\n if (\n (list === 'sessions' || list === 'follows') &&\n typeof orgId === 'string' &&\n typeof factoryProjectId === 'string'\n ) {\n lists[list].changed({ orgId, factoryProjectId });\n }\n });\n try {\n // Without `latest`, a retaining broker replays changes made before this replica read anything.\n await pubsub.subscribe(SESSION_LIST_CHANGES_TOPIC, onEvent, { startFrom: 'latest' });\n } catch (error) {\n console.warn(\n `[factory] subscribing to session list changes failed; the sidebar reads sessions and follows from the database on every request: ${error instanceof Error ? error.message : error}`,\n );\n return async () => stopPublishing();\n }\n for (const list of Object.values(lists)) list.trustAnnouncements();\n return async () => {\n for (const list of Object.values(lists)) list.distrustAnnouncements();\n stopPublishing();\n await pubsub.unsubscribe(SESSION_LIST_CHANGES_TOPIC, onEvent);\n };\n}\n"],"mappings":";;;AAQA,MAAa,6BAA6B;AAI1C,eAAsB,wBACpB,QACA,SAI8B;CAC9B,MAAM,SAAS,WAAW,OAAO,WAAW;CAC5C,MAAM,QAAmD;EACvD,UAAU,QAAQ,cAAc;EAChC,SAAS,QAAQ,UAAU;CAC7B;CACA,MAAM,iBAAkB,OAAO,KAAK,KAAK,CAAC,CAAgB,KAAI,SAC5D,MAAM,KAAK,CAAC,aAAY,UAAS;EAC/B,OACG,QAAQ,4BAA4B;GACnC,MAAM;GACN,OAAO;GACP,MAAM;IAAE;IAAM,OAAO,MAAM;IAAO,kBAAkB,MAAM;GAAiB;EAC7E,CAAC,CAAC,CACD,OAAO,UAAmB;GACzB,QAAQ,KAAK,qDAAqD;IAChE,kBAAkB,MAAM;IACxB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GAC9D,CAAC;EACH,CAAC;EACH,UAAU,QAAQ,KAAK;CACzB,CAAC,CACH;CACA,MAAM,uBAAuB;EAC3B,KAAK,MAAM,QAAQ,gBAAgB,KAAK;CAC1C;CACA,MAAM,UAAyB,QAAQ,OAAM,UAAS;EACpD,IAAI,MAAM,UAAU,QAAQ;EAC5B,MAAM,EAAE,MAAM,OAAO,qBAAsB,MAAM,QAAQ,CAAC;EAC1D,KACG,SAAS,cAAc,SAAS,cACjC,OAAO,UAAU,YACjB,OAAO,qBAAqB,UAE5B,MAAM,KAAK,CAAC,QAAQ;GAAE;GAAO;EAAiB,CAAC;CAEnD,CAAC;CACD,IAAI;EAEF,MAAM,OAAO,UAAU,4BAA4B,SAAS,EAAE,WAAW,SAAS,CAAC;CACrF,SAAS,OAAO;EACd,QAAQ,KACN,oIAAoI,iBAAiB,QAAQ,MAAM,UAAU,OAC/K;EACA,OAAO,YAAY,eAAe;CACpC;CACA,KAAK,MAAM,QAAQ,OAAO,OAAO,KAAK,GAAG,KAAK,mBAAmB;CACjE,OAAO,YAAY;EACjB,KAAK,MAAM,QAAQ,OAAO,OAAO,KAAK,GAAG,KAAK,sBAAsB;EACpE,eAAe;EACf,MAAM,OAAO,YAAY,4BAA4B,OAAO;CAC9D;AACF"}
@@ -0,0 +1,14 @@
1
+ export interface ProjectListScope {
2
+ orgId: string;
3
+ factoryProjectId: string;
4
+ }
5
+ export declare class AnnouncedLists<T> {
6
+ #private;
7
+ onAnnounced(listener: (scope: ProjectListScope) => void): () => void;
8
+ trustAnnouncements(): void;
9
+ distrustAnnouncements(): void;
10
+ announce(scope: ProjectListScope): void;
11
+ changed(scope: ProjectListScope): void;
12
+ read(scope: ProjectListScope, load: () => Promise<readonly T[]>): Promise<readonly T[]>;
13
+ }
14
+ //# sourceMappingURL=announced-lists.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"announced-lists.d.ts","sourceRoot":"","sources":["../../src/storage/announced-lists.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAcD,qBAAa,cAAc,CAAC,CAAC;;IAM3B,WAAW,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,gBAAgB,KAAK,IAAI,GAAG,MAAM,IAAI,CAKnE;IAED,kBAAkB,IAAI,IAAI,CAEzB;IAED,qBAAqB,IAAI,IAAI,CAI5B;IAED,QAAQ,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI,CAGtC;IAED,OAAO,CAAC,KAAK,EAAE,gBAAgB,GAAG,IAAI,CAErC;IAED,IAAI,CAAC,KAAK,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC,CAsBtF;CAmBF"}