@tenonai/yew 0.0.0-stage → 1.4.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 +296 -0
  2. package/LICENSE +21 -0
  3. package/README.md +55 -2
  4. package/THIRD-PARTY-NOTICES.md +122 -0
  5. package/bin/yew.js +9 -0
  6. package/dist/cli/app.js +198 -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 +44 -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 +126 -0
  16. package/dist/cli/serve.js +301 -0
  17. package/dist/cli/service.js +241 -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 +119 -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 +143 -0
  36. package/dist/server/db/database.js +49 -0
  37. package/dist/server/db/migrations.js +347 -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 +468 -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 +51 -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 +179 -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 +34 -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 +80 -0
  82. package/dist/server/skills.js +262 -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-B9oWPSod.css +1 -0
  115. package/web/dist/assets/index-C5qBMzFX.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,1159 @@
1
+ import { rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { messageText, plainLine, } from "../../shared/messages.js";
4
+ import { crossedWarning, dollars, grantMore, localDay, reached, } from "../budget.js";
5
+ import { conflict, invalid, YewError } from "../errors.js";
6
+ import { PostOffice } from "../mail/post.js";
7
+ import { Manager } from "../manage.js";
8
+ import { ScheduleBook } from "../schedules.js";
9
+ import { skillFolders } from "../skills.js";
10
+ import { validateSessionName } from "../store.js";
11
+ import { Jobs } from "../tools/jobs.js";
12
+ import { settleAnswer } from "../tools/misc.js";
13
+ import { ReadState } from "../tools/read-state.js";
14
+ import { ALL_TOOLS, specs, toolsFor } from "../tools/registry.js";
15
+ import { ToolInputError, } from "../tools/types.js";
16
+ import { ContextKeeper, notice } from "./compaction.js";
17
+ import { sanitizeInterrupted, toModelMessages, usageTotals, YEW_NOTE } from "./context.js";
18
+ import { Held } from "./held.js";
19
+ import { runHelper } from "./helper.js";
20
+ import { freeName, Mailroom } from "./mailroom.js";
21
+ import { helperPrompt, NAMING_PROMPT, systemPrompt, } from "./prompt.js";
22
+ /** Words a reply uses to offer a next step instead of asking outright. */
23
+ const OFFER = /如需|需要的话|要不要|是否需要|告诉我|说一声|let me know|tell me if|shall i|should i|would you like|do you want/i;
24
+ /**
25
+ * The question a reply ends with, if it ends with one: its last paragraph (outside code) when that asks
26
+ * something or offers a next step. A session that asks the person this way goes idle, so Yew puts the
27
+ * question in the approval center for it (blueprint principle 8: Yew carries this, not a prompt rule).
28
+ */
29
+ export function askedInReply(text) {
30
+ const prose = text.replace(/```[\s\S]*?(```|$)/g, "").trim();
31
+ const last = prose
32
+ .split(/\n\s*\n/)
33
+ .at(-1)
34
+ ?.trim() ?? "";
35
+ if (!last)
36
+ return null;
37
+ const end = last.replace(/[\s*_`)\])」』"'”’]+$/u, "");
38
+ if (!/[??]$/.test(end) && !OFFER.test(last))
39
+ return null;
40
+ return last.length > 600 ? `…${last.slice(-600)}` : last;
41
+ }
42
+ const MAX_MESSAGE_CHARS = 100_000;
43
+ const MAX_STEPS = 500;
44
+ /** How many times in a row a reply cut off at the model's output limit is continued by itself. */
45
+ const MAX_CUT_REPLIES = 3;
46
+ /** After this many tool calls without a change to a task list that still has open tasks, Yew reminds the model. */
47
+ const TODO_REMINDER_AFTER = 12;
48
+ /** How long a session waits for another one's answer (blueprint 7.1: one wait, no polling). */
49
+ const WAIT_MS = 30 * 60 * 1000;
50
+ /** The result of a call that was running when Yew stopped (blueprint 7.3). */
51
+ const CUT_CALL = "Not run: your reply was cut off at the output limit before its tool calls were complete. Make the call again; write long content in parts.";
52
+ const CUT_TOO_OFTEN = "The reply was cut off at the model's output limit several times in a row.";
53
+ const RESTARTED = "Yew restarted while this call was running. It may or may not have finished; check the current state before running it again.";
54
+ const clip = (text, max) => [...text].length > max ? `${[...text].slice(0, max - 1).join("")}…` : text;
55
+ const userEntry = (text) => ({
56
+ role: "user",
57
+ message: { role: "user", content: text, timestamp: Date.now() },
58
+ });
59
+ /** Tokens the next request starts from: everything sent plus what the model just wrote. */
60
+ function contextSize(message) {
61
+ const usage = message.usage;
62
+ return usage.input + usage.cacheRead + usage.cacheWrite + usage.output;
63
+ }
64
+ function resultEntry(call, result, started) {
65
+ const message = {
66
+ role: "toolResult",
67
+ toolCallId: call.callId,
68
+ toolName: call.tool,
69
+ content: result.content,
70
+ isError: result.isError ?? false,
71
+ timestamp: Date.now(),
72
+ durationMs: Date.now() - started,
73
+ };
74
+ return { role: "toolResult", message };
75
+ }
76
+ const failure = (text) => ({
77
+ content: [{ type: "text", text }],
78
+ isError: true,
79
+ });
80
+ /**
81
+ * Runs sessions. Each working session is one async loop in this process (M1 plan, section 4): ask the
82
+ * model, check and run the tools it calls, feed back the results, and repeat until the model stops.
83
+ * Every step is stored as it happens, so a restart can tell what was in flight.
84
+ */
85
+ export class Agents {
86
+ #store;
87
+ #gateway;
88
+ #permissions;
89
+ #home;
90
+ #version;
91
+ #allTools;
92
+ #log;
93
+ #draftInterval;
94
+ #live = new Map();
95
+ #readStates = new Map();
96
+ #jobs = new Map();
97
+ /** Messages from Yew itself (such as "a background job ended") waiting to reach the model. */
98
+ #notes = new Map();
99
+ /** Tool calls since each session last changed its task list. */
100
+ #sinceTodo = new Map();
101
+ /** Letters, decision cards and the approval center. */
102
+ post;
103
+ /** Scheduled tasks, whose runs end in this runner. */
104
+ schedules;
105
+ #mail;
106
+ /** Each working session's latest written reply in this turn. */
107
+ #lastText = new Map();
108
+ #userHome;
109
+ /**
110
+ * Sessions the person stopped (letters wait until the person writes to them or continues them) and
111
+ * sessions that stopped at a daily spending limit (raising the limit that day continues them).
112
+ */
113
+ #held;
114
+ #maxSteps;
115
+ #context;
116
+ #manager;
117
+ /** A session's or team's name by id, for what the person reads on permission cards. */
118
+ #names = (id) => {
119
+ const session = this.post.sessionName(id);
120
+ if (session)
121
+ return session;
122
+ try {
123
+ return this.#store.getGroup(id).name;
124
+ }
125
+ catch {
126
+ return null;
127
+ }
128
+ };
129
+ constructor(options) {
130
+ this.#store = options.store;
131
+ this.#gateway = options.gateway;
132
+ this.#permissions = options.permissions;
133
+ this.#home = options.home;
134
+ this.#version = options.version;
135
+ const tools = options.tools ?? ALL_TOOLS;
136
+ this.#allTools = typeof tools === "function" ? tools : () => tools;
137
+ this.#log = options.log ?? ((line) => process.stderr.write(`${line}\n`));
138
+ this.#draftInterval = options.draftIntervalMs ?? 50;
139
+ this.post = options.post ?? new PostOffice(options.store, this.#log);
140
+ this.schedules = options.schedules ?? new ScheduleBook(options.store);
141
+ this.#userHome = options.userHome ?? null;
142
+ this.#held = new Held(options.store);
143
+ this.#maxSteps = options.maxSteps ?? MAX_STEPS;
144
+ this.#context = new ContextKeeper({
145
+ store: this.#store,
146
+ gateway: this.#gateway,
147
+ home: this.#home,
148
+ placement: (session) => this.#placement(session),
149
+ extras: () => this.#extras(),
150
+ });
151
+ // Memory folders and the person's skill folders are read without asking, like the working folder.
152
+ this.#permissions.readRoots = () => [
153
+ ...this.#store.getSetting("memoryDirs", []),
154
+ ...skillFolders(null, this.#home, this.#userHome),
155
+ ];
156
+ this.#mail = new Mailroom({
157
+ store: this.#store,
158
+ gateway: this.#gateway,
159
+ post: this.post,
160
+ schedules: this.schedules,
161
+ log: this.#log,
162
+ waitMs: options.waitMs ?? WAIT_MS,
163
+ isRunning: (id) => this.isRunning(id),
164
+ wake: (id) => this.#wake(id),
165
+ quiet: (session, said) => this.#askFromReply(session, said),
166
+ });
167
+ this.post.setHooks({ queued: (letter) => this.#mail.queued(letter) });
168
+ this.#manager = new Manager({
169
+ store: this.#store,
170
+ schedules: this.schedules,
171
+ mainId: () => this.post.mainSessionId(),
172
+ modelExists: (provider, model) => Boolean(this.#gateway.model(provider, model)),
173
+ onArchived: (id) => this.archived(id),
174
+ });
175
+ }
176
+ /** What tools may look up while Yew checks a call of `session`. */
177
+ #lookup(session) {
178
+ return { name: this.#names, plan: (args) => this.#manager.plan(session, args) };
179
+ }
180
+ isRunning(sessionId) {
181
+ return this.#live.has(sessionId);
182
+ }
183
+ /**
184
+ * Whether a command of this session may still be writing its output file: a turn is running, or a
185
+ * background command has not ended. The data cleanup leaves such a session's files alone.
186
+ */
187
+ hasLiveCommands(sessionId) {
188
+ if (this.isRunning(sessionId))
189
+ return true;
190
+ return (this.#jobs
191
+ .get(sessionId)
192
+ ?.list()
193
+ .some((job) => !job.finished) ?? false);
194
+ }
195
+ /** Resolves when the session is not running. */
196
+ async whenIdle(sessionId) {
197
+ await this.#live.get(sessionId)?.done;
198
+ }
199
+ /** The person sends a message: it starts a turn, or waits in the queue while one runs (blueprint 7.1). */
200
+ send(sessionId, text) {
201
+ const trimmed = text.trim();
202
+ if (!trimmed)
203
+ throw invalid("The message is empty.", "text");
204
+ if (text.length > MAX_MESSAGE_CHARS)
205
+ throw invalid("The message is too long.", "text");
206
+ const session = this.#store.getSession(sessionId);
207
+ if (session.archivedAt !== null)
208
+ throw conflict("This session is archived. Restore it first.", undefined, "session-archived");
209
+ // The person stepped in: a full quota of letters again, and a new chain of hand-offs (blueprint 7.1).
210
+ this.#dropReplyQuestions(sessionId);
211
+ this.#held.resume(sessionId);
212
+ this.#store.resetLettersSent(sessionId);
213
+ this.#store.addIntervention(sessionId);
214
+ this.post.resetChain(sessionId);
215
+ if (this.isRunning(sessionId))
216
+ return { queued: this.#store.enqueue(sessionId, text) };
217
+ this.#dropLeftovers(sessionId, "Not run: the person sent a new message instead of continuing.");
218
+ const entry = this.#store.appendEntry(sessionId, userEntry(text));
219
+ this.#start(sessionId, { byPerson: true });
220
+ return { entry };
221
+ }
222
+ /** Picks up after a stop, an error or a restart, without a new message. */
223
+ continue(sessionId) {
224
+ const session = this.#store.getSession(sessionId);
225
+ if (this.isRunning(sessionId))
226
+ throw conflict("This session is already working.", undefined, "session-busy");
227
+ if (session.archivedAt !== null)
228
+ throw conflict("This session is archived. Restore it first.", undefined, "session-archived");
229
+ const entries = this.#store.contextEntries(sessionId);
230
+ if (entries.length === 0)
231
+ throw conflict("There is nothing to continue yet.", undefined, "nothing-to-continue");
232
+ this.#dropReplyQuestions(sessionId);
233
+ this.#held.resume(sessionId);
234
+ // Continuing a session that stopped at a spending limit gives it as much room again for today.
235
+ grantMore(this.#store, session, Date.now());
236
+ this.#start(sessionId, { resume: true, byPerson: true });
237
+ }
238
+ /** The person stops a session. Letters that arrive later wait until the person writes or continues. */
239
+ stop(sessionId) {
240
+ const live = this.#live.get(sessionId);
241
+ if (!live)
242
+ return;
243
+ this.#held.pause(sessionId);
244
+ this.#held.uncap(sessionId);
245
+ live.controller.abort();
246
+ }
247
+ /** Records the person's answer to a permission request or a question, and lets the session go on. */
248
+ answer(approvalId, answer) {
249
+ const approval = this.#store.getApproval(approvalId);
250
+ if (approval.kind === "permission") {
251
+ if (!answer.decision)
252
+ throw invalid("Choose allow_once, allow_always or deny.", "decision");
253
+ const request = approval.request;
254
+ if (answer.decision === "allow_always" && (request.mustConfirm || !request.rememberRules)) {
255
+ throw invalid("This operation can only be allowed once.", "decision");
256
+ }
257
+ }
258
+ else {
259
+ // The session reads the answer as text; the structured answer stays for the card.
260
+ const settled = settleAnswer(approval.request, answer);
261
+ answer = {
262
+ answer: settled.text,
263
+ ...(settled.answers ? { answers: settled.answers } : {}),
264
+ };
265
+ if (approval.request.fromReply) {
266
+ // Nothing waits for it: the answer is the person's next message to the session.
267
+ const resolved = this.#store.resolveApproval(approvalId, answer);
268
+ this.send(approval.sessionId, settled.text);
269
+ return resolved;
270
+ }
271
+ }
272
+ const resolved = this.#store.resolveApproval(approvalId, answer);
273
+ this.#store.addIntervention(approval.sessionId);
274
+ const waiter = this.#live.get(approval.sessionId)?.waiters.get(approvalId);
275
+ waiter?.(answer);
276
+ return resolved;
277
+ }
278
+ /**
279
+ * Takes the conversation back to a point the person picked (blueprint 6.11, item 42): one of its
280
+ * replies, or just before one of the person's messages. Not while it works. A question Yew made of a
281
+ * reply goes with the reply. Returns how many entries were taken back.
282
+ */
283
+ rewind(sessionId, entryId) {
284
+ if (this.isRunning(sessionId)) {
285
+ throw conflict("Stop the session first, then take it back.", undefined, "session-busy");
286
+ }
287
+ const count = this.#store.rewindSession(sessionId, this.#store.turnPoint(sessionId, entryId));
288
+ this.#dropReplyQuestions(sessionId);
289
+ for (const approval of this.#store.pendingApprovals(sessionId)) {
290
+ this.#store.cancelApproval(approval.id);
291
+ }
292
+ if (this.#store.getSession(sessionId).status !== "idle")
293
+ this.#store.setStatus(sessionId, "idle");
294
+ return count;
295
+ }
296
+ /** Shortens the context now; the session must not be working. */
297
+ async compactNow(sessionId) {
298
+ if (this.isRunning(sessionId))
299
+ throw conflict("Wait until the session stops working.", undefined, "session-busy");
300
+ const session = this.#store.getSession(sessionId);
301
+ const model = this.#requireModel(session);
302
+ // Compacting does not change where the session stands: one that needs review or failed still does.
303
+ const keep = session.status === "needs_review" || session.status === "error";
304
+ const controller = new AbortController();
305
+ const done = this.#context.compact(session, model, controller.signal, true).then(() => { });
306
+ this.#live.set(sessionId, { controller, done, waiters: new Map() });
307
+ try {
308
+ this.#store.setStatus(sessionId, "working");
309
+ await done;
310
+ }
311
+ finally {
312
+ this.#live.delete(sessionId);
313
+ if (keep)
314
+ this.#store.setStatus(sessionId, session.status, session.statusDetail);
315
+ else
316
+ this.#store.setStatus(sessionId, "idle");
317
+ this.#wake(sessionId);
318
+ }
319
+ }
320
+ /**
321
+ * The person archived a session. Letters waiting for it are dropped, so they do not linger or arrive
322
+ * when it is restored, and sessions waiting on one of them stop waiting.
323
+ */
324
+ archived(sessionId) {
325
+ const letters = this.post.mail.dropWaiting(sessionId, "archived");
326
+ for (const letter of letters)
327
+ this.schedules.finished(letter, "skipped", "archived");
328
+ const dropped = new Set(letters.map((letter) => letter.id));
329
+ this.#mail.archived(sessionId, dropped);
330
+ }
331
+ /**
332
+ * Deletes every archived session for good, except one that is still working. Their scratch folders go
333
+ * too, and the main conversation setting if it named one of them. Returns the deleted sessions' ids.
334
+ */
335
+ deleteArchived() {
336
+ const ids = this.#store.deleteArchivedSessions((id) => this.isRunning(id));
337
+ for (const id of ids) {
338
+ rmSync(join(this.#home, "tmp", id), { recursive: true, force: true });
339
+ // Its artifacts' rows went with the session; their files go too.
340
+ rmSync(join(this.#home, "artifacts", id), { recursive: true, force: true });
341
+ this.#readStates.delete(id);
342
+ this.#jobs.get(id)?.stopAll();
343
+ this.#jobs.delete(id);
344
+ this.#held.forget(id);
345
+ }
346
+ if (ids.includes(this.#store.getSetting("mainSessionId", null) ?? "")) {
347
+ this.#store.setSetting("mainSessionId", null);
348
+ }
349
+ // Their scheduled tasks went with them.
350
+ if (ids.length > 0)
351
+ this.schedules.refresh();
352
+ return ids;
353
+ }
354
+ shutdown() {
355
+ for (const live of this.#live.values())
356
+ live.controller.abort();
357
+ for (const jobs of this.#jobs.values())
358
+ jobs.stopAll();
359
+ }
360
+ #start(sessionId, options = {}) {
361
+ const controller = new AbortController();
362
+ const live = { controller, done: Promise.resolve(), waiters: new Map() };
363
+ this.#live.set(sessionId, live);
364
+ this.#lastText.delete(sessionId);
365
+ this.#mail.begin(sessionId, options.byPerson ?? false);
366
+ live.done = this.#run(sessionId, live, options.resume ?? false)
367
+ .catch((error) => this.#log(`session ${sessionId}: ${error.stack ?? error}`))
368
+ .finally(() => {
369
+ this.#live.delete(sessionId);
370
+ // Letters that arrived after the last delivery start the next turn, unless the person stopped this one.
371
+ if (!controller.signal.aborted)
372
+ this.#wake(sessionId);
373
+ });
374
+ }
375
+ /** The calls a session can make depend on its place: card tools for the main conversation. */
376
+ #roles(session) {
377
+ return {
378
+ canPostCards: this.post.canPostCards(session),
379
+ canOrganize: this.post.canOrganize(session),
380
+ };
381
+ }
382
+ /**
383
+ * The conversation moves on: calls left over from an interrupted run will not be run later. Calls that
384
+ * were running when Yew stopped may have finished, so they say that rather than "not run".
385
+ */
386
+ #dropLeftovers(sessionId, reason) {
387
+ this.#store.tx(() => {
388
+ for (const call of this.#store.toolCallsByStatus(sessionId, ["pending", "needs_review"])) {
389
+ const text = call.status === "needs_review" ? RESTARTED : reason;
390
+ this.#finishCall(call, failure(text), "error", Date.now());
391
+ }
392
+ });
393
+ }
394
+ /** Memory folders from the settings, and where the person's own skills and instructions are. */
395
+ #extras() {
396
+ return {
397
+ memoryDirs: this.#store.getSetting("memoryDirs", []),
398
+ userHome: this.#userHome,
399
+ disabledSkills: this.#store.getSetting("disabledSkills", []),
400
+ };
401
+ }
402
+ #requireModel(session) {
403
+ const model = this.#gateway.model(session.provider, session.model);
404
+ if (!model)
405
+ throw invalid(`${session.provider} has no model ${session.model}.`, "model");
406
+ return model;
407
+ }
408
+ async #run(sessionId, live, resume) {
409
+ const signal = live.controller.signal;
410
+ this.#store.setStatus(sessionId, "working");
411
+ let endStatus = "idle";
412
+ let detail = null;
413
+ let capped = null;
414
+ try {
415
+ let retriedOverflow = false;
416
+ let cutReplies = 0;
417
+ if (resume)
418
+ await this.#resumeCalls(sessionId, live);
419
+ this.#deliver(sessionId);
420
+ for (let step = 0;; step++) {
421
+ if (signal.aborted)
422
+ break;
423
+ if (step >= this.#maxSteps) {
424
+ // Not finished: the person decides whether it goes on.
425
+ endStatus = "error";
426
+ detail = `Stopped after ${this.#maxSteps} steps in one turn.`;
427
+ this.#notice(sessionId, "error", detail, {
428
+ code: "step-limit",
429
+ steps: this.#maxSteps,
430
+ });
431
+ break;
432
+ }
433
+ const session = this.#store.getSession(sessionId);
434
+ const over = reached(this.#store, session, Date.now());
435
+ if (over) {
436
+ capped = this.#budgetNotice(sessionId, "budget-reached", over);
437
+ break;
438
+ }
439
+ const model = this.#requireModel(session);
440
+ const snapshot = this.#context.refresh(session);
441
+ if ((await this.#context.compactIfNeeded(session, model, signal)) === "failed") {
442
+ // Going on would ask for a summary again at every step and end in a context that does not fit.
443
+ if (!signal.aborted) {
444
+ endStatus = "error";
445
+ detail = "The context could not be shortened.";
446
+ }
447
+ break;
448
+ }
449
+ if (signal.aborted)
450
+ break;
451
+ const final = await this.#ask(this.#store.getSession(sessionId), model, snapshot, signal);
452
+ const message = sanitizeInterrupted(final);
453
+ const entry = message.content.length > 0
454
+ ? this.#store.appendEntry(sessionId, { role: "assistant", message })
455
+ : null;
456
+ const said = message.content
457
+ .map((block) => (block.type === "text" ? block.text : ""))
458
+ .join("\n")
459
+ .trim();
460
+ if (said)
461
+ this.#lastText.set(sessionId, said);
462
+ this.#store.addUsage(sessionId, usageTotals(final), contextSize(final));
463
+ for (const mark of crossedWarning(this.#store, session, usageTotals(final).cost, Date.now())) {
464
+ this.#budgetNotice(sessionId, "budget-warning", mark);
465
+ }
466
+ if (final.stopReason === "aborted" || signal.aborted) {
467
+ this.#notice(sessionId, "interrupted", "Stopped by the person.");
468
+ break;
469
+ }
470
+ if (final.stopReason === "error") {
471
+ if (!retriedOverflow &&
472
+ this.#gateway.isContextOverflow(final, session.provider, session.model)) {
473
+ retriedOverflow = true;
474
+ const shortened = await this.#context.compact(this.#store.getSession(sessionId), model, signal, true);
475
+ if (shortened === "done")
476
+ continue;
477
+ if (signal.aborted)
478
+ break;
479
+ }
480
+ endStatus = "error";
481
+ detail = final.errorMessage ?? "The model request failed.";
482
+ this.#notice(sessionId, "error", detail, { code: "model-error" });
483
+ break;
484
+ }
485
+ const calls = message.content.filter((block) => block.type === "toolCall");
486
+ if (calls.length === 0 || !entry) {
487
+ if (final.stopReason === "length") {
488
+ // The reply stopped at the model's output limit, not because the model was done.
489
+ if (cutReplies >= MAX_CUT_REPLIES) {
490
+ endStatus = "error";
491
+ detail = CUT_TOO_OFTEN;
492
+ this.#notice(sessionId, "error", detail, { code: "output-cut" });
493
+ break;
494
+ }
495
+ cutReplies++;
496
+ this.#note(sessionId, "Your reply was cut off at the output limit. Go on from where it stopped; write long content to a file in parts.");
497
+ }
498
+ // The model is done; anything the person sent meanwhile starts the next round.
499
+ if (this.#deliver(sessionId))
500
+ continue;
501
+ break;
502
+ }
503
+ const rows = calls.map((call) => this.#store.createToolCall({
504
+ sessionId,
505
+ messageId: entry.id,
506
+ callId: call.id,
507
+ tool: call.name,
508
+ args: call.arguments,
509
+ }));
510
+ if (final.stopReason === "length") {
511
+ // The reply stopped at the output limit in the middle of its calls. Arguments that were
512
+ // cut short can still read as complete (half a file to write, say), so none of them runs.
513
+ this.#store.tx(() => {
514
+ for (const row of rows)
515
+ this.#finishCall(row, failure(CUT_CALL), "error", Date.now());
516
+ });
517
+ if (cutReplies >= MAX_CUT_REPLIES) {
518
+ endStatus = "error";
519
+ detail = CUT_TOO_OFTEN;
520
+ this.#notice(sessionId, "error", detail, { code: "output-cut" });
521
+ break;
522
+ }
523
+ cutReplies++;
524
+ this.#deliver(sessionId);
525
+ continue;
526
+ }
527
+ cutReplies = 0;
528
+ await this.#runCalls(sessionId, rows, calls, live);
529
+ this.#remindTodos(sessionId, calls);
530
+ if (signal.aborted) {
531
+ this.#notice(sessionId, "interrupted", "Stopped by the person.");
532
+ break;
533
+ }
534
+ this.#deliver(sessionId);
535
+ }
536
+ }
537
+ catch (error) {
538
+ endStatus = "error";
539
+ detail =
540
+ error instanceof YewError
541
+ ? error.message
542
+ : `Yew hit an internal error: ${error.message}`;
543
+ if (!(error instanceof YewError))
544
+ this.#log(`session ${sessionId}: ${error.stack ?? error}`);
545
+ // The code lets the interface explain the problem in the person's language.
546
+ const data = error instanceof YewError
547
+ ? { code: error.code, ...(error.details ?? {}) }
548
+ : { code: "internal-error" };
549
+ this.#notice(sessionId, "error", detail, data);
550
+ }
551
+ finally {
552
+ this.#store.live(sessionId, { type: "draftCleared" });
553
+ if (signal.aborted)
554
+ endStatus = "idle";
555
+ this.#store.setStatus(sessionId, endStatus, detail);
556
+ this.#store.bumpUnread(sessionId);
557
+ if (capped && !signal.aborted)
558
+ this.#held.cap(sessionId, localDay(Date.now()));
559
+ else
560
+ this.#held.uncap(sessionId);
561
+ // To the sessions that wait for this one, a stop at a spending limit is a turn that failed.
562
+ const said = this.#lastText.get(sessionId) ?? "";
563
+ this.#lastText.delete(sessionId);
564
+ if (capped && !signal.aborted)
565
+ this.#mail.endTurn(sessionId, "error", capped, false, said);
566
+ else
567
+ this.#mail.endTurn(sessionId, endStatus, detail, signal.aborted, said);
568
+ if (endStatus === "idle" && !signal.aborted && !capped) {
569
+ this.#nameAfterFirstTurn(sessionId).catch((error) => this.#log(`session ${sessionId}: naming failed: ${error.message}`));
570
+ }
571
+ }
572
+ }
573
+ /**
574
+ * A session started from the home page is named after the start of its first message. After its
575
+ * first turn its own model gives it a short name, once; a name the person or the main conversation
576
+ * chose is kept (blueprint section 5).
577
+ */
578
+ async #nameAfterFirstTurn(sessionId) {
579
+ const session = this.#store.getSession(sessionId);
580
+ if (!session.options.autoName)
581
+ return;
582
+ this.#store.updateSession(sessionId, { options: { autoName: false } });
583
+ const model = this.#gateway.model(session.provider, session.model);
584
+ if (!model)
585
+ return;
586
+ const entries = this.#store.contextEntries(sessionId);
587
+ const asked = entries.find((entry) => entry.role === "user");
588
+ const replied = entries.find((entry) => entry.role === "assistant");
589
+ const textOf = (entry) => entry && (entry.role === "user" || entry.role === "assistant")
590
+ ? messageText(entry.message).trim()
591
+ : "";
592
+ const first = clip(textOf(asked), 2000);
593
+ if (!first)
594
+ return;
595
+ const reply = await this.#gateway.stream({
596
+ provider: session.provider,
597
+ model: model.id,
598
+ thinking: "off",
599
+ systemPrompt: NAMING_PROMPT,
600
+ messages: [
601
+ {
602
+ role: "user",
603
+ content: `The person's first message:\n${first}\n\nThe start of the reply:\n${clip(textOf(replied), 500)}`,
604
+ timestamp: Date.now(),
605
+ },
606
+ ],
607
+ tools: [],
608
+ signal: new AbortController().signal,
609
+ });
610
+ const now = this.#store.getSession(sessionId);
611
+ this.#store.addUsage(sessionId, usageTotals(reply), now.contextTokens);
612
+ const said = reply.content
613
+ .map((block) => (block.type === "text" ? block.text : ""))
614
+ .join("")
615
+ .trim();
616
+ const name = plainLine(said)
617
+ .replace(/^["'“”‘’「」『』《》]+|["'“”‘’「」『』《》]+$/g, "")
618
+ .replace(/[。.!!??]+$/, "")
619
+ .trim();
620
+ // Renamed meanwhile, or nothing usable came back: keep the name it has.
621
+ if (reply.stopReason !== "stop" || !name || now.name !== session.name)
622
+ return;
623
+ let chosen;
624
+ try {
625
+ chosen = freeName(this.#store, validateSessionName(clip(name, 40)));
626
+ }
627
+ catch {
628
+ return;
629
+ }
630
+ this.#store.updateSession(sessionId, { name: chosen });
631
+ // One turn in, there is little prompt cache to keep: the prompt learns the name without an update.
632
+ const saved = this.#store.getContextSnapshot(sessionId);
633
+ if (saved) {
634
+ this.#store.setContextSnapshot(sessionId, {
635
+ ...saved,
636
+ name: chosen,
637
+ ...(saved.told ? { told: { ...saved.told, name: chosen } } : {}),
638
+ });
639
+ }
640
+ }
641
+ async #ask(session, model, snapshot, signal) {
642
+ const tools = toolsFor(session, this.#allTools(), this.#roles(session));
643
+ let last = 0;
644
+ let pending = null;
645
+ let latest = null;
646
+ const flush = () => {
647
+ pending = null;
648
+ last = Date.now();
649
+ if (latest)
650
+ this.#store.live(session.id, { type: "draft", draft: structuredClone(latest) });
651
+ };
652
+ try {
653
+ return await this.#gateway.stream({
654
+ provider: session.provider,
655
+ model: model.id,
656
+ thinking: session.thinking,
657
+ systemPrompt: systemPrompt(session, snapshot, this.#groupName(session)),
658
+ messages: toModelMessages(this.#store.contextEntries(session.id)),
659
+ tools: specs(tools),
660
+ signal,
661
+ sessionId: session.id,
662
+ onRetry: (retry) => {
663
+ this.#log(`session ${session.id}: model request failed (${retry.error}); retry ${retry.attempt} of ${retry.of}`);
664
+ this.#store.live(session.id, {
665
+ type: "retrying",
666
+ attempt: retry.attempt,
667
+ of: retry.of,
668
+ seconds: Math.round(retry.delayMs / 1000),
669
+ text: clip(retry.error, 300),
670
+ });
671
+ },
672
+ }, (draft) => {
673
+ latest = draft;
674
+ if (pending)
675
+ return;
676
+ const wait = this.#draftInterval - (Date.now() - last);
677
+ if (wait <= 0)
678
+ flush();
679
+ else
680
+ pending = setTimeout(flush, wait);
681
+ });
682
+ }
683
+ finally {
684
+ if (pending)
685
+ clearTimeout(pending);
686
+ }
687
+ }
688
+ /** Checks every call of a batch first (asking where needed), then runs the allowed ones (prior-art 4.1). */
689
+ async #runCalls(sessionId, rows, calls, live) {
690
+ const signal = live.controller.signal;
691
+ const current = this.#store.getSession(sessionId);
692
+ const byName = new Map(toolsFor(current, this.#allTools(), this.#roles(current)).map((tool) => [tool.name, tool]));
693
+ const results = new Map();
694
+ const approved = [];
695
+ for (const [index, row] of rows.entries()) {
696
+ const started = Date.now();
697
+ if (signal.aborted) {
698
+ results.set(row.id, {
699
+ result: failure("Not run: stopped by the person."),
700
+ status: "error",
701
+ started,
702
+ });
703
+ continue;
704
+ }
705
+ const tool = byName.get(row.tool);
706
+ const argumentsError = calls[index]?.argumentsError;
707
+ if (!tool) {
708
+ results.set(row.id, {
709
+ result: failure(`There is no tool named ${row.tool}.`),
710
+ status: "error",
711
+ started,
712
+ });
713
+ continue;
714
+ }
715
+ if (argumentsError) {
716
+ results.set(row.id, {
717
+ result: failure(`The arguments were not valid JSON: ${argumentsError}`),
718
+ status: "error",
719
+ started,
720
+ });
721
+ continue;
722
+ }
723
+ const session = this.#store.getSession(sessionId);
724
+ let decision;
725
+ try {
726
+ // In the automatic mode the model asks for a person's approval itself, with `confirm`.
727
+ const flagged = row.args.confirm === true;
728
+ const subject = tool.subject(row.args, session, this.#lookup(session));
729
+ decision = this.#permissions.decide(subject, this.#mail.withRunMode(session), flagged);
730
+ }
731
+ catch (error) {
732
+ const message = error instanceof ToolInputError
733
+ ? error.message
734
+ : `Could not check this call: ${error.message}`;
735
+ results.set(row.id, { result: failure(message), status: "error", started });
736
+ continue;
737
+ }
738
+ if (decision.effect === "deny") {
739
+ results.set(row.id, {
740
+ result: failure(`Refused by Yew: ${decision.reason}`),
741
+ status: "denied",
742
+ started,
743
+ });
744
+ continue;
745
+ }
746
+ const run = this.#mail.run(sessionId);
747
+ if (decision.effect === "ask" && run?.unattended) {
748
+ // Nobody is there to say yes: refuse now rather than wait (blueprint 6.1, item 6).
749
+ run.refused.push(decision.request.summary);
750
+ results.set(row.id, {
751
+ result: {
752
+ ...failure(`Refused: this turn runs for the scheduled task "${run.name}" and nobody is watching, so nobody can approve it. Do what you can without it; Yew lists what was refused in the report.`),
753
+ detail: { code: "unattended" },
754
+ },
755
+ status: "denied",
756
+ started,
757
+ });
758
+ continue;
759
+ }
760
+ if (decision.effect === "ask") {
761
+ this.#store.updateToolCall(row.id, { status: "waiting" });
762
+ const approval = this.#store.createApproval({
763
+ sessionId,
764
+ toolCallId: row.id,
765
+ kind: "permission",
766
+ // What the call is for and what it would change, so the person decides on what they see.
767
+ request: {
768
+ ...decision.request,
769
+ ...tool.preview?.(row.args, session, this.#lookup(session)),
770
+ },
771
+ });
772
+ const answer = await this.#waitFor(sessionId, approval.id, live);
773
+ if (!answer || answer.decision === "deny" || answer.decision === undefined) {
774
+ const reason = answer?.reason?.trim();
775
+ const text = !answer
776
+ ? "Not run: stopped before the person decided."
777
+ : reason
778
+ ? `The person declined this call: ${reason}`
779
+ : "The person declined this call.";
780
+ results.set(row.id, { result: failure(text), status: "denied", started });
781
+ continue;
782
+ }
783
+ if (answer.decision === "allow_always" && decision.request.rememberRules) {
784
+ const current = this.#store.getSession(sessionId);
785
+ this.#store.updateSession(sessionId, {
786
+ rules: [...current.rules, ...decision.request.rememberRules],
787
+ });
788
+ }
789
+ }
790
+ approved.push({ row, tool });
791
+ }
792
+ const execute = async ({ row, tool }) => {
793
+ const started = Date.now();
794
+ if (signal.aborted) {
795
+ results.set(row.id, {
796
+ result: failure("Not run: stopped by the person."),
797
+ status: "error",
798
+ started,
799
+ });
800
+ return;
801
+ }
802
+ this.#store.updateToolCall(row.id, { status: "running", startedAt: started });
803
+ let result;
804
+ try {
805
+ result = await tool.run(row.args, this.#toolContext(sessionId, row, live));
806
+ }
807
+ catch (error) {
808
+ result = failure(error instanceof ToolInputError
809
+ ? error.message
810
+ : `The tool failed: ${error.message}`);
811
+ }
812
+ results.set(row.id, { result, status: result.isError ? "error" : "done", started });
813
+ };
814
+ if (approved.every(({ tool }) => tool.readOnly))
815
+ await Promise.all(approved.map(execute));
816
+ else
817
+ for (const call of approved)
818
+ await execute(call);
819
+ // Results go into the transcript in the order the model made the calls.
820
+ this.#store.tx(() => {
821
+ for (const row of rows) {
822
+ const outcome = results.get(row.id) ?? {
823
+ result: failure("Not run."),
824
+ status: "error",
825
+ started: Date.now(),
826
+ };
827
+ this.#finishCall(row, outcome.result, outcome.status, outcome.started);
828
+ }
829
+ });
830
+ }
831
+ #finishCall(row, result, status, started) {
832
+ const entry = this.#store.appendEntry(row.sessionId, resultEntry(row, result, started));
833
+ this.#store.updateToolCall(row.id, {
834
+ status,
835
+ detail: result.detail ?? null,
836
+ resultMessageId: entry.id,
837
+ finishedAt: Date.now(),
838
+ });
839
+ // A letter this call waited for is now in the transcript, inside the result.
840
+ const handed = this.#mail.takeHanded(row.id);
841
+ if (handed)
842
+ this.post.mail.setLetterEntry(handed, entry.id);
843
+ }
844
+ /** After a restart: calls that were running get an honest "unknown" result; calls that never ran are checked again. */
845
+ async #resumeCalls(sessionId, live) {
846
+ const unknown = this.#store.toolCallsByStatus(sessionId, ["needs_review"]);
847
+ this.#store.tx(() => {
848
+ for (const call of unknown)
849
+ this.#finishCall(call, failure(RESTARTED), "error", Date.now());
850
+ });
851
+ const pending = this.#store.toolCallsByStatus(sessionId, ["pending"]);
852
+ if (pending.length > 0)
853
+ await this.#runCalls(sessionId, pending, pending.map(() => null), live);
854
+ }
855
+ #waitFor(sessionId, approvalId, live) {
856
+ const signal = live.controller.signal;
857
+ this.#store.setStatus(sessionId, "waiting");
858
+ return new Promise((resolve) => {
859
+ const finish = (answer) => {
860
+ live.waiters.delete(approvalId);
861
+ signal.removeEventListener("abort", onAbort);
862
+ if (!signal.aborted)
863
+ this.#store.setStatus(sessionId, "working");
864
+ resolve(answer);
865
+ };
866
+ const onAbort = () => {
867
+ this.#store.cancelApproval(approvalId);
868
+ finish(null);
869
+ };
870
+ live.waiters.set(approvalId, finish);
871
+ if (signal.aborted)
872
+ onAbort();
873
+ else
874
+ signal.addEventListener("abort", onAbort, { once: true });
875
+ });
876
+ }
877
+ #toolContext(sessionId, row, live) {
878
+ const session = this.#store.getSession(sessionId);
879
+ const model = this.#gateway.model(session.provider, session.model);
880
+ let tail = "";
881
+ let timer = null;
882
+ const context = {
883
+ session,
884
+ signal: live.controller.signal,
885
+ readState: this.#readState(sessionId),
886
+ jobs: this.#jobsFor(sessionId),
887
+ tmpDir: join(this.#home, "tmp", sessionId),
888
+ acceptsImages: model?.input.includes("image") ?? false,
889
+ version: this.#version,
890
+ output: (chunk) => {
891
+ tail = (tail + chunk).slice(-4000);
892
+ if (timer)
893
+ return;
894
+ timer = setTimeout(() => {
895
+ timer = null;
896
+ this.#store.live(sessionId, { type: "toolOutput", toolCallId: row.id, output: tail });
897
+ }, 200);
898
+ },
899
+ setTodos: (todos) => this.#store.setTodos(sessionId, todos),
900
+ ask: async (request) => {
901
+ const run = this.#mail.run(sessionId);
902
+ if (run?.unattended) {
903
+ const first = request.questions?.[0]?.question ?? request.question ?? "";
904
+ run.refused.push(`Question: ${clip(plainLine(first), 200)}`);
905
+ throw new ToolInputError(`Nobody can answer now: this turn runs for the scheduled task "${run.name}" and nobody is watching. Decide what you can yourself and say in your reply what is still open.`);
906
+ }
907
+ const approval = this.#store.createApproval({
908
+ sessionId,
909
+ toolCallId: row.id,
910
+ kind: "question",
911
+ request,
912
+ });
913
+ const answer = await this.#waitFor(sessionId, approval.id, live);
914
+ if (!answer?.answer)
915
+ throw new ToolInputError("Stopped before the person answered.");
916
+ return answer.answer;
917
+ },
918
+ mail: this.#mailContext(sessionId, live, row.id),
919
+ helper: (task) => {
920
+ const parent = this.#store.getSession(sessionId);
921
+ return runHelper({
922
+ gateway: this.#gateway,
923
+ permissions: this.#permissions,
924
+ session: this.#mail.withRunMode(parent),
925
+ tools: toolsFor(parent, this.#allTools(), this.#roles(parent)),
926
+ lookup: this.#lookup(parent),
927
+ // Its own reads, so they do not count as the session's before an edit; no questions.
928
+ context: {
929
+ ...context,
930
+ readState: new ReadState(),
931
+ output: () => { },
932
+ setTodos: () => { },
933
+ ask: async () => {
934
+ throw new ToolInputError("A helper cannot ask the person.");
935
+ },
936
+ },
937
+ systemPrompt: helperPrompt(parent.name, parent.cwd),
938
+ task,
939
+ signal: live.controller.signal,
940
+ onStep: (line) => context.output(`${line}\n`),
941
+ onUsage: (usage) => this.#store.addUsage(sessionId, usage, this.#store.getSession(sessionId).contextTokens),
942
+ });
943
+ },
944
+ };
945
+ return context;
946
+ }
947
+ // --- letters (blueprint section 7) ---
948
+ #mailContext(sessionId, live, callId) {
949
+ return {
950
+ post: this.post,
951
+ canPostCards: this.post.canPostCards(this.#store.getSession(sessionId)),
952
+ send: (out) => {
953
+ const session = this.#store.getSession(sessionId);
954
+ return this.#mail.sent(sessionId, this.post.send({ kind: "session", session }, out));
955
+ },
956
+ wait: (letter) => this.#mail.awaitReply(sessionId, letter, live.controller.signal, callId),
957
+ open: (input) => this.#mail.openChild(this.#store.getSession(sessionId), input, callId),
958
+ finish: (outcome) => this.#store.setOutcome(sessionId, outcome),
959
+ manage: (args) => {
960
+ const by = this.#store.getSession(sessionId);
961
+ if (!this.post.canOrganize(by)) {
962
+ throw conflict("Only the main conversation, or a session the person allowed, can manage Yew.", undefined, "not-allowed");
963
+ }
964
+ return this.#manager.apply(by, args);
965
+ },
966
+ };
967
+ }
968
+ /**
969
+ * Starts a session that has letters waiting, when it is free: idle, or stopped by an error. A session
970
+ * that needs review (blueprint 7.3) or that the person stopped waits for the person; one that is
971
+ * working gets its letters between tool calls.
972
+ */
973
+ #wake(sessionId) {
974
+ if (this.isRunning(sessionId) || this.#held.isPaused(sessionId))
975
+ return;
976
+ let session;
977
+ try {
978
+ session = this.#store.getSession(sessionId);
979
+ }
980
+ catch {
981
+ return;
982
+ }
983
+ if (session.archivedAt !== null)
984
+ return;
985
+ if (session.status !== "idle" && session.status !== "error")
986
+ return;
987
+ // At a spending limit letters wait: for the next day, a higher limit, or the person.
988
+ if (reached(this.#store, session, Date.now()))
989
+ return;
990
+ if (this.post.mail.queuedFor(sessionId).length === 0)
991
+ return;
992
+ this.#dropLeftovers(sessionId, "Not run: a letter arrived and the conversation moved on.");
993
+ this.#start(sessionId);
994
+ }
995
+ /** Starts every free session with letters waiting: after a restart, and for letters from `yew send`. */
996
+ wakeQueued() {
997
+ this.#continueCapped();
998
+ for (const id of this.post.mail.sessionsWithQueued())
999
+ this.#wake(id);
1000
+ }
1001
+ /** Sessions that stopped at a spending limit today go on once the limit was raised or removed. */
1002
+ #continueCapped() {
1003
+ const now = Date.now();
1004
+ for (const [id, day] of this.#held.capped()) {
1005
+ let session;
1006
+ try {
1007
+ session = this.#store.getSession(id);
1008
+ }
1009
+ catch {
1010
+ this.#held.uncap(id);
1011
+ continue;
1012
+ }
1013
+ if (day !== localDay(now) || session.archivedAt !== null || this.#held.isPaused(id)) {
1014
+ this.#held.uncap(id);
1015
+ continue;
1016
+ }
1017
+ if (this.isRunning(id) || reached(this.#store, session, now))
1018
+ continue;
1019
+ this.#held.uncap(id);
1020
+ this.#start(id, { resume: true });
1021
+ }
1022
+ }
1023
+ /** A line for the person about a daily spending limit; returns the text. */
1024
+ #budgetNotice(sessionId, code, mark) {
1025
+ const whose = mark.scope === "session" ? "this session's" : "the shared";
1026
+ const amounts = `${dollars(mark.spent)} of ${dollars(mark.limit)}`;
1027
+ const text = code === "budget-reached"
1028
+ ? `Stopped: today's spending reached ${whose} daily limit (${amounts}).`
1029
+ : `Today's spending passed 80% of ${whose} daily limit (${amounts}).`;
1030
+ this.#notice(sessionId, "budget", text, {
1031
+ code,
1032
+ scope: mark.scope,
1033
+ spent: mark.spent,
1034
+ limit: mark.limit,
1035
+ });
1036
+ return text;
1037
+ }
1038
+ /**
1039
+ * A code session's last reply that nobody else reads, ending with a question or an offer, becomes a
1040
+ * question in the approval center, and the session shows that it waits. The latest such question
1041
+ * replaces an older one; the person's next message, or continuing, takes it away.
1042
+ */
1043
+ #askFromReply(session, said) {
1044
+ if (!session.cwd || session.archivedAt !== null || session.id === this.post.mainSessionId()) {
1045
+ return;
1046
+ }
1047
+ const older = this.#replyQuestions(session.id);
1048
+ const asked = askedInReply(said);
1049
+ if (asked) {
1050
+ for (const approval of older)
1051
+ this.#store.cancelApproval(approval.id);
1052
+ this.#store.createApproval({
1053
+ sessionId: session.id,
1054
+ toolCallId: null,
1055
+ kind: "question",
1056
+ request: { questions: [{ question: asked }], fromReply: true },
1057
+ });
1058
+ }
1059
+ if (asked || older.length > 0)
1060
+ this.#store.setStatus(session.id, "waiting", null);
1061
+ }
1062
+ #replyQuestions(sessionId) {
1063
+ return this.#store
1064
+ .pendingApprovals(sessionId)
1065
+ .filter((approval) => approval.request.fromReply === true);
1066
+ }
1067
+ #dropReplyQuestions(sessionId) {
1068
+ for (const approval of this.#replyQuestions(sessionId))
1069
+ this.#store.cancelApproval(approval.id);
1070
+ }
1071
+ /** The main conversation and the session's opener, as the system prompt names them. */
1072
+ #placement(session) {
1073
+ const mainId = this.post.mainSessionId();
1074
+ const ref = (id) => {
1075
+ if (!id)
1076
+ return null;
1077
+ try {
1078
+ return { id, name: this.#store.getSession(id).name };
1079
+ }
1080
+ catch {
1081
+ return null;
1082
+ }
1083
+ };
1084
+ return { main: ref(mainId), parent: ref(session.parentId), team: this.#groupName(session) };
1085
+ }
1086
+ #readState(sessionId) {
1087
+ let state = this.#readStates.get(sessionId);
1088
+ if (!state) {
1089
+ state = new ReadState();
1090
+ this.#readStates.set(sessionId, state);
1091
+ }
1092
+ return state;
1093
+ }
1094
+ #jobsFor(sessionId) {
1095
+ let jobs = this.#jobs.get(sessionId);
1096
+ if (!jobs) {
1097
+ jobs = new Jobs((job) => {
1098
+ const code = job.finished?.exitCode;
1099
+ const note = `Background job ${job.id} (${job.command}) ended${code === null || code === undefined ? "" : ` with exit code ${code}`}. Use shell_job to read its output.`;
1100
+ this.#note(sessionId, note);
1101
+ this.#notice(sessionId, "job_finished", note, {
1102
+ job: job.id,
1103
+ command: job.command,
1104
+ exitCode: code ?? null,
1105
+ });
1106
+ });
1107
+ this.#jobs.set(sessionId, jobs);
1108
+ }
1109
+ return jobs;
1110
+ }
1111
+ #note(sessionId, note) {
1112
+ const notes = this.#notes.get(sessionId) ?? [];
1113
+ notes.push(note);
1114
+ this.#notes.set(sessionId, notes);
1115
+ }
1116
+ /**
1117
+ * Models tend to write a task list once and then forget it, so the list the person sees falls behind.
1118
+ * After many calls without a change while tasks are still open, Yew reminds the model to update it.
1119
+ */
1120
+ #remindTodos(sessionId, calls) {
1121
+ if (calls.some((call) => call.name === "todo")) {
1122
+ this.#sinceTodo.delete(sessionId);
1123
+ return;
1124
+ }
1125
+ const count = (this.#sinceTodo.get(sessionId) ?? 0) + calls.length;
1126
+ const open = this.#store.getSession(sessionId).todos.some((todo) => todo.status !== "done");
1127
+ if (count < TODO_REMINDER_AFTER || !open) {
1128
+ this.#sinceTodo.set(sessionId, count);
1129
+ return;
1130
+ }
1131
+ this.#sinceTodo.delete(sessionId);
1132
+ this.#note(sessionId, `Your task list has not changed in the last ${count} tool calls. If it no longer matches the work, update it with the todo tool.`);
1133
+ }
1134
+ /** Moves Yew's notes, letters and the person's queued messages into the transcript; true if anything arrived. */
1135
+ #deliver(sessionId) {
1136
+ const notes = this.#notes.get(sessionId) ?? [];
1137
+ this.#notes.delete(sessionId);
1138
+ for (const note of notes) {
1139
+ this.#store.appendEntry(sessionId, userEntry(`${YEW_NOTE} ${note}`));
1140
+ }
1141
+ const letters = this.#mail.deliver(sessionId, this.#mail.firstDelivery(sessionId));
1142
+ const fromPerson = this.#store.deliverQueue(sessionId, userEntry).length;
1143
+ if (fromPerson > 0) {
1144
+ // What the person wrote starts a new chain of hand-offs, and they are watching now.
1145
+ this.post.resetChain(sessionId);
1146
+ this.#mail.watched(sessionId);
1147
+ }
1148
+ return letters > 0 || fromPerson > 0 || notes.length > 0;
1149
+ }
1150
+ /** The name of the session's group, for the system prompt. */
1151
+ #groupName(session) {
1152
+ if (!session.groupId)
1153
+ return null;
1154
+ return this.#store.listGroups().find((group) => group.id === session.groupId)?.name ?? null;
1155
+ }
1156
+ #notice(sessionId, kind, text, data) {
1157
+ notice(this.#store, sessionId, kind, text, data);
1158
+ }
1159
+ }