@tenonai/yew 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +273 -0
  2. package/LICENSE +21 -0
  3. package/README.md +64 -2
  4. package/THIRD-PARTY-NOTICES.md +122 -0
  5. package/bin/yew.js +9 -0
  6. package/dist/cli/app.js +211 -0
  7. package/dist/cli/export.js +57 -0
  8. package/dist/cli/io.js +65 -0
  9. package/dist/cli/key.js +113 -0
  10. package/dist/cli/main.js +58 -0
  11. package/dist/cli/mcp.js +76 -0
  12. package/dist/cli/remote.js +116 -0
  13. package/dist/cli/run.js +72 -0
  14. package/dist/cli/schedule.js +123 -0
  15. package/dist/cli/send.js +127 -0
  16. package/dist/cli/serve.js +301 -0
  17. package/dist/cli/service.js +268 -0
  18. package/dist/cli/system.js +44 -0
  19. package/dist/remote/access.js +107 -0
  20. package/dist/remote/connector.js +278 -0
  21. package/dist/remote/identity.js +71 -0
  22. package/dist/remote/noise.js +287 -0
  23. package/dist/remote/protocol.js +51 -0
  24. package/dist/remote/push.js +37 -0
  25. package/dist/server/agent/compaction.js +242 -0
  26. package/dist/server/agent/context.js +120 -0
  27. package/dist/server/agent/held.js +48 -0
  28. package/dist/server/agent/helper.js +122 -0
  29. package/dist/server/agent/mailroom.js +510 -0
  30. package/dist/server/agent/prompt.js +268 -0
  31. package/dist/server/agent/runner.js +1159 -0
  32. package/dist/server/artifacts.js +216 -0
  33. package/dist/server/budget.js +88 -0
  34. package/dist/server/data-export.js +105 -0
  35. package/dist/server/data-usage.js +144 -0
  36. package/dist/server/db/database.js +49 -0
  37. package/dist/server/db/migrations.js +343 -0
  38. package/dist/server/errors.js +16 -0
  39. package/dist/server/events.js +17 -0
  40. package/dist/server/export.js +378 -0
  41. package/dist/server/folder-picker.js +32 -0
  42. package/dist/server/from-jig.js +98 -0
  43. package/dist/server/http/agents.js +78 -0
  44. package/dist/server/http/api.js +465 -0
  45. package/dist/server/http/app.js +111 -0
  46. package/dist/server/http/artifacts.js +53 -0
  47. package/dist/server/http/data.js +54 -0
  48. package/dist/server/http/devices.js +47 -0
  49. package/dist/server/http/events.js +134 -0
  50. package/dist/server/http/idempotency.js +53 -0
  51. package/dist/server/http/input.js +106 -0
  52. package/dist/server/http/mail.js +52 -0
  53. package/dist/server/http/mcp.js +134 -0
  54. package/dist/server/http/notes.js +91 -0
  55. package/dist/server/http/problem.js +55 -0
  56. package/dist/server/http/providers.js +131 -0
  57. package/dist/server/http/schedules.js +58 -0
  58. package/dist/server/http/search.js +42 -0
  59. package/dist/server/http/security.js +168 -0
  60. package/dist/server/http/skills.js +53 -0
  61. package/dist/server/http/system.js +26 -0
  62. package/dist/server/ids.js +30 -0
  63. package/dist/server/keys.js +70 -0
  64. package/dist/server/mail/envelope.js +152 -0
  65. package/dist/server/mail/post.js +603 -0
  66. package/dist/server/mail/store.js +279 -0
  67. package/dist/server/manage.js +601 -0
  68. package/dist/server/mcp-builtin.js +180 -0
  69. package/dist/server/mcp-config.js +305 -0
  70. package/dist/server/mcp-oauth.js +448 -0
  71. package/dist/server/mcp.js +668 -0
  72. package/dist/server/model/gateway.js +410 -0
  73. package/dist/server/paths.js +43 -0
  74. package/dist/server/permissions/engine.js +249 -0
  75. package/dist/server/permissions/paths.js +93 -0
  76. package/dist/server/permissions/shell.js +635 -0
  77. package/dist/server/push.js +345 -0
  78. package/dist/server/reveal.js +36 -0
  79. package/dist/server/runtime.js +17 -0
  80. package/dist/server/schedules.js +356 -0
  81. package/dist/server/settings.js +77 -0
  82. package/dist/server/skills.js +263 -0
  83. package/dist/server/store.js +1077 -0
  84. package/dist/server/tools/files.js +318 -0
  85. package/dist/server/tools/html.js +221 -0
  86. package/dist/server/tools/jobs.js +38 -0
  87. package/dist/server/tools/mail.js +680 -0
  88. package/dist/server/tools/match.js +81 -0
  89. package/dist/server/tools/misc.js +253 -0
  90. package/dist/server/tools/process.js +128 -0
  91. package/dist/server/tools/read-state.js +40 -0
  92. package/dist/server/tools/registry.js +43 -0
  93. package/dist/server/tools/search.js +175 -0
  94. package/dist/server/tools/shell.js +124 -0
  95. package/dist/server/tools/types.js +43 -0
  96. package/dist/server/tools/web-search.js +198 -0
  97. package/dist/server/tools/web.js +240 -0
  98. package/dist/shared/cron.js +105 -0
  99. package/dist/shared/mcp-presets.js +170 -0
  100. package/dist/shared/messages.js +45 -0
  101. package/dist/shared/policy.js +42 -0
  102. package/dist/shared/types.js +34 -0
  103. package/dist/shared/version.js +8 -0
  104. package/mcp-builtin/package-lock.json +3398 -0
  105. package/mcp-builtin/package.json +14 -0
  106. package/mcp-builtin/presets/gitee/package-lock.json +105 -0
  107. package/mcp-builtin/presets/gitee/package.json +10 -0
  108. package/mcp-builtin/presets/notion/package-lock.json +2243 -0
  109. package/mcp-builtin/presets/notion/package.json +10 -0
  110. package/mcp-builtin/presets/sentry/package-lock.json +28 -0
  111. package/mcp-builtin/presets/sentry/package.json +10 -0
  112. package/package.json +75 -5
  113. package/web/dist/THIRD-PARTY-NOTICES.txt +1944 -0
  114. package/web/dist/assets/index-BtK_SzpF.css +1 -0
  115. package/web/dist/assets/index-C0rnUFI-.js +68 -0
  116. package/web/dist/icons/app-icon.png +0 -0
  117. package/web/dist/icons/apple-touch-icon.png +0 -0
  118. package/web/dist/icons/favicon-16.png +0 -0
  119. package/web/dist/icons/favicon-32.png +0 -0
  120. package/web/dist/icons/favicon-64.png +0 -0
  121. package/web/dist/icons/tenon-mark.svg +1 -0
  122. package/web/dist/icons/yew-mark.svg +1 -0
  123. package/web/dist/index.html +18 -0
  124. package/web/dist/mascot/gift.webp +0 -0
  125. package/web/dist/mascot/greeting.webp +0 -0
  126. package/web/dist/mascot/happy.webp +0 -0
  127. package/web/dist/mascot/lost.webp +0 -0
  128. package/web/dist/mascot/shush.webp +0 -0
  129. package/web/dist/mascot/sleepy.webp +0 -0
  130. package/web/dist/mascot/sorry.webp +0 -0
  131. package/web/dist/mascot/thinking.webp +0 -0
  132. package/web/dist/mascot/waking.webp +0 -0
  133. package/web/dist/mascot/writing.webp +0 -0
