rushes 0.9.1 → 0.10.1

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.
@@ -0,0 +1,1031 @@
1
+ // §28.2, §28.3: one run of the user's own agent per project. The runner owns the adapter process, the
2
+ // conversation, the turn queue, progress, permission asks (§28.4), answers on notes (§28.5) and Stop.
3
+ //
4
+ // How it moves:
5
+ // idle/finished/question/failed --send--> starting (adapter up, initialize, load or new session)
6
+ // starting --ready--> working (one session/prompt per turn: batches and follow-ups, in order of arrival)
7
+ // starting --fails--> failed (notes of every waiting batch recalled; send says why)
8
+ // working --an ask the rules don't allow--> waiting (until the user answers; never by time) --> working
9
+ // working --turn ends, more queued--> working; --turn ends, none--> question | finished (idle timer armed)
10
+ // working --adapter exits--> failed (notes recalled); any busy phase --stop--> idle (notes recalled)
11
+ // Stop, close and an adapter exit answer every pending ask cancelled.
12
+ //
13
+ // `gen` counts stops and closes. Anything that awaited (a start, a turn's end) checks it afterwards, so
14
+ // work begun before a Stop never changes the state after it.
15
+ import { ACTIVITY_LINE_MAX, ActivityTracker } from "../../core/agentActivity.js";
16
+ import { alwaysLabel, decide } from "../../core/agentRules.js";
17
+ import { NotFoundError, RushesError } from "../../core/errors.js";
18
+ import { oneLine } from "../../core/labels.js";
19
+ import { lineEvent } from "../../core/logEvents.js";
20
+ import { needsYou, noteState, recallNote, recallNotes } from "../../core/noteState.js";
21
+ import { logBookFor } from "../logbook.js";
22
+ import { AcpConnection } from "./acp.js";
23
+ import { ASK_MODE, adapterSpec, clientMeta, rushesMcp, sessionSetup } from "./adapters.js";
24
+ import { noteToolCall, withSeen } from "./seenCalls.js";
25
+ import { isOwnRushesTool, noteMcpCall } from "./ownTools.js";
26
+ import { PermissionBroker, addRule, allowOutcome, dropRule, toRequest } from "./broker.js";
27
+ import { detectAgents } from "./detect.js";
28
+ import { agentRulesFor } from "./rules.js";
29
+ import { batchJob, followUpFor } from "./followUp.js";
30
+ /** How long the adapter stays up after its last turn (§5.2). */
31
+ export const AGENT_IDLE_MS = 600_000;
32
+ /** How long an adapter may take to start, from spawn to a ready session (a first `npx -y` fetch included). */
33
+ export const AGENT_START_MS = 120_000;
34
+ /** How long Stop waits for a cancelled turn to end before it kills the adapter. */
35
+ export const STOP_WAIT_MS = 5000;
36
+ /** Activity keeps this many lines, in memory only. */
37
+ export const AGENT_LINES_KEPT = 200;
38
+ /** Long enough for AcpConnection.kill's SIGKILL (2 s) to land. */
39
+ const EXIT_WAIT_MS = 4000;
40
+ const CANCELLED = { outcome: "cancelled" };
41
+ /** Why a send or follow-up is refused once close() has begun. */
42
+ const CLOSING = "Rushes is closing";
43
+ /** A turn's failure in the adapter's words is kept to this many characters (the chip's tooltip). */
44
+ const ERROR_MAX = 200;
45
+ /** An answer's name in Activity (Task 10, 4): its follow-up's label, or "your answer on a note" when it was never read. */
46
+ const answerOf = (job) => job?.label ?? "your answer on a note";
47
+ const capitalised = (s) => s.charAt(0).toUpperCase() + s.slice(1);
48
+ /** I1: Send to AI is on in the project, but the user's own rules file has no answer to the first-Send sheet. */
49
+ export const NOT_SET_UP = "Send to AI is not set up";
50
+ const OFF = "Send to AI is off";
51
+ /** Each agent by name, as Activity and the notification say it. */
52
+ export const AGENT_NAMES = { claude: "Claude Code", codex: "Codex" };
53
+ const NAMES = AGENT_NAMES;
54
+ /** A start-up ended by Stop or close, not by a failure. */
55
+ /** The session could not be put in the mode in which the agent asks Rushes (R14, R15): the start fails with this. */
56
+ class ModeError extends Error {
57
+ }
58
+ class Halted extends Error {
59
+ constructor() {
60
+ super("Stopped before the agent started");
61
+ }
62
+ }
63
+ const messageOf = (e) => (e instanceof Error ? e.message : String(e));
64
+ /** 120000 -> "2 minutes", 1500 -> "1.5 seconds". */
65
+ function spell(ms) {
66
+ if (ms >= 60_000 && ms % 60_000 === 0)
67
+ return ms === 60_000 ? "1 minute" : `${ms / 60_000} minutes`;
68
+ return ms === 1000 ? "1 second" : `${ms / 1000} seconds`;
69
+ }
70
+ /** The last line of a stderr tail with anything in it, as one short line. */
71
+ function lastLine(stderr) {
72
+ const lines = stderr.split(/\r?\n/).map((l) => oneLine(l, ACTIVITY_LINE_MAX)).filter((l) => l !== "" && l !== "…");
73
+ return lines.at(-1) ?? "";
74
+ }
75
+ /** Resolves when `c` has exited, or after `ms` (kill's SIGKILL has landed by then). */
76
+ function exited(c, ms = EXIT_WAIT_MS) {
77
+ if (c.hasExited)
78
+ return Promise.resolve();
79
+ return new Promise((resolve) => {
80
+ const t = setTimeout(resolve, ms);
81
+ t.unref();
82
+ c.once("exit", () => {
83
+ clearTimeout(t);
84
+ resolve();
85
+ });
86
+ });
87
+ }
88
+ /** Waits for `p` or `ms`, whichever comes first, and clears the timer when `p` wins. */
89
+ async function within(p, ms) {
90
+ let timer;
91
+ const timeout = new Promise((resolve) => {
92
+ timer = setTimeout(resolve, ms);
93
+ timer.unref();
94
+ });
95
+ try {
96
+ await Promise.race([p, timeout]);
97
+ }
98
+ finally {
99
+ clearTimeout(timer);
100
+ }
101
+ }
102
+ export class AgentRunner {
103
+ store;
104
+ detect;
105
+ specFor;
106
+ /**
107
+ * Per adapter: which agent it runs, (Codex only) its MCP calls by tool call id (R16), and its session's mode as
108
+ * last reported (round 2, item 3).
109
+ */
110
+ adapters = new WeakMap();
111
+ mcp;
112
+ idleMs;
113
+ startMs;
114
+ now;
115
+ settings = null;
116
+ /** The user's rules for this project, kept outside it (R10). `rules` is the last read, for the status. */
117
+ rulesFile;
118
+ rules = { permissions: "project-edits", always: [], setUp: false, agent: null };
119
+ /** I3: batches whose hand-over was refused while Send to AI was on (not signed in, not set up…); resend takes each once. */
120
+ refused = new Set();
121
+ ruleReads = 0;
122
+ rulesApplied = 0;
123
+ /** agent.json reads started, and the newest one applied (a write counts as one). */
124
+ reads = 0;
125
+ applied = 0;
126
+ phase = "idle";
127
+ error = null;
128
+ lines = [];
129
+ current = { note: null, doing: null };
130
+ /** Batches and follow-ups waiting for their turn, in the order they came in. */
131
+ queue = [];
132
+ /** The job whose session/prompt is in flight; `done` settles when that prompt does. */
133
+ turn = null;
134
+ /** Permission asks waiting for the user. */
135
+ broker;
136
+ /** The latest Always rule write; a permission ask waits for it before reading the rules. */
137
+ ruleWrite = Promise.resolve();
138
+ /** R13: per note, the follow-ups being handed (from the user's answer until hand() returns). */
139
+ answering = new Map();
140
+ /** A turn has ended and the runner is reading the notes to choose question or finished. */
141
+ ending = false;
142
+ conn = null;
143
+ sessionId = null;
144
+ /** The agent the running adapter was started for. */
145
+ info = null;
146
+ exits = new WeakMap();
147
+ /** Every adapter process not yet seen to exit, so close() leaves none behind. */
148
+ live = new Set();
149
+ starting = null;
150
+ stopping = null;
151
+ idleTimer = null;
152
+ gen = 0;
153
+ closed = false;
154
+ closing = null;
155
+ /** Sends are checked and queued one at a time, so two at once keep their order. */
156
+ sendLock = Promise.resolve();
157
+ /** Writes started from event handlers (recalls, Change Log lines, settings reads); close() waits for them. */
158
+ pending = new Set();
159
+ onChange = (e) => {
160
+ if (e.file === "agent" && !this.closed)
161
+ this.track(this.loadSettings());
162
+ };
163
+ /** The user answered on a note: a follow-up turn when R11 allows one (followUp.ts). */
164
+ onUserReply = (e) => {
165
+ if (!this.closed)
166
+ this.track(this.followUp(e));
167
+ };
168
+ constructor(store, opts = {}) {
169
+ this.store = store;
170
+ this.detect = opts.detect ?? (() => detectAgents());
171
+ this.specFor = opts.spec ?? adapterSpec;
172
+ this.mcp = opts.mcp ?? rushesMcp;
173
+ this.idleMs = opts.idleMs ?? AGENT_IDLE_MS;
174
+ this.startMs = opts.startMs ?? AGENT_START_MS;
175
+ this.now = opts.now ?? (() => new Date());
176
+ this.broker = new PermissionBroker(store.root, { now: this.now, onChange: () => this.asksChanged() });
177
+ this.rulesFile = agentRulesFor(store);
178
+ store.on("change", this.onChange);
179
+ store.on("user-reply", this.onUserReply);
180
+ this.track(this.loadSettings());
181
+ this.track(this.loadRules());
182
+ }
183
+ /** Consent fix: on only when the project's switch is on for the agent the user chose, in their own rules file. */
184
+ switchedOn(settings, rules) {
185
+ return !!settings?.on && rules.agent !== null && rules.agent === settings.agent;
186
+ }
187
+ status() {
188
+ const on = this.switchedOn(this.settings, this.rules);
189
+ const jobs = [...(this.turn ? [this.turn.job] : []), ...this.queue];
190
+ return {
191
+ on,
192
+ agent: this.settings?.agent ?? null,
193
+ phase: !on && !this.busy() ? "off" : this.broker.size > 0 ? "waiting" : this.phase,
194
+ batches: jobs.filter((j) => j.kind === "batch").map((j) => j.batchId),
195
+ followUps: jobs.flatMap((j) => (j.kind === "followUp" && j.note ? [j.note] : [])),
196
+ current: { ...this.current },
197
+ asks: this.broker.pending(),
198
+ lines: this.lines.slice(),
199
+ error: this.error,
200
+ session: this.settings?.session?.id ?? null,
201
+ // I1: from the user's own rules file, never the project's agent.json.
202
+ asked: this.rules.setUp,
203
+ permissions: this.rules.permissions,
204
+ always: this.rules.always.map((r) => ({ ...r })),
205
+ };
206
+ }
207
+ /** Reads agent.json and the rules now and gives the status from them: for a route that has just changed either. */
208
+ async reload() {
209
+ await Promise.all([this.loadSettings(), this.loadRules()]);
210
+ return this.status();
211
+ }
212
+ /** From the first send until the queue is empty and no ask is waiting. */
213
+ busy() {
214
+ return this.starting !== null || this.stopping !== null || this.turn !== null || this.ending || this.queue.length > 0 || this.broker.size > 0;
215
+ }
216
+ /**
217
+ * Hands a filed batch to the agent: it starts the adapter if none is up, or queues behind the turn in
218
+ * flight. Never rejects: when the batch can't be handed over it says why, so the desk can copy the prompt.
219
+ */
220
+ async send(batch) {
221
+ const r = (await this.hand(async () => batchJob(batch)));
222
+ // A batch is never parked (only a follow-up is).
223
+ return this.noteRefusal(batch.id, "park" in r ? { handedTo: null, why: r.why } : r);
224
+ }
225
+ /**
226
+ * I3: hands over a batch whose hand-over was refused, once (the copy dialog's Set up, through the setup route). The id
227
+ * is taken from the refused set under the send lock, so two at once hand it over once. Null when it wasn't refused, or
228
+ * has gone already.
229
+ */
230
+ async resend(batch) {
231
+ const r = await this.hand(async () => (this.refused.delete(batch.id) ? batchJob(batch) : null));
232
+ if (r === null)
233
+ return null;
234
+ return this.noteRefusal(batch.id, "park" in r ? { handedTo: null, why: r.why } : r);
235
+ }
236
+ /**
237
+ * Records a batch refused while Send to AI really was on (the user's agent, switched on) and nothing started, its notes
238
+ * still waiting with it (not signed in, not installed), for resend. Not one refused because it only looked on (not set
239
+ * up, no agent chosen) or was off: the desk offers no Set up for those, and the user may have copied the prompt.
240
+ */
241
+ noteRefusal(id, r) {
242
+ if (r.handedTo === null && !r.stopped && !r.recalled && r.why !== CLOSING && this.switchedOn(this.settings, this.rules))
243
+ this.refused.add(id);
244
+ return r;
245
+ }
246
+ /**
247
+ * Hands the answer on as a follow-up (R11). With Send to AI on but no kept session, or the agent not signed in,
248
+ * the note goes back to to do and Activity says so. One that can't be sent for another reason says why, unless
249
+ * Send to AI is off.
250
+ */
251
+ async followUp(e) {
252
+ // R13: held from before hand() until it returns (the job is queued or running by then, or refused), so a turn
253
+ // ending meanwhile leaves this note to the follow-up.
254
+ this.answering.set(e.note, (this.answering.get(e.note) ?? 0) + 1);
255
+ try {
256
+ await this.followUpHanded(e);
257
+ }
258
+ finally {
259
+ const left = (this.answering.get(e.note) ?? 1) - 1;
260
+ if (left > 0)
261
+ this.answering.set(e.note, left);
262
+ else
263
+ this.answering.delete(e.note);
264
+ }
265
+ }
266
+ async followUpHanded(e) {
267
+ let job = null;
268
+ const r = await this.hand(async () => {
269
+ job = await followUpFor(this.store, e).catch((err) => {
270
+ console.error(`Rushes: couldn't read note ${e.note} to pass on its answer: ${messageOf(err)}`);
271
+ throw err;
272
+ });
273
+ return job;
274
+ });
275
+ if (!r)
276
+ return;
277
+ if ("park" in r) {
278
+ await this.recall({ batches: [], notes: [{ id: e.note, batch: r.park.batch }] });
279
+ if (this.closed)
280
+ return;
281
+ this.addLine(`${capitalised(answerOf(job))} is saved. Press Send to hand it to ${r.park.name}.`, e.note);
282
+ this.announce();
283
+ return;
284
+ }
285
+ if (this.closed) {
286
+ // Refused because Rushes is closing, before it was queued: its note goes back too (I3), as a queued job's does.
287
+ const j = job;
288
+ if (j?.note && r.handedTo === null && r.why === CLOSING)
289
+ await this.recall({ batches: [], notes: [{ id: j.note, batch: j.batchId }] });
290
+ return;
291
+ }
292
+ // Quiet when Send to AI is off, and when the user's own Stop cut it short.
293
+ if (r.handedTo !== null || r.stopped || r.why === "Send to AI is off")
294
+ return;
295
+ this.addLine(`${capitalised(answerOf(job))} was not sent: ${r.why}`, e.note);
296
+ this.announce();
297
+ }
298
+ /** Queues the job `make` gives (none: nothing to do, null back), then starts the adapter or pumps the queue. */
299
+ async hand(make) {
300
+ const accepting = this.sendLock.then(async () => {
301
+ // A follow-up is dropped if a Stop lands after its note was read: the Stop may have taken the note back.
302
+ const gen = this.gen;
303
+ const job = await make();
304
+ return job ? this.accept(job, job.kind === "followUp" ? gen : null) : null;
305
+ });
306
+ this.sendLock = accepting.catch(() => undefined);
307
+ let accepted;
308
+ try {
309
+ accepted = await accepting;
310
+ }
311
+ catch (e) {
312
+ return { handedTo: null, why: messageOf(e) };
313
+ }
314
+ if (accepted === null)
315
+ return null;
316
+ if ("park" in accepted)
317
+ return { handedTo: null, why: accepted.why, park: accepted.park };
318
+ if ("why" in accepted)
319
+ return accepted.stopped ? { handedTo: null, why: accepted.why, stopped: true } : { handedTo: null, why: accepted.why };
320
+ try {
321
+ await this.ensureStarted();
322
+ }
323
+ catch (e) {
324
+ // Halted by the user's Stop (not by close): flagged, so the desk doesn't fall back to copying the prompt.
325
+ if (e instanceof Halted && !this.closed)
326
+ return { handedTo: null, why: e.message, stopped: true };
327
+ // The job was queued before the start: the failure (failRun) or the close (shutdown) gave its notes back.
328
+ return { handedTo: null, why: messageOf(e), recalled: true };
329
+ }
330
+ this.pump();
331
+ return { handedTo: accepted.info.id };
332
+ }
333
+ /**
334
+ * Checks the switch, the agent and its sign-in, then queues the job. Runs one at a time. A follow-up that can't
335
+ * go now for want of a kept session or a signed-in agent is parked: its note goes back to to do (R11).
336
+ */
337
+ async accept(job, sinceGen) {
338
+ while (this.stopping)
339
+ await this.stopping;
340
+ if (this.closed)
341
+ return { why: CLOSING };
342
+ const [settings, rules] = await Promise.all([this.loadSettings(), this.loadRules()]);
343
+ if (!settings.on)
344
+ return { why: OFF };
345
+ const agent = settings.agent;
346
+ const park = (why, name) => job.kind === "followUp" ? { why, park: { name, batch: job.batchId } } : { why };
347
+ // I1 and the consent fix: the switch and the agent in the project's agent.json are not the user's consent; the agent
348
+ // they chose, in their own rules file, is. Unless the two name the same agent nothing is handed over and nothing
349
+ // starts: the desk shows Send to AI off and copies the prompt, or opens the first-Send sheet.
350
+ if (agent && !this.switchedOn(settings, rules))
351
+ return park(NOT_SET_UP, NAMES[agent]);
352
+ if (job.kind === "followUp" && (!agent || settings.session?.agent !== agent)) {
353
+ return park("No conversation to carry on", agent ? NAMES[agent] : "your agent");
354
+ }
355
+ if (!agent)
356
+ return { why: "No agent chosen" };
357
+ const info = (await this.detect()).find((a) => a.id === agent);
358
+ if (!info?.installed)
359
+ return park(`${info?.name ?? NAMES[agent]} is not installed`, info?.name ?? NAMES[agent]);
360
+ if (!info.signedIn)
361
+ return park(`${info.name} is not signed in`, info.name);
362
+ // A follow-up's note may have left the agent while this was checking (recalled, done): then there is nothing to
363
+ // follow up, and it is dropped quietly, with no line and no turn.
364
+ if (job.kind === "followUp" && !(await this.stillSent(job)))
365
+ return null;
366
+ // A Stop or close may have begun while this send was checking.
367
+ while (this.stopping)
368
+ await this.stopping;
369
+ if (this.closed)
370
+ return { why: CLOSING };
371
+ if (sinceGen !== null && sinceGen !== this.gen)
372
+ return { why: "Stopped", stopped: true };
373
+ const queued = this.busy();
374
+ if (!queued && this.conn) {
375
+ // An idle adapter for another agent or another conversation is replaced.
376
+ const kept = settings.session?.id ?? null;
377
+ if (this.info?.id !== info.id || this.sessionId !== kept)
378
+ this.dropConn();
379
+ }
380
+ if (!queued)
381
+ this.info = info;
382
+ this.clearIdle();
383
+ this.queue.push(job);
384
+ // Queued behind a run: say so now. Otherwise the start or the turn about to begin says it.
385
+ if (queued)
386
+ this.announce();
387
+ return { info };
388
+ }
389
+ /** The follow-up's note is still with the agent, in the batch the follow-up was made for. */
390
+ async stillSent(job) {
391
+ const n = (await this.store.read("notes")).notes.find((x) => x.id === job.note);
392
+ return n !== undefined && noteState(n) === "sent" && n.batch === job.batchId;
393
+ }
394
+ /** One start at a time: a second caller waits on the first one's promise. */
395
+ ensureStarted() {
396
+ if (this.starting)
397
+ return this.starting;
398
+ if (this.closed)
399
+ return Promise.reject(new Error(CLOSING));
400
+ if (this.conn && this.sessionId && !this.conn.hasExited)
401
+ return Promise.resolve();
402
+ const info = this.info;
403
+ if (!info)
404
+ return Promise.reject(new Error("No agent chosen"));
405
+ const p = this.start(info).finally(() => {
406
+ if (this.starting === p)
407
+ this.starting = null;
408
+ });
409
+ this.starting = p;
410
+ return p;
411
+ }
412
+ async start(info) {
413
+ const gen = this.gen;
414
+ const root = this.store.root;
415
+ this.clearIdle();
416
+ this.phase = "starting";
417
+ this.error = null;
418
+ this.current = { note: null, doing: null };
419
+ this.announce();
420
+ let conn = null;
421
+ // A start that outlives startMs (a slow first fetch, an adapter that stalls) fails like any other start.
422
+ let timedOut = false;
423
+ let timer;
424
+ try {
425
+ conn = AcpConnection.start(this.specFor(info, root));
426
+ this.attach(conn, info.id);
427
+ const c = conn;
428
+ const deadline = new Promise((_, reject) => {
429
+ timer = setTimeout(() => {
430
+ timedOut = true;
431
+ reject(new Error("timed out"));
432
+ }, this.startMs);
433
+ timer.unref();
434
+ });
435
+ const opening = this.open(c, info, gen, root);
436
+ // Left behind on a timeout: the adapter is killed below, and what it then throws is not news.
437
+ opening.catch(() => undefined);
438
+ await Promise.race([opening, deadline]);
439
+ }
440
+ catch (e) {
441
+ if (e instanceof Halted || gen !== this.gen)
442
+ throw e instanceof Halted ? e : new Halted();
443
+ if (conn && this.conn === conn)
444
+ this.dropConn();
445
+ const tail = conn && !timedOut ? lastLine(this.exits.get(conn)?.stderr ?? "") : "";
446
+ const why = timedOut
447
+ ? `${info.name} did not start within ${spell(this.startMs)}`
448
+ : e instanceof ModeError
449
+ ? e.message
450
+ : `${info.name} could not start: ${tail || messageOf(e)}`;
451
+ await this.failRun(why);
452
+ throw new Error(why);
453
+ }
454
+ finally {
455
+ clearTimeout(timer);
456
+ }
457
+ }
458
+ /** From initialize to a ready session on `c`. Throws Halted when a Stop or close, or another adapter, came first. */
459
+ async open(c, info, gen, root) {
460
+ const check = () => {
461
+ if (gen !== this.gen || this.conn !== c)
462
+ throw new Halted();
463
+ };
464
+ const { loadSession } = await c.initialize(clientMeta(info.id));
465
+ check();
466
+ const settings = await this.loadSettings();
467
+ check();
468
+ const mcp = [this.mcp(root)];
469
+ const setup = sessionSetup(info.id);
470
+ const kept = settings.session;
471
+ let sessionId = null;
472
+ let modes = [];
473
+ let current = null;
474
+ if (kept && kept.agent === info.id && loadSession) {
475
+ try {
476
+ ({ modes, current } = await c.loadSession(kept.id, root, mcp, setup));
477
+ sessionId = kept.id;
478
+ }
479
+ catch (e) {
480
+ // An agent prunes old conversations. With the adapter still up, start a new one rather than fail
481
+ // this Send and every one after it.
482
+ if (c.hasExited)
483
+ throw e;
484
+ check();
485
+ this.addLine("Started a new conversation (the last one could not be loaded)", null);
486
+ }
487
+ }
488
+ if (sessionId === null) {
489
+ const opened = await c.newSession(root, mcp, setup);
490
+ const made = opened.sessionId;
491
+ sessionId = made;
492
+ ({ modes, current } = opened);
493
+ check();
494
+ const startedAt = this.now().toISOString();
495
+ const { data } = await this.store.update("agent", (f) => {
496
+ f.session = { id: made, agent: info.id, startedAt };
497
+ });
498
+ this.applySettings(data);
499
+ }
500
+ check();
501
+ await this.askMode(c, info, sessionId, modes, current);
502
+ check();
503
+ if (c.hasExited)
504
+ throw new Error("the adapter exited as it started");
505
+ this.sessionId = sessionId;
506
+ }
507
+ /**
508
+ * R14/R15: every opened or loaded session goes into the mode in which the agent asks Rushes before it acts
509
+ * (ASK_MODE), before the first prompt. Fails closed (round 2, item 3): the start fails with a ModeError, and its
510
+ * notes go back, when the mode isn't offered (or no modes are reported), when set_mode throws, or when the
511
+ * session's mode isn't the ask mode afterwards. That mode is the setup response's currentModeId, then the
512
+ * ask mode once set_mode succeeds, unless a current_mode_update during set_mode reports another one (as
513
+ * claude-agent-acp's setSessionMode does when it falls back).
514
+ */
515
+ async askMode(c, info, sessionId, modes, current) {
516
+ const want = ASK_MODE[info.id];
517
+ const refused = new ModeError(`${info.name} could not be put in a mode where Rushes approves actions`);
518
+ const adapter = this.adapters.get(c);
519
+ if (!adapter || !modes.includes(want))
520
+ throw refused;
521
+ adapter.mode = current;
522
+ adapter.modeReported = false;
523
+ try {
524
+ await c.setMode(sessionId, want);
525
+ }
526
+ catch (e) {
527
+ if (c.hasExited)
528
+ throw e;
529
+ throw refused;
530
+ }
531
+ if (!adapter.modeReported)
532
+ adapter.mode = want;
533
+ if (adapter.mode !== want)
534
+ throw refused;
535
+ }
536
+ /** Makes `conn` the runner's adapter and listens to it. */
537
+ attach(conn, agent) {
538
+ this.conn = conn;
539
+ this.sessionId = null;
540
+ this.live.add(conn);
541
+ // R16: Codex names an MCP call's server and tool only in its tool_call update, before the approval comes.
542
+ const calls = new Map();
543
+ // Task 10 (3): each adapter's tool calls are followed from announced to run, so a command says it ran only then.
544
+ // Task 10 round 2 (1): every tool call's kind, input and paths, so an ask that lacks them (Codex under AIR) gets them.
545
+ const seen = new Map();
546
+ const adapter = { agent, calls, seen, mode: null, modeReported: false, activity: new ActivityTracker(this.store.root) };
547
+ this.adapters.set(conn, adapter);
548
+ conn.on("update", (u) => {
549
+ if (agent === "codex")
550
+ noteMcpCall(calls, u);
551
+ noteToolCall(seen, u);
552
+ const m = u;
553
+ if (m?.sessionUpdate === "current_mode_update" && typeof m.currentModeId === "string") {
554
+ adapter.mode = m.currentModeId;
555
+ adapter.modeReported = true;
556
+ }
557
+ this.onUpdate(conn, u);
558
+ });
559
+ conn.on("exit", (e) => this.onExit(conn, e));
560
+ conn.onPermission((p) => this.onPermission(conn, p));
561
+ }
562
+ /** Lets go of the adapter and asks it to exit. Its exit event is then ignored, and its asks are cancelled. */
563
+ dropConn() {
564
+ const c = this.conn;
565
+ this.conn = null;
566
+ this.sessionId = null;
567
+ this.broker.cancelAll();
568
+ c?.kill();
569
+ return c;
570
+ }
571
+ /**
572
+ * The agent asks to do something. Allowed by the project's rules: yes at once, no ask shown. Otherwise the
573
+ * ask waits in the broker for the user. Asks from an adapter that is going (Stop, close, replaced) get "cancelled".
574
+ */
575
+ async onPermission(conn, asked) {
576
+ const live = () => !this.closed && !this.stopping && conn === this.conn && !conn.hasExited;
577
+ if (!live())
578
+ return CANCELLED;
579
+ const adapter = this.adapters.get(conn);
580
+ // What the ask lacks (a kind, a command, paths) comes from the tool call this adapter reported for it (seenCalls.ts).
581
+ const p = adapter ? withSeen(asked, adapter.seen) : asked;
582
+ // R16: Rushes's own MCP tools never ask, under any permission level.
583
+ if (adapter && isOwnRushesTool(adapter.agent, this.store.root, p, adapter.calls))
584
+ return allowOutcome(p.options);
585
+ // The adapter hears "yes" before an Always rule is written: wait for that write, then read the rules.
586
+ await this.ruleWrite;
587
+ const rules = await this.loadRules();
588
+ if (!live())
589
+ return CANCELLED;
590
+ if (decide(toRequest(p, this.store.root), rules, this.store.root) === "allow")
591
+ return allowOutcome(p.options);
592
+ return this.broker.ask(p);
593
+ }
594
+ asksChanged() {
595
+ this.announce();
596
+ // The last ask answered with nothing else going on: the adapter's idle time starts again.
597
+ if (!this.busy() && !this.closed)
598
+ this.armIdle();
599
+ }
600
+ /** The user's answer to a pending ask. "always" also keeps the rule in the user's rules file. */
601
+ async answer(askId, choice) {
602
+ const rule = this.broker.answer(askId, choice);
603
+ if (rule)
604
+ await this.ruleWriting(this.keepRule(rule));
605
+ }
606
+ /** Takes an Always rule out of the user's rules file by its kind and command (T6). One not there is not found. */
607
+ async removeRule(rule) {
608
+ await this.ruleWriting(this.rulesFile.update((f) => dropRule(f.always, { kind: rule.kind, command: rule.command })).then(({ data }) => {
609
+ this.applyRules(data);
610
+ }));
611
+ }
612
+ /** A change to the Always rules: an ask arriving meanwhile waits for it before reading them. */
613
+ ruleWriting(writing) {
614
+ this.ruleWrite = writing.catch(() => undefined);
615
+ return writing;
616
+ }
617
+ /** Keeps the rule in the user's rules file (once; the oldest goes at the cap) and says so in Activity and the Change Log. */
618
+ async keepRule(rule) {
619
+ const { data, result: added } = await this.rulesFile.update((f) => addRule(f.always, rule));
620
+ this.applyRules(data);
621
+ if (added) {
622
+ const text = `Always allowed: ${alwaysLabel(rule)}`;
623
+ this.addLine(text, null);
624
+ await this.writeMilestone(text);
625
+ }
626
+ this.announce();
627
+ }
628
+ /** Starts the next queued batch when nothing else is in flight. */
629
+ pump() {
630
+ if (this.closed || this.turn || this.ending || this.starting || this.stopping || this.queue.length === 0)
631
+ return;
632
+ const conn = this.conn;
633
+ const sessionId = this.sessionId;
634
+ if (!conn || !sessionId || conn.hasExited) {
635
+ // The adapter went away between turns: start a fresh one (it loads the session), then come back.
636
+ this.ensureStarted().then(() => this.pump(), () => undefined);
637
+ return;
638
+ }
639
+ const job = this.queue.shift();
640
+ const gen = this.gen;
641
+ const name = this.info?.name ?? "The agent";
642
+ this.clearIdle();
643
+ let done;
644
+ this.turn = { job, done: new Promise((r) => (done = r)) };
645
+ this.phase = "working";
646
+ this.error = null;
647
+ this.current = { note: null, doing: null };
648
+ this.milestone(job.kind === "batch" ? `${name} started on ${job.label}` : `${name} picked up ${job.label}`);
649
+ this.announce();
650
+ this.track(conn.prompt(sessionId, job.prompt).then((r) => {
651
+ done();
652
+ return r.failure !== null ? this.turnFailedInPlace(gen, job, r.failure) : this.turnEnded(gen, job, r.stopReason);
653
+ }, (err) => {
654
+ done();
655
+ this.turnFailed(gen, conn, job, err);
656
+ }));
657
+ }
658
+ async turnEnded(gen, job, stopReason) {
659
+ // Stopped, closed or failed meanwhile: whoever did that has already settled this job.
660
+ if (gen !== this.gen || this.turn?.job !== job)
661
+ return;
662
+ const name = this.info?.name ?? "The agent";
663
+ this.turn = null;
664
+ this.ending = true;
665
+ this.milestone(stopReason === "end_turn" ? `${name} finished ${job.label}` : `${name} ended ${job.label} (${stopReason})`);
666
+ this.announce();
667
+ // Still busy while the notes are read, so a send now queues and is picked up below. The phase follows
668
+ // the batch this turn worked on: a question on one of its notes makes it "question".
669
+ let question = false;
670
+ let back = 0;
671
+ try {
672
+ const notes = await this.store.read("notes");
673
+ question = notes.notes.some((n) => n.batch === job.batchId && needsYou(n));
674
+ // M3: what the turn left untouched (still sent, no question waiting) goes back to to do.
675
+ if (notes.notes.some((n) => this.leftOver(job, n))) {
676
+ const { result } = await this.store.update("notes", (f) => {
677
+ const left = f.notes.filter((n) => this.leftOver(job, n));
678
+ for (const n of left)
679
+ recallNote(f.notes, n.id, job.batchId);
680
+ return left.length;
681
+ });
682
+ back = result;
683
+ }
684
+ }
685
+ catch (e) {
686
+ console.error(`Rushes: couldn't read the notes after a turn: ${messageOf(e)}`);
687
+ }
688
+ if (gen !== this.gen)
689
+ return;
690
+ if (back > 0)
691
+ this.addLine(back === 1 ? "1 note was not picked up and is back in to do" : `${back} notes were not picked up and are back in to do`, null);
692
+ this.ending = false;
693
+ if (this.queue.length)
694
+ return this.pump();
695
+ this.phase = question ? "question" : "finished";
696
+ this.current = { note: null, doing: null };
697
+ this.announce();
698
+ this.armIdle();
699
+ }
700
+ /**
701
+ * M3: a note the ended turn left with the agent: still sent in the turn's batch, no question waiting on it, and no
702
+ * other follow-up for it in flight. A follow-up turn answers for its own note only.
703
+ *
704
+ * R13: a follow-up in flight is one being handed (`answering`: read, accepted, started) or queued. The turn ending
705
+ * now has already left `this.turn`, so a follow-up turn that leaves its own note untouched gives it back unless
706
+ * another answer on it is still on its way.
707
+ */
708
+ leftOver(job, n) {
709
+ if (n.batch !== job.batchId || noteState(n) !== "sent" || needsYou(n))
710
+ return false;
711
+ if (job.kind === "followUp" && n.id !== job.note)
712
+ return false;
713
+ return !this.followUpInFlight(n.id);
714
+ }
715
+ followUpInFlight(note) {
716
+ return (this.answering.get(note) ?? 0) > 0 || this.queue.some((q) => q.kind === "followUp" && q.note === note);
717
+ }
718
+ /**
719
+ * Task 10 (1): the adapter answered the prompt but said the turn failed (Codex: a model it can't use, a service error).
720
+ * The run fails with the adapter's words, one line: "<A> couldn't finish: <words>" in Activity and the Change Log, and
721
+ * the words as the status's error. As when a turn ends (M3), the notes it left untouched go back to to do, and asked
722
+ * and done ones stay; the jobs queued behind it give their notes back, as a failure's do. The adapter stays up.
723
+ */
724
+ async turnFailedInPlace(gen, job, message) {
725
+ if (gen !== this.gen || this.turn?.job !== job)
726
+ return;
727
+ const name = this.info?.name ?? "The agent";
728
+ // Kept to a readable length for the chip's tooltip (Task 10 round 2, 4).
729
+ const why = oneLine(message, ERROR_MAX) || "it stopped with an error";
730
+ this.turn = null;
731
+ this.ending = true;
732
+ const queued = this.queue;
733
+ this.queue = [];
734
+ this.milestone(`${name} couldn't finish: ${why}`);
735
+ this.announce();
736
+ let back = 0;
737
+ try {
738
+ const notes = await this.store.read("notes");
739
+ if (notes.notes.some((n) => this.leftOver(job, n))) {
740
+ const { result } = await this.store.update("notes", (f) => {
741
+ const left = f.notes.filter((n) => this.leftOver(job, n));
742
+ for (const n of left)
743
+ recallNote(f.notes, n.id, job.batchId);
744
+ return left.length;
745
+ });
746
+ back = result;
747
+ }
748
+ }
749
+ catch (e) {
750
+ console.error(`Rushes: couldn't read the notes after a turn: ${messageOf(e)}`);
751
+ }
752
+ await this.recall({
753
+ batches: queued.filter((j) => j.kind === "batch").map((j) => j.batchId),
754
+ notes: queued.flatMap((j) => (j.kind === "followUp" && j.note ? [{ id: j.note, batch: j.batchId }] : [])),
755
+ });
756
+ if (gen !== this.gen)
757
+ return;
758
+ if (back > 0)
759
+ this.addLine(back === 1 ? "1 note was not picked up and is back in to do" : `${back} notes were not picked up and are back in to do`, null);
760
+ this.ending = false;
761
+ // A Send accepted while this was being settled queued behind it: it runs now, as after any turn (round 2, 3).
762
+ if (this.queue.length)
763
+ return this.pump();
764
+ this.phase = "failed";
765
+ this.error = why;
766
+ this.current = { note: null, doing: null };
767
+ this.announce();
768
+ this.armIdle();
769
+ }
770
+ /** The prompt failed while the adapter stayed up (an RPC error): the run fails and the adapter is replaced. */
771
+ turnFailed(gen, conn, job, err) {
772
+ if (gen !== this.gen || this.turn?.job !== job)
773
+ return;
774
+ if (this.conn === conn)
775
+ this.dropConn();
776
+ const name = this.info?.name ?? "The agent";
777
+ this.track(this.failRun(`${name} could not finish ${job.label}: ${messageOf(err)}`));
778
+ }
779
+ onUpdate(conn, update) {
780
+ if (conn !== this.conn || this.closed)
781
+ return;
782
+ const text = this.adapters.get(conn)?.activity.line(update) ?? null;
783
+ if (!text)
784
+ return;
785
+ this.addLine(text, this.current.note);
786
+ this.announce();
787
+ }
788
+ onExit(conn, e) {
789
+ this.live.delete(conn);
790
+ this.exits.set(conn, e);
791
+ if (conn !== this.conn || this.closed)
792
+ return;
793
+ // A Stop is under way (an adapter may exit on session/cancel): halt() settles everything, and Stop is never a failure.
794
+ if (this.stopping)
795
+ return;
796
+ // While starting, the request in flight rejects and start() reports the failure with this stderr.
797
+ if (this.starting && !this.sessionId)
798
+ return;
799
+ this.conn = null;
800
+ this.sessionId = null;
801
+ this.clearIdle();
802
+ this.broker.cancelAll();
803
+ if (!this.turn)
804
+ return; // it went between turns; the next send starts a fresh one
805
+ const line = lastLine(e.stderr);
806
+ const name = this.info?.name ?? "The agent";
807
+ this.track(this.failRun(`${name} stopped unexpectedly${line ? `: ${line}` : ""}`));
808
+ }
809
+ /** The run failed: every job in flight or waiting gives its notes back. The state changes at once; the writes follow. */
810
+ failRun(why) {
811
+ const back = this.unfinished();
812
+ this.broker.cancelAll();
813
+ this.turn = null;
814
+ this.ending = false;
815
+ this.queue = [];
816
+ this.phase = "failed";
817
+ this.error = why;
818
+ this.current = { note: null, doing: null };
819
+ this.addLine(why, null);
820
+ this.announce();
821
+ return this.recall(back).then(async () => {
822
+ await this.writeMilestone(why);
823
+ });
824
+ }
825
+ /**
826
+ * Stop: cancels the turn, waits up to 5 s for it to end, kills the adapter and gives the unfinished notes
827
+ * of the current and queued batches back. With nothing running it changes nothing. Two at once share one.
828
+ */
829
+ stop() {
830
+ if (this.stopping)
831
+ return this.stopping;
832
+ if (!this.busy() || this.closed)
833
+ return Promise.resolve();
834
+ const p = this.halt().finally(() => {
835
+ if (this.stopping === p)
836
+ this.stopping = null;
837
+ });
838
+ this.stopping = p;
839
+ return p;
840
+ }
841
+ async halt() {
842
+ this.gen += 1;
843
+ this.clearIdle();
844
+ // First, and let the cancelled answers reach the adapter's stdin before session/cancel does.
845
+ if (this.broker.size > 0) {
846
+ this.broker.cancelAll();
847
+ await new Promise((r) => setImmediate(r));
848
+ }
849
+ const name = this.info?.name ?? "the agent";
850
+ const turn = this.turn;
851
+ // Batches and follow-ups in flight or queued are dropped, and give their notes back.
852
+ const back = this.unfinished();
853
+ this.queue = [];
854
+ const conn = this.conn;
855
+ const sessionId = this.sessionId;
856
+ if (turn && conn && sessionId && !conn.hasExited) {
857
+ conn.cancel(sessionId);
858
+ await within(turn.done, STOP_WAIT_MS);
859
+ }
860
+ // While starting, the adapter being started is `conn` too: killing it ends the start.
861
+ const dropped = this.dropConn();
862
+ if (dropped)
863
+ await exited(dropped);
864
+ if (this.starting)
865
+ await this.starting.catch(() => undefined);
866
+ this.turn = null;
867
+ this.ending = false;
868
+ await this.recall(back);
869
+ this.phase = "idle";
870
+ this.error = null;
871
+ this.current = { note: null, doing: null };
872
+ const text = `Stopped ${name}`;
873
+ this.addLine(text, null);
874
+ await this.writeMilestone(text);
875
+ this.announce();
876
+ }
877
+ /**
878
+ * rushes_working_on: the agent says which note it is on and what it is doing. Refused for a note that isn't
879
+ * with the agent (sent), as the store has it now. Shown only while a turn is in flight (M2): an agent the
880
+ * user pasted the prompt into, or a call after its turn, changes nothing.
881
+ */
882
+ async workingOn(note, doing) {
883
+ const file = await this.store.read("notes");
884
+ const n = file.notes.find((x) => x.id === note);
885
+ if (!n)
886
+ throw new NotFoundError("note", note);
887
+ if (noteState(n) !== "sent")
888
+ throw new RushesError(`Note "${note}" is not with the agent`, 409, "note_not_sent", { id: note });
889
+ if (!this.turn || this.closed)
890
+ return;
891
+ const text = oneLine(doing, ACTIVITY_LINE_MAX);
892
+ const line = text === "" || text === "…" ? "Working on a note" : text;
893
+ this.current = { note, doing: line };
894
+ this.addLine(line, note);
895
+ this.announce();
896
+ }
897
+ /**
898
+ * Server shutdown: cancels, kills the adapter and clears the timers. The notes of the batches and follow-ups in
899
+ * flight or queued go back to to do (I3), so none is left with an agent that is gone.
900
+ */
901
+ close() {
902
+ this.closing ??= this.shutdown();
903
+ return this.closing;
904
+ }
905
+ async shutdown() {
906
+ this.closed = true;
907
+ this.gen += 1;
908
+ this.store.off("change", this.onChange);
909
+ this.store.off("user-reply", this.onUserReply);
910
+ this.clearIdle();
911
+ this.broker.cancelAll();
912
+ const back = this.unfinished();
913
+ const conn = this.conn;
914
+ if (this.turn && conn && this.sessionId && !conn.hasExited)
915
+ conn.cancel(this.sessionId);
916
+ this.dropConn();
917
+ this.queue = [];
918
+ this.track(this.recall(back));
919
+ this.turn = null;
920
+ this.ending = false;
921
+ const all = [...this.live];
922
+ for (const c of all)
923
+ c.kill();
924
+ await Promise.all(all.map((c) => exited(c)));
925
+ if (this.starting)
926
+ await this.starting.catch(() => undefined);
927
+ if (this.stopping)
928
+ await this.stopping.catch(() => undefined);
929
+ while (this.pending.size)
930
+ await Promise.allSettled([...this.pending]);
931
+ }
932
+ armIdle() {
933
+ this.clearIdle();
934
+ if (!this.conn)
935
+ return;
936
+ this.idleTimer = setTimeout(() => {
937
+ this.idleTimer = null;
938
+ // A send that came in meanwhile keeps the adapter; the session stays in agent.json either way.
939
+ if (this.busy() || this.closed)
940
+ return;
941
+ this.dropConn();
942
+ }, this.idleMs);
943
+ this.idleTimer.unref();
944
+ }
945
+ clearIdle() {
946
+ if (this.idleTimer)
947
+ clearTimeout(this.idleTimer);
948
+ this.idleTimer = null;
949
+ }
950
+ /** Reads agent.json into the cache, announcing when what the status shows from it changed. */
951
+ async loadSettings() {
952
+ const seq = ++this.reads;
953
+ const next = await this.store.read("agent");
954
+ // Reads can finish out of order: an older one never replaces what a newer one (or a write) put in.
955
+ if (seq < this.applied)
956
+ return next;
957
+ this.applySettings(next, seq);
958
+ return next;
959
+ }
960
+ /** Reads the user's rules into the cache, announcing when they changed. */
961
+ async loadRules() {
962
+ const seq = ++this.ruleReads;
963
+ const next = await this.rulesFile.read();
964
+ // As with agent.json: an older read never replaces what a newer one (or a write) put in.
965
+ if (seq >= this.rulesApplied)
966
+ this.applyRules(next, seq);
967
+ return next;
968
+ }
969
+ applyRules(next, seq = ++this.ruleReads) {
970
+ const changed = JSON.stringify(next) !== JSON.stringify(this.rules);
971
+ this.rules = next;
972
+ this.rulesApplied = seq;
973
+ if (changed)
974
+ this.announce();
975
+ }
976
+ applySettings(next, seq = ++this.reads) {
977
+ const key = (s) => JSON.stringify(s ? [s.on, s.agent, s.session?.id ?? null] : null);
978
+ const changed = key(next) !== key(this.settings);
979
+ this.settings = next;
980
+ this.applied = seq;
981
+ if (changed)
982
+ this.announce();
983
+ }
984
+ /**
985
+ * What goes back on Stop or failure, from the jobs in flight and queued: a batch's unfinished notes, and a
986
+ * follow-up's own note (not the rest of its batch, whose turn has already ended).
987
+ */
988
+ unfinished() {
989
+ const jobs = [...(this.turn ? [this.turn.job] : []), ...this.queue];
990
+ return {
991
+ batches: jobs.filter((j) => j.kind === "batch").map((j) => j.batchId),
992
+ notes: jobs.flatMap((j) => (j.kind === "followUp" && j.note ? [{ id: j.note, batch: j.batchId }] : [])),
993
+ };
994
+ }
995
+ recall(back) {
996
+ if (!back.batches.length && !back.notes.length)
997
+ return Promise.resolve();
998
+ return this.store
999
+ .update("notes", (f) => {
1000
+ recallNotes(f.notes, back.batches);
1001
+ // Only while the note is still in the batch the follow-up was for.
1002
+ for (const n of back.notes)
1003
+ recallNote(f.notes, n.id, n.batch);
1004
+ })
1005
+ .then(() => undefined, (e) => console.error(`Rushes: couldn't give back the notes of ${[...back.batches, ...back.notes.map((n) => n.id)].join(", ")}: ${messageOf(e)}`));
1006
+ }
1007
+ /** An Activity line and a Change Log line, for a run starting, finishing, stopping or failing. */
1008
+ milestone(text) {
1009
+ this.addLine(text, null);
1010
+ this.track(this.writeMilestone(text));
1011
+ }
1012
+ writeMilestone(text) {
1013
+ // LogBook.add never throws: a line it can't write is reported and counted.
1014
+ return logBookFor(this.store).add(lineEvent(text, "notes"), "rushes", this.now());
1015
+ }
1016
+ addLine(text, note) {
1017
+ this.lines.push({ at: this.now().toISOString(), text, note });
1018
+ if (this.lines.length > AGENT_LINES_KEPT)
1019
+ this.lines.splice(0, this.lines.length - AGENT_LINES_KEPT);
1020
+ }
1021
+ announce() {
1022
+ if (this.closed)
1023
+ return;
1024
+ this.store.emit("agent", this.status());
1025
+ }
1026
+ track(p) {
1027
+ const tracked = p.catch((e) => console.error(`Rushes: the agent runner hit an error: ${messageOf(e)}`));
1028
+ this.pending.add(tracked);
1029
+ void tracked.finally(() => this.pending.delete(tracked));
1030
+ }
1031
+ }