@@ -0,0 +1,510 @@
1
+ /**
2
+ * A session's letters over one turn (blueprint section 7): what it sent and read, the call that waits
3
+ * for another session's answer, the scheduled run a turn may be, and what Yew sends on the session's
4
+ * behalf when the turn ends. The loop in runner.ts asks this module; it does not keep letter state.
5
+ */
6
+ import { isAbsolute, join } from "node:path";
7
+ import { plainLine } from "../../shared/messages.js";
8
+ import { permissionModeOf, } from "../../shared/types.js";
9
+ import { conflict, invalid, YewError } from "../errors.js";
10
+ import { decisionRef, letterRef, letterText } from "../mail/envelope.js";
11
+ import { BODY_MAX, reasonText, SUMMARY_MAX } from "../mail/post.js";
12
+ import { resolveWorkingFolder } from "../paths.js";
13
+ import { inheritableRules } from "../permissions/engine.js";
14
+ import { isInside } from "../permissions/paths.js";
15
+ import { validateSessionName } from "../store.js";
16
+ import { PERMISSION_MODE } from "./prompt.js";
17
+ const clip = (text, max) => [...text].length > max ? `${[...text].slice(0, max - 1).join("")}…` : text;
18
+ /** Session names are unique: "修复登录", then "修复登录 2"… */
19
+ export function freeName(store, base) {
20
+ if (!store.findSessionByName(base))
21
+ return base;
22
+ for (let n = 2;; n++) {
23
+ const name = `${base.slice(0, 55)} ${n}`;
24
+ if (!store.findSessionByName(name))
25
+ return name;
26
+ }
27
+ }
28
+ export class Mailroom {
29
+ #store;
30
+ #gateway;
31
+ #post;
32
+ #schedules;
33
+ #log;
34
+ #waitMs;
35
+ #isRunning;
36
+ #wake;
37
+ #quiet;
38
+ /** Sessions blocked in send_letter or open_session: the session, letter and tool call each waits on. */
39
+ #waits = new Map();
40
+ /**
41
+ * Each working session's current turn: the letters it sent, and for each letter it read, how many it
42
+ * had sent by then, so Yew can tell what it asked after reading a request.
43
+ */
44
+ #turns = new Map();
45
+ /** Letters handed to a waiting tool call, by the call's id, until the call's result is stored. */
46
+ #handed = new Map();
47
+ constructor(options) {
48
+ this.#store = options.store;
49
+ this.#gateway = options.gateway;
50
+ this.#post = options.post;
51
+ this.#schedules = options.schedules;
52
+ this.#log = options.log;
53
+ this.#waitMs = options.waitMs;
54
+ this.#isRunning = options.isRunning;
55
+ this.#wake = options.wake;
56
+ this.#quiet = options.quiet;
57
+ }
58
+ /** A turn begins. */
59
+ begin(sessionId, byPerson) {
60
+ this.#turns.set(sessionId, { sent: [], read: new Map(), byPerson, started: false, run: null });
61
+ }
62
+ /** The scheduled run this turn is, if it is one. */
63
+ run(sessionId) {
64
+ return this.#turns.get(sessionId)?.run ?? null;
65
+ }
66
+ /** Whether this is the turn's first delivery; from now on it is not. */
67
+ firstDelivery(sessionId) {
68
+ const turn = this.#turns.get(sessionId);
69
+ if (!turn)
70
+ return false;
71
+ const first = !turn.started;
72
+ turn.started = true;
73
+ return first;
74
+ }
75
+ /** The person wrote to the session: somebody is watching a scheduled run now. */
76
+ watched(sessionId) {
77
+ const run = this.#turns.get(sessionId)?.run;
78
+ if (run)
79
+ run.unattended = false;
80
+ }
81
+ /** The letter a waiting call was handed, once: the call's result is being stored. */
82
+ takeHanded(callId) {
83
+ const letterId = this.#handed.get(callId) ?? null;
84
+ this.#handed.delete(callId);
85
+ return letterId;
86
+ }
87
+ /** A session was archived and these letters to it dropped: calls waiting on them stop waiting. */
88
+ archived(sessionId, dropped) {
89
+ for (const waiting of [...this.#waits.values()]) {
90
+ if (waiting.target === sessionId && dropped.has(waiting.letterId)) {
91
+ waiting.resolve({ kind: "archived" });
92
+ }
93
+ }
94
+ }
95
+ /** Notes a letter the session sent in this turn, for what Yew sends on its behalf at the end. */
96
+ sent(sessionId, letter) {
97
+ this.#turns.get(sessionId)?.sent.push(letter);
98
+ return letter;
99
+ }
100
+ /** Notes that the session read a letter in this turn. */
101
+ #read(sessionId, letterId) {
102
+ const turn = this.#turns.get(sessionId);
103
+ turn?.read.set(letterId, turn.sent.length);
104
+ }
105
+ /**
106
+ * A letter is queued: a reply to the letter a session waits on goes to that waiting call; anything
107
+ * else wakes the recipient (or reaches it between tool calls).
108
+ */
109
+ queued(letter) {
110
+ const waiting = this.#waits.get(letter.toSession);
111
+ if (waiting && letter.fromSession === waiting.target && letter.replyTo === waiting.letterId) {
112
+ this.#post.mail.setLetterStatus(letter.id, "delivered", {
113
+ entryId: null,
114
+ deliveredAt: Date.now(),
115
+ });
116
+ this.#handed.set(waiting.callId, letter.id);
117
+ this.#read(letter.toSession, letter.id);
118
+ waiting.resolve({ kind: "letter", letter: this.#post.mail.getLetter(letter.id) });
119
+ return;
120
+ }
121
+ this.#wake(letter.toSession);
122
+ }
123
+ /**
124
+ * Moves queued letters into the transcript; the model reads them, the interface shows letters. A
125
+ * scheduled task's letter starts a turn of its own: only a turn that Yew started for waiting letters
126
+ * takes it, as its first delivery, and one per turn. Its own permission mode and the rule that nobody
127
+ * is watching then hold for that turn alone.
128
+ */
129
+ deliver(sessionId, first) {
130
+ const turn = this.#turns.get(sessionId);
131
+ let letters = this.#post.mail.queuedFor(sessionId);
132
+ let adopted = null;
133
+ if (first && turn && !turn.byPerson) {
134
+ adopted = letters.find((letter) => letter.scheduleId !== null) ?? null;
135
+ }
136
+ letters = letters.filter((letter) => letter.scheduleId === null || letter === adopted);
137
+ if (letters.length === 0)
138
+ return 0;
139
+ const session = this.#store.getSession(sessionId);
140
+ if (adopted && turn) {
141
+ const schedule = this.#schedules.find(adopted.scheduleId);
142
+ turn.run = {
143
+ letterId: adopted.id,
144
+ scheduleId: adopted.scheduleId,
145
+ name: schedule?.name ?? adopted.fromName,
146
+ mode: schedule?.permissionMode ?? null,
147
+ unattended: true,
148
+ refused: [],
149
+ };
150
+ }
151
+ this.#store.tx(() => {
152
+ for (const letter of letters) {
153
+ let decision = null;
154
+ if (letter.decision !== null) {
155
+ try {
156
+ decision = decisionRef(this.#post.mail.cardByNumber(letter.decision));
157
+ }
158
+ catch {
159
+ decision = null;
160
+ }
161
+ }
162
+ const schedule = this.#scheduleRef(letter);
163
+ const note = letter === adopted && turn?.run ? this.#runNote(session, turn.run) : null;
164
+ const entry = this.#store.appendEntry(sessionId, {
165
+ role: "user",
166
+ message: {
167
+ role: "user",
168
+ content: letterText(letter, decision, schedule, note),
169
+ timestamp: Date.now(),
170
+ },
171
+ letter: letterRef(letter, decision, schedule),
172
+ });
173
+ this.#post.mail.setLetterStatus(letter.id, "delivered", {
174
+ entryId: entry.id,
175
+ deliveredAt: Date.now(),
176
+ });
177
+ this.#read(sessionId, letter.id);
178
+ }
179
+ });
180
+ this.#post.enterChain(sessionId, letters);
181
+ return letters.length;
182
+ }
183
+ /** The scheduled task a letter belongs to, if it still exists. */
184
+ #scheduleRef(letter) {
185
+ if (!letter.scheduleId)
186
+ return null;
187
+ const schedule = this.#schedules.find(letter.scheduleId);
188
+ return schedule ? { id: schedule.id, name: schedule.name } : null;
189
+ }
190
+ /** What Yew tells a session about the scheduled run it is starting. */
191
+ #runNote(session, run) {
192
+ const lines = [
193
+ "This is a scheduled run and nobody is watching: Yew refuses calls that need the person's approval, and questions for them.",
194
+ ];
195
+ if (run.mode && run.mode !== permissionModeOf(session.options)) {
196
+ lines.push(`For this run: ${PERMISSION_MODE[run.mode]}`);
197
+ }
198
+ const main = this.#post.mainSessionId();
199
+ const mainName = main && main !== session.id ? this.#post.sessionName(main) : null;
200
+ lines.push(mainName
201
+ ? `When you finish, Yew sends your last reply to the main conversation (${mainName}) as the report.`
202
+ : "Your last reply is the report.");
203
+ return lines.join(" ");
204
+ }
205
+ /** The session as the permission check sees it: with the scheduled run's own mode, if it has one. */
206
+ withRunMode(session) {
207
+ const mode = this.#turns.get(session.id)?.run?.mode;
208
+ if (!mode)
209
+ return session;
210
+ return { ...session, options: { ...session.options, permissionMode: mode } };
211
+ }
212
+ /**
213
+ * The turn is over (blueprint 6.3, item 11). Sessions waiting for this one get its last reply. Every
214
+ * session whose request it read and has not answered hears how the turn ended: when the turn finished
215
+ * normally and nothing it asked others is still open, its last reply goes back as the report and the
216
+ * request is done; after an error, a stop, or while it waits for answers of its own, a notice says so
217
+ * and the request stays open, so the real result still follows. A task session's opener hears about
218
+ * every turn (M2 plan, section 6). What is owed is read from the database, so a restart in the middle
219
+ * loses nothing. Yew's letters never ask for more letters, so this cannot loop.
220
+ */
221
+ endTurn(sessionId, status, detail, stopped, said) {
222
+ this.#post.resetChain(sessionId);
223
+ const turn = this.#turns.get(sessionId) ?? {
224
+ sent: [],
225
+ read: new Map(),
226
+ byPerson: false,
227
+ started: true,
228
+ run: null,
229
+ };
230
+ this.#turns.delete(sessionId);
231
+ const mail = this.#post.mail;
232
+ const session = this.#store.getSession(sessionId);
233
+ const failed = stopped || status === "error";
234
+ const open = (letter) => ["queued", "held", "delivered"].includes(mail.getLetter(letter.id).status);
235
+ const sawEnd = new Set();
236
+ for (const [waiter, waiting] of [...this.#waits]) {
237
+ if (waiting.target !== sessionId)
238
+ continue;
239
+ if (mail.getLetter(waiting.letterId).status === "queued") {
240
+ // A letter not read yet starts the next turn at once: wait for that turn. Not when the
241
+ // person stopped this session or archived it.
242
+ if (session.archivedAt !== null) {
243
+ waiting.resolve({ kind: "archived" });
244
+ continue;
245
+ }
246
+ if (!stopped)
247
+ continue;
248
+ }
249
+ sawEnd.add(waiter);
250
+ waiting.resolve({ kind: "ended", status, text: said, detail, stopped });
251
+ }
252
+ const owed = new Map();
253
+ for (const request of mail.openRequests(sessionId)) {
254
+ if (!request.fromSession)
255
+ continue;
256
+ owed.set(request.fromSession, [...(owed.get(request.fromSession) ?? []), request]);
257
+ }
258
+ if (session.parentId && !owed.has(session.parentId))
259
+ owed.set(session.parentId, []);
260
+ for (const [requester, requests] of owed) {
261
+ const close = () => {
262
+ for (const request of requests)
263
+ mail.closeRequest(request.id);
264
+ };
265
+ let target = null;
266
+ try {
267
+ target = this.#store.getSession(requester);
268
+ }
269
+ catch {
270
+ target = null;
271
+ }
272
+ if (!target || target.archivedAt !== null) {
273
+ close();
274
+ continue;
275
+ }
276
+ // What it sent after reading these requests (all of this turn for requests read earlier).
277
+ const since = requests.length === 0
278
+ ? 0
279
+ : Math.min(...requests.map((request) => turn.read.get(request.id) ?? 0));
280
+ const after = turn.sent.slice(since);
281
+ // A question back or work handed on that is still open: its reply is not the answer yet.
282
+ const asking = after.some((letter) => letter.kind === "request" && open(letter));
283
+ const finished = !failed && !asking;
284
+ // It saw the end through its wait; a normal end answered it.
285
+ if (sawEnd.has(requester)) {
286
+ if (finished)
287
+ close();
288
+ continue;
289
+ }
290
+ const wrote = after.filter((letter) => letter.toSession === requester &&
291
+ letter.status !== "refused" &&
292
+ letter.status !== "dropped");
293
+ const replyTo = requests.at(-1)?.id ?? null;
294
+ if (finished) {
295
+ // A task session that already reported to its opener in this turn has said it.
296
+ if (requests.length === 0 && wrote.some((letter) => letter.kind === "report"))
297
+ continue;
298
+ this.#autoLetter(session, requester, {
299
+ kind: "report",
300
+ summary: plainLine(said) || `${session.name} finished without a written reply.`,
301
+ body: said,
302
+ replyTo,
303
+ });
304
+ close();
305
+ continue;
306
+ }
307
+ // Waiting for answers and already in touch with the requester: nothing to add.
308
+ if (!failed && wrote.length > 0)
309
+ continue;
310
+ const follows = `When ${session.name} goes on, its reply comes to you.`;
311
+ this.#autoLetter(session, requester, {
312
+ kind: "notice",
313
+ summary: stopped
314
+ ? `The person stopped ${session.name} before it finished.`
315
+ : status === "error"
316
+ ? `${session.name} stopped with an error.`
317
+ : plainLine(said) || `${session.name} is waiting for answers from other sessions.`,
318
+ body: [status === "error" && !stopped ? (detail ?? "") : said, follows]
319
+ .filter(Boolean)
320
+ .join("\n\n"),
321
+ replyTo,
322
+ });
323
+ }
324
+ // Runs of scheduled tasks this turn read end with it; read from the database, so a run that a
325
+ // restart interrupted ends with the turn that continues it.
326
+ let reported = false;
327
+ for (const letter of mail.scheduledRead(sessionId)) {
328
+ const run = turn.run?.letterId === letter.id ? turn.run : null;
329
+ if (this.#finishRun(session, letter, run, { status, detail, said, stopped }))
330
+ reported = true;
331
+ }
332
+ mail.finishRead(sessionId);
333
+ if (!failed && owed.size === 0 && !reported)
334
+ this.#quiet(session, said);
335
+ }
336
+ /**
337
+ * A scheduled run ended. Its result goes on the task, and to the main conversation as a report, which
338
+ * sums it up for the person (M3 plan, decision 3); a run the person stopped needs no report. Returns
339
+ * whether a report went out.
340
+ */
341
+ #finishRun(session, letter, run, end) {
342
+ const outcome = end.stopped ? "stopped" : end.status === "error" ? "error" : "done";
343
+ const first = plainLine(end.said);
344
+ this.#schedules.finished(letter, outcome, outcome === "error" ? end.detail : outcome === "done" ? first || null : null);
345
+ const main = this.#post.mainSessionId();
346
+ if (outcome === "stopped" || !main || main === session.id)
347
+ return false;
348
+ const name = this.#scheduleRef(letter)?.name ?? letter.fromName;
349
+ const refused = run?.refused ?? [];
350
+ const body = [
351
+ outcome === "error" ? (end.detail ?? "") : "",
352
+ end.said,
353
+ refused.length > 0
354
+ ? `Refused because nobody was watching:\n${refused.map((line) => `- ${line}`).join("\n")}`
355
+ : "",
356
+ ]
357
+ .filter(Boolean)
358
+ .join("\n\n");
359
+ this.#autoLetter(session, main, {
360
+ kind: outcome === "done" ? "report" : "notice",
361
+ summary: outcome === "error"
362
+ ? `The scheduled task "${name}" stopped with an error in ${session.name}.`
363
+ : first ||
364
+ `${session.name} finished the scheduled task "${name}" without a written reply.`,
365
+ body,
366
+ replyTo: null,
367
+ schedule: letter.scheduleId,
368
+ });
369
+ return true;
370
+ }
371
+ /** A letter Yew sends on a session's behalf at the end of its turn. */
372
+ #autoLetter(session, to, letter) {
373
+ try {
374
+ this.#post.send({ kind: "session", session }, {
375
+ to,
376
+ kind: letter.kind,
377
+ summary: clip(letter.summary, SUMMARY_MAX),
378
+ body: clip(letter.body, BODY_MAX),
379
+ replyTo: letter.replyTo,
380
+ auto: true,
381
+ schedule: letter.schedule ?? null,
382
+ });
383
+ }
384
+ catch (error) {
385
+ if (!(error instanceof YewError))
386
+ throw error;
387
+ this.#log(`session ${session.id}: no ${letter.kind} to ${to}: ${error.message}`);
388
+ }
389
+ }
390
+ /**
391
+ * Waits until the recipient of `letter` replies to it or ends its turn, at most `waitMs`. Refuses to
392
+ * wait when the recipient already waits for this session, directly or through others: neither could
393
+ * go on.
394
+ */
395
+ awaitReply(sessionId, letter, signal, callId) {
396
+ const target = letter.toSession;
397
+ for (let at = target, hops = 0; at && hops < 100; hops++) {
398
+ if (at === sessionId)
399
+ return Promise.resolve({ kind: "cycle" });
400
+ at = this.#waits.get(at)?.target;
401
+ }
402
+ const current = this.#post.mail.getLetter(letter.id);
403
+ if (current.status === "queued" && !this.#isRunning(target)) {
404
+ return Promise.resolve({
405
+ kind: "not-running",
406
+ status: this.#store.getSession(target).status,
407
+ });
408
+ }
409
+ return new Promise((resolve) => {
410
+ const finish = (result) => {
411
+ clearTimeout(timer);
412
+ signal.removeEventListener("abort", onAbort);
413
+ if (this.#waits.get(sessionId)?.resolve === finish)
414
+ this.#waits.delete(sessionId);
415
+ resolve(result);
416
+ };
417
+ const onAbort = () => finish({ kind: "stopped" });
418
+ const timer = setTimeout(() => finish({ kind: "timeout" }), this.#waitMs);
419
+ this.#waits.set(sessionId, { target, letterId: letter.id, callId, resolve: finish });
420
+ if (signal.aborted)
421
+ onAbort();
422
+ else
423
+ signal.addEventListener("abort", onAbort, { once: true });
424
+ });
425
+ }
426
+ /**
427
+ * Opens a task session for `parent` and sends it the brief as a request (blueprint 6.2, item 8). Its
428
+ * permissions are never above the parent's: same mode and rules, the parent's folder or one inside it.
429
+ */
430
+ openChild(parent, input,
431
+ /** The tool call opening it; with `fork`, the conversation is copied up to the step that made it. */
432
+ callRowId) {
433
+ const brief = input.brief.trim();
434
+ if (!brief)
435
+ throw invalid("The brief is empty.", "brief");
436
+ if ([...brief].length > BODY_MAX) {
437
+ throw invalid(`The brief can be at most ${BODY_MAX} characters.`, "brief");
438
+ }
439
+ // The brief must be able to go out before there is a session to send it to.
440
+ const blocked = this.#post.blockedNew(parent);
441
+ if (blocked) {
442
+ throw conflict(`Not opened: ${reasonText(blocked)}.`, undefined, "letter-refused");
443
+ }
444
+ let cwd = parent.cwd;
445
+ if (input.cwd === null)
446
+ cwd = null;
447
+ else if (input.cwd !== undefined) {
448
+ if (!parent.cwd) {
449
+ throw invalid("You have no working folder, so the new session cannot have one.", "folder");
450
+ }
451
+ const folder = resolveWorkingFolder(isAbsolute(input.cwd) ? input.cwd : join(parent.cwd, input.cwd));
452
+ if (!isInside(folder, parent.cwd)) {
453
+ throw invalid("The folder must be your working folder or inside it.", "folder");
454
+ }
455
+ cwd = folder;
456
+ }
457
+ let provider = parent.provider;
458
+ let model = parent.model;
459
+ if (input.provider && input.model) {
460
+ if (!this.#gateway.model(input.provider, input.model)) {
461
+ throw invalid(`${input.provider} has no model ${input.model}.`, "model");
462
+ }
463
+ provider = input.provider;
464
+ model = input.model;
465
+ }
466
+ const session = this.#store.tx(() => {
467
+ const child = this.#store.createSession({
468
+ name: freeName(this.#store, validateSessionName(input.name)),
469
+ kind: "task",
470
+ groupId: parent.groupId,
471
+ cwd,
472
+ provider,
473
+ model,
474
+ thinking: parent.thinking,
475
+ rules: inheritableRules(parent.rules),
476
+ options: { permissionMode: permissionModeOf(parent.options) },
477
+ parentId: parent.id,
478
+ });
479
+ if (input.fork)
480
+ this.#fork(parent, child, callRowId);
481
+ return child;
482
+ });
483
+ const letter = this.sent(parent.id, this.#post.send({ kind: "session", session: parent }, {
484
+ to: session.id,
485
+ kind: "request",
486
+ summary: clip(plainLine(brief), SUMMARY_MAX),
487
+ body: brief,
488
+ }));
489
+ return { session: this.#store.getSession(session.id), letter };
490
+ }
491
+ /**
492
+ * Gives a new task session the opener's conversation so far: everything before the step that
493
+ * opened it, so no half-made step with unanswered calls goes along. A note after it tells the new
494
+ * session who it is now; the brief follows as its request.
495
+ */
496
+ #fork(parent, child, callRowId) {
497
+ const call = callRowId ? this.#store.getToolCall(callRowId) : null;
498
+ const through = call ? this.#store.getEntry(call.messageId).seq - 1 : null;
499
+ if (this.#store.copyHistory(parent.id, child.id, through) === 0)
500
+ return;
501
+ this.#store.appendEntry(child.id, {
502
+ role: "system",
503
+ message: {
504
+ role: "system",
505
+ content: `You were forked from the session "${parent.name}": the conversation above happened there, up to the moment it opened you. You are "${child.name}" now, a task session of your own. Your task is the request below; your replies go back to "${parent.name}".`,
506
+ timestamp: Date.now(),
507
+ },
508
+ });
509
+ }
510
+ }