@operad-io/chat 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/reply.ts CHANGED
@@ -7,16 +7,39 @@
7
7
 
8
8
  import { mkdir, writeFile } from "node:fs/promises";
9
9
  import { dirname, join } from "node:path";
10
- import { AskTimeoutError, attachmentDir, isRecord, messageOf, safeFileName, type AskOutcome, type AskRequest, type JsonValue, type PluginStepResult, type RunObject, type StepAsker, type StepContext } from "@operad-io/engine";
11
- import { emptyFold, foldLines, maskSecrets, type FoldEntry, type FoldState } from "@operad-io/harness-process";
10
+ import { AskTimeoutError, attachmentDir, isRecord, messageOf, modelIds, safeFileName, type AskOutcome, type AskRecheck, type AskRequest, type ChoiceInfo, type CostQuality, type JsonValue, type PluginStepResult, type RunObject, type StepAsker, type StepContext, type UsageTokens } from "@operad-io/engine";
11
+ import { isAccessLevel, match, MCP_TOOL, withAccessLevel, writeLiveAccess, type AccessLevel } from "@operad-io/access-match";
12
12
  import {
13
- allEntries,
14
- allMessages,
13
+ appendAlwaysAllow,
14
+ alwaysAllowEntry,
15
+ emptyFold,
16
+ foldLines,
17
+ maskSecrets,
18
+ personStarted,
19
+ readAlwaysAllow,
20
+ type AlwaysAllowEntry,
21
+ type FoldEntry,
22
+ type FoldState,
23
+ type MessageInbox,
24
+ } from "@operad-io/harness-process";
25
+ import { readSkills, skillMessage } from "./skills.ts";
26
+ import {
27
+ ACCESS_FACT,
28
+ ACCESS_LEVEL_INFO,
29
+ accessLevelPath,
30
+ ANSWER_FACT,
31
+ answeredOfFact,
32
+ attachmentsOf,
33
+ ATTEMPT_END_FACT,
34
+ attemptEndedOfFact,
15
35
  chatFacts,
16
36
  IMAGE_TYPES,
17
37
  chatData,
38
+ chosenEffort,
18
39
  type ChatData,
19
- type CostQuality,
40
+ type ChatNoteHashes,
41
+ type ChatRead,
42
+ type Entry,
20
43
  chatRef,
21
44
  currentSession,
22
45
  ENTRY_FACT,
@@ -25,37 +48,70 @@ import {
25
48
  RUN_FACT,
26
49
  newMessageId,
27
50
  promptFor,
51
+ readChat,
52
+ replyContextOf,
53
+ takenIds,
28
54
  unanswered,
29
55
  usageOf,
30
56
  worseQuality,
57
+ timingsOf,
31
58
  CHAT_TYPE,
32
59
  type EntryData,
33
60
  type Message,
34
61
  type MessageData,
35
62
  } from "./model.ts";
63
+ import { noteBlock, noteFilesOf, noteHashesAfter, notesToAttach, notesWrittenHere, readNoteFiles, type NoteFile } from "./notes.ts";
64
+ import { queueTestHooks, syncQueuedLocked, takeLocked, withQueueLock } from "./queue.ts";
65
+ import { agentLogPath, foldLogTail } from "./tail.ts";
36
66
 
37
67
  /**
38
68
  * Brings the chat object in line with its facts: the session after a reply, and
39
69
  * the model and the cost so far, summed from the replies recorded. Reading the
40
70
  * facts, not adding to the object, makes a rerun after a crash end in the same state.
41
71
  */
42
- async function syncChat(ctx: StepContext, id: string, session: string | undefined): Promise<void> {
72
+ async function syncChat(
73
+ ctx: StepContext,
74
+ id: string,
75
+ session: string | undefined,
76
+ contextCwd?: string | undefined,
77
+ noteHashes?: ChatNoteHashes | undefined,
78
+ ): Promise<void> {
43
79
  const fresh = await ctx.store.get(CHAT_TYPE, id);
44
80
  if (fresh === undefined) return;
45
81
  const next: Record<string, unknown> = { ...fresh.data };
46
82
  if (session !== undefined) next.session = session;
83
+ if (contextCwd !== undefined) next.contextCwd = contextCwd;
84
+ if (noteHashes !== undefined) next.noteHashes = noteHashes;
47
85
  let micros: number | undefined;
48
86
  let quality: CostQuality | undefined;
49
- for (const message of allMessages(ctx.store, id)) {
87
+ let costMissing = false;
88
+ let tokens: UsageTokens | undefined;
89
+ let tokensMissing = false;
90
+ for (const message of readChat(ctx.store, id).messages) {
50
91
  if (message.role !== "assistant") continue;
51
92
  if (message.model !== undefined) next.lastModel = message.model;
52
- if (message.costMicros !== undefined) {
93
+ if (message.costMicros === undefined) costMissing = true;
94
+ else {
53
95
  micros = (micros ?? 0) + message.costMicros;
54
96
  quality = worseQuality(quality, message.costQuality);
55
97
  }
98
+ if (message.tokens === undefined) tokensMissing = true;
99
+ else {
100
+ tokens = {
101
+ input: (tokens?.input ?? 0) + message.tokens.input,
102
+ output: (tokens?.output ?? 0) + message.tokens.output,
103
+ cacheread: (tokens?.cacheread ?? 0) + message.tokens.cacheread,
104
+ cachewrite: (tokens?.cachewrite ?? 0) + message.tokens.cachewrite,
105
+ };
106
+ }
56
107
  }
57
- if (micros !== undefined) next.costMicros = micros;
58
- if (quality !== undefined) next.costQuality = quality;
108
+ if (micros !== undefined) {
109
+ next.costMicros = micros;
110
+ next.costQuality = costMissing ? worseQuality(quality, "incomplete") : quality;
111
+ }
112
+ if (tokens !== undefined) next.tokens = tokens;
113
+ if (tokens !== undefined && tokensMissing) next.tokensIncomplete = true;
114
+ else if (tokens !== undefined) delete next.tokensIncomplete;
59
115
  if (JSON.stringify(next) !== JSON.stringify(fresh.data)) {
60
116
  await ctx.store.put(CHAT_TYPE, id, next, "step:chat/reply");
61
117
  }
@@ -76,12 +132,79 @@ export const WORKTREE_CALL_LIMIT = 120;
76
132
  export const READ_ONLY_REFUSAL =
77
133
  "The call was refused because this chat is read-only. Answer in the chat or use read-only commands.";
78
134
 
79
- /** The answers to the worktree question. */
80
- export const WORKTREE_CHOICES = ["yes", "no"] as const;
135
+ /** The answers to the worktree question: the permission words, then the worktree offer. */
136
+ export const WORKTREE_ALLOW_ONCE = "Allow once";
137
+ export const WORKTREE_ALLOW_ALWAYS = "Always allow";
138
+ export const WORKTREE_DENY = "Deny";
139
+ export const WORKTREE_YES = "Open a worktree";
140
+ export const WORKTREE_CHOICES = [WORKTREE_ALLOW_ONCE, WORKTREE_ALLOW_ALWAYS, WORKTREE_DENY, WORKTREE_YES] as const;
141
+
142
+ /** What each worktree answer is, keyed by the words an answer sends. */
143
+ const WORKTREE_CHOICE_INFO: Readonly<Record<string, ChoiceInfo>> = {
144
+ [WORKTREE_ALLOW_ONCE]: {
145
+ label: WORKTREE_ALLOW_ONCE,
146
+ hint: "Run this call once in the main clone.",
147
+ role: "primary",
148
+ },
149
+ [WORKTREE_ALLOW_ALWAYS]: {
150
+ label: WORKTREE_ALLOW_ALWAYS,
151
+ hint: "Allow this exact call in every chat.",
152
+ },
153
+ [WORKTREE_DENY]: {
154
+ label: WORKTREE_DENY,
155
+ hint: "Refuse this call.",
156
+ },
157
+ [WORKTREE_YES]: {
158
+ label: WORKTREE_YES,
159
+ hint: "Move this chat to a writable worktree.",
160
+ },
161
+ };
162
+
163
+ /** The worktree question's information for just the choices it offers here. */
164
+ export function worktreeChoiceInfo(
165
+ choices: readonly string[] = WORKTREE_CHOICES,
166
+ ): Readonly<Record<string, ChoiceInfo>> {
167
+ const info: Record<string, ChoiceInfo> = {};
168
+ for (const choice of choices) {
169
+ const entry = WORKTREE_CHOICE_INFO[choice];
170
+ if (entry !== undefined) info[choice] = entry;
171
+ }
172
+ return info;
173
+ }
174
+
175
+ type WorktreeAnswer = "allow_once" | "allow_always" | "deny" | "worktree";
176
+
177
+ /** The action a worktree answer asks for; the older yes/no and the internal names still answer. */
178
+ function worktreeAnswer(choice: string | undefined): WorktreeAnswer {
179
+ switch (choice) {
180
+ case WORKTREE_ALLOW_ONCE:
181
+ case "allow_once":
182
+ return "allow_once";
183
+ case WORKTREE_ALLOW_ALWAYS:
184
+ case "allow_always":
185
+ return "allow_always";
186
+ case WORKTREE_YES:
187
+ case "yes":
188
+ return "worktree";
189
+ default:
190
+ return "deny";
191
+ }
192
+ }
81
193
 
82
194
  /** The event a "yes" sends; the plugin that owns the working directory acts on it. */
83
195
  export const WORKTREE_EVENT = "chat.worktree";
84
196
 
197
+ /** The event dev sends after opening a worktree, so the chat answers the same message there. */
198
+ export const WORKTREE_REPLY_EVENT = "dev.chat_reply";
199
+
200
+ /** Ends the asking reply when a person chooses the worktree; the caller opens it and starts the next reply. */
201
+ class WorktreeChosen extends Error {
202
+ constructor() {
203
+ super("the chat now works in a worktree");
204
+ this.name = "WorktreeChosen";
205
+ }
206
+ }
207
+
85
208
  /** The call a harness question asks about. */
86
209
  export interface WorktreeCall {
87
210
  readonly kind: "command" | "path";
@@ -89,18 +212,22 @@ export interface WorktreeCall {
89
212
  readonly tool?: string;
90
213
  }
91
214
 
215
+ /** One worktree call record, wherever it is written: its kind, value and tool. */
216
+ function callOf(record: unknown): WorktreeCall | undefined {
217
+ if (!isRecord(record)) return undefined;
218
+ const kind = record.kind;
219
+ const value = record.value;
220
+ const tool = record.tool;
221
+ if ((kind !== "command" && kind !== "path") || typeof value !== "string" || value.length === 0) return undefined;
222
+ return { kind, value, ...(typeof tool === "string" ? { tool } : {}) };
223
+ }
224
+
92
225
  /** The call behind a write question: its grant, or the words of a question with no session. */
93
226
  function worktreeCall(request: AskRequest): WorktreeCall | undefined {
94
227
  const resume = request.resume;
95
228
  if (isRecord(resume) && isRecord(resume.grant)) {
96
- const grant = resume.grant;
97
- if ((grant.kind === "command" || grant.kind === "path") && typeof grant.value === "string" && grant.value.length > 0) {
98
- return {
99
- kind: grant.kind,
100
- value: grant.value,
101
- ...(typeof grant.tool === "string" ? { tool: grant.tool } : {}),
102
- };
103
- }
229
+ const grant = callOf(resume.grant);
230
+ if (grant !== undefined) return grant;
104
231
  }
105
232
  const command = /^Run this command\? ([\s\S]+)$/.exec(request.prompt);
106
233
  if (command?.[1] !== undefined && command[1].trim().length > 0) {
@@ -151,17 +278,79 @@ function worktreeResume(request: AskRequest, call: WorktreeCall | undefined): Js
151
278
  value: call.value,
152
279
  ...(call.tool === undefined ? {} : { tool: call.tool }),
153
280
  },
281
+ // Either permission answer gives the late call its one-time permission.
282
+ ...(session === null
283
+ ? {}
284
+ : {
285
+ grant: {
286
+ kind: call.kind,
287
+ value: call.value,
288
+ choice: WORKTREE_ALLOW_ONCE,
289
+ choices: [WORKTREE_ALLOW_ONCE, WORKTREE_ALLOW_ALWAYS],
290
+ ...(call.kind === "path" && call.tool !== undefined ? { tool: call.tool } : {}),
291
+ },
292
+ }),
154
293
  }),
155
294
  };
156
295
  }
157
296
 
297
+ /** Whether a user-layer entry covers this exact call and working directory. */
298
+ function remembered(entry: AlwaysAllowEntry, call: WorktreeCall, cwd: string): boolean {
299
+ return (
300
+ entry.cwd === cwd &&
301
+ entry.kind === call.kind &&
302
+ entry.value === call.value &&
303
+ (call.kind === "command" || entry.tool === call.tool)
304
+ );
305
+ }
306
+
307
+ /** Reads the user layer, logging a file that had to be treated as empty. */
308
+ async function userLayer(ctx: StepContext): Promise<readonly AlwaysAllowEntry[]> {
309
+ const found = await readAlwaysAllow(ctx.home);
310
+ if (found.problem !== undefined) await ctx.logger.write(found.problem);
311
+ return found.entries;
312
+ }
313
+
314
+ /** Writes an `Always allow` answer to the user layer; a failure still lets this call run. */
315
+ async function rememberAlways(ctx: StepContext, call: WorktreeCall, cwd: string): Promise<void> {
316
+ try {
317
+ await appendAlwaysAllow(ctx.home, alwaysAllowEntry(call, cwd));
318
+ } catch (error) {
319
+ await ctx.logger.write(
320
+ `Always allow could not be written to the user access file: ${messageOf(error)}; this call runs once`,
321
+ );
322
+ }
323
+ }
324
+
325
+ /** The full call from the grants a late answer brings, when the kernel made one. */
326
+ function callFromGrants(access: JsonValue): WorktreeCall | undefined {
327
+ if (!isRecord(access) || !Array.isArray(access["grants"])) return undefined;
328
+ for (const value of access["grants"]) {
329
+ const call = callOf(value);
330
+ if (call !== undefined) return call;
331
+ }
332
+ return undefined;
333
+ }
334
+
335
+ /** The call a late answer names in the worktree question, when no grant carries it. */
336
+ function callFromQuestion(prompt: string): WorktreeCall | undefined {
337
+ const command = /^The agent wants to run `([\s\S]+)` in this read-only chat\. Open a worktree for it\?$/.exec(prompt);
338
+ if (command?.[1] !== undefined && command[1].length > 0) return { kind: "command", value: command[1] };
339
+ const path = /^The agent wants to (write|edit) `([\s\S]+)` in this read-only chat\. Open a worktree for it\?$/.exec(prompt);
340
+ if (path?.[1] !== undefined && path[2] !== undefined && path[2].length > 0) {
341
+ return { kind: "path", value: path[2], tool: path[1] };
342
+ }
343
+ return undefined;
344
+ }
345
+
158
346
  /**
159
347
  * Whether a harness question is about a call in the working directory: a
160
- * path write or edit, or a shell command. A read-only chat lets no such call
161
- * through on a one-time permission (the profile already let the read-only ones
162
- * run), so each becomes the worktree question.
348
+ * path write or edit, or a shell command. A read-only chat asks the worktree
349
+ * question for each, with the permission answers and the worktree offer.
163
350
  */
164
351
  export function isWriteQuestion(request: AskRequest): boolean {
352
+ // A form is a question about the agent's own choice, never about one call.
353
+ if (request.questions !== undefined && request.questions.length > 0) return false;
165
354
  const resume = request.resume;
166
355
  if (isRecord(resume) && isRecord(resume.grant)) {
167
356
  const grant = resume.grant;
@@ -176,38 +365,77 @@ function failed(reason: string, message: string): PluginStepResult {
176
365
  return { result: "failed", data: { reason, message } };
177
366
  }
178
367
 
368
+ /** The call a question names in its own resume, when it carries one. */
369
+ function resumeCall(resume: unknown): WorktreeCall | undefined {
370
+ return isRecord(resume) ? callOf(resume.call) : undefined;
371
+ }
372
+
373
+ /** The call a question is about, from its grant, its resume or its own words. */
374
+ function questionedCall(request: AskRequest): WorktreeCall | undefined {
375
+ // A form carries no call: its questions are the agent's, not the profile's.
376
+ if (request.questions !== undefined && request.questions.length > 0) return undefined;
377
+ return worktreeCall(request) ?? resumeCall(request.resume) ?? callFromQuestion(request.prompt);
378
+ }
379
+
380
+ /** One call in the words `access-match` takes. */
381
+ function matcherCall(call: WorktreeCall): { readonly tool: string; readonly input: Record<string, unknown> } {
382
+ if (call.kind === "command") {
383
+ if (call.value.startsWith("mcp ")) {
384
+ const rest = call.value.slice("mcp ".length);
385
+ const at = rest.indexOf(".");
386
+ if (at > 0 && at + 1 < rest.length) {
387
+ return { tool: MCP_TOOL, input: { server: rest.slice(0, at), tool: rest.slice(at + 1) } };
388
+ }
389
+ }
390
+ return { tool: "bash", input: { command: call.value } };
391
+ }
392
+ return { tool: call.tool ?? "write", input: { path: call.value } };
393
+ }
394
+
395
+ /** Who changed the chat's level to `level`, from the latest access fact that did. */
396
+ function levelActor(ctx: StepContext, chat: string, level: AccessLevel): { readonly via: string; readonly id: string } | undefined {
397
+ const fact = [...readChat(ctx.store, chat).facts].reverse().find((item) => item.type === ACCESS_FACT && item.data.to === level);
398
+ const by = fact !== undefined && isRecord(fact.data.by) ? fact.data.by : undefined;
399
+ if (by === undefined || typeof by.via !== "string" || typeof by.id !== "string") return undefined;
400
+ return { via: by.via, id: by.id };
401
+ }
402
+
179
403
  /**
180
- * The asker a read-only chat's harness gets: a question about writing a file
181
- * becomes the worktree question and never a one-time permission; any other
182
- * question goes where it would have gone.
404
+ * The check a chat's question runs again while it waits. A question about one
405
+ * call is lifted only when the level changed and the new level would not ask
406
+ * that call; a question that is not about a call, or whose ask comes from the
407
+ * profile rather than the level, stays open.
183
408
  */
184
- function readOnlyAsker(ctx: StepContext, onYes: () => Promise<void>): StepAsker {
409
+ function levelRecheck(
410
+ ctx: StepContext,
411
+ chatId: string,
412
+ cwd: string,
413
+ base: () => Readonly<Record<string, JsonValue>>,
414
+ openedLevel: AccessLevel,
415
+ request: AskRequest,
416
+ ): (() => Promise<AskRecheck>) | undefined {
417
+ const call = questionedCall(request);
418
+ if (call === undefined) return undefined;
419
+ const judged = matcherCall(call);
420
+ return async () => {
421
+ const stored = await ctx.store.get(CHAT_TYPE, chatId);
422
+ if (stored === undefined) return { ask: true };
423
+ const chat = chatData(stored.data);
424
+ const level = chat.accessLevel ?? "ask";
425
+ if (level === openedLevel) return { ask: true };
426
+ const verdict = match(withAccessLevel(base(), level), { ...judged, cwd });
427
+ if (!verdict.allow) return { ask: true };
428
+ const actor = levelActor(ctx, chatId, level);
429
+ return { ask: false, note: ACCESS_LEVEL_INFO[level].title, ...(actor === undefined ? {} : { actor }) };
430
+ };
431
+ }
432
+
433
+ /** The chat step's own `ctx.ask`, in the shape the harness's asker takes. */
434
+ function contextAsker(ctx: StepContext): StepAsker {
185
435
  return {
186
436
  async ask(request): Promise<AskOutcome> {
187
- const write = isWriteQuestion(request);
188
- const call = write ? worktreeCall(request) : undefined;
189
- const shaped: AskRequest = write
190
- ? {
191
- prompt: call === undefined ? WORKTREE_QUESTION : worktreeQuestion(call),
192
- choices: [...WORKTREE_CHOICES],
193
- ...(request.resume === undefined ? {} : { resume: worktreeResume(request, call) }),
194
- ...(request.onTimeout === undefined ? {} : { onTimeout: request.onTimeout }),
195
- ...(request.graceSecs === undefined ? {} : { graceSecs: request.graceSecs }),
196
- }
197
- : request;
198
437
  try {
199
- const answer = await ctx.ask(shaped);
200
- if (shaped === request) return { kind: "answered", answer };
201
- if (answer.choice === "yes") await onYes();
202
- // The call itself is never let through in the main clone. A no says why.
203
- return {
204
- kind: "answered",
205
- answer: {
206
- choice: "reject_once",
207
- ...(answer.choice === "yes" ? {} : { note: READ_ONLY_REFUSAL }),
208
- ...(answer.actor === undefined ? {} : { actor: answer.actor }),
209
- },
210
- };
438
+ return { kind: "answered", answer: await ctx.ask(request) };
211
439
  } catch (error) {
212
440
  if (error instanceof AskTimeoutError) {
213
441
  return {
@@ -215,6 +443,9 @@ function readOnlyAsker(ctx: StepContext, onYes: () => Promise<void>): StepAsker
215
443
  waitId: error.waitId,
216
444
  prompt: error.prompt,
217
445
  choices: error.choices,
446
+ ...(error.choiceInfo === undefined ? {} : { choiceInfo: error.choiceInfo }),
447
+ ...(error.questions === undefined ? {} : { questions: error.questions }),
448
+ ...(error.resume === undefined || error.resume === null ? {} : { resume: error.resume as JsonValue }),
218
449
  };
219
450
  }
220
451
  throw error;
@@ -224,6 +455,118 @@ function readOnlyAsker(ctx: StepContext, onYes: () => Promise<void>): StepAsker
224
455
  };
225
456
  }
226
457
 
458
+ /** An asker that adds the level recheck to every question about one call. */
459
+ function levelAsker(
460
+ ctx: StepContext,
461
+ chatId: string,
462
+ cwd: string,
463
+ base: () => Readonly<Record<string, JsonValue>>,
464
+ initialLevel: AccessLevel,
465
+ inner: StepAsker,
466
+ ): StepAsker {
467
+ return {
468
+ async ask(request, signal): Promise<AskOutcome> {
469
+ if (request.recheck !== undefined) return inner.ask(request, signal);
470
+ // The question may be opened after the reply started, under a level the
471
+ // owner set meanwhile; changing back to the reply's start level is still
472
+ // a change that may lift this question.
473
+ const stored = await ctx.store.get(CHAT_TYPE, chatId);
474
+ const openedLevel = stored === undefined ? initialLevel : chatData(stored.data).accessLevel ?? "ask";
475
+ const recheck = levelRecheck(ctx, chatId, cwd, base, openedLevel, request);
476
+ return inner.ask(recheck === undefined ? request : { ...request, recheck }, signal);
477
+ },
478
+ useGrant: (waitId) => inner.useGrant(waitId),
479
+ };
480
+ }
481
+
482
+ /** Whether the chat's working directory is no longer `cwd`, the one this reply started in. */
483
+ async function movedFrom(ctx: StepContext, chatId: string, cwd: string): Promise<boolean> {
484
+ const stored = await ctx.store.get(CHAT_TYPE, chatId);
485
+ return stored !== undefined && chatData(stored.data).cwd !== cwd;
486
+ }
487
+
488
+ /**
489
+ * The asker a read-only chat's harness gets: a question about writing a file
490
+ * becomes the worktree question, which may let this call run once, remember it
491
+ * with Always allow, refuse it, or open a worktree; any other question goes
492
+ * where it would have gone.
493
+ *
494
+ * Choosing the worktree stops the harness at once through `stop`, even when it
495
+ * swallows the thrown stop: the reply that asked has ended (ADR 0028 D3).
496
+ */
497
+ function readOnlyAsker(
498
+ ctx: StepContext,
499
+ chatId: string,
500
+ cwd: string,
501
+ chosen: { run: boolean; readonly stop: AbortController },
502
+ inner: StepAsker,
503
+ ): StepAsker {
504
+ const person = personStarted(ctx.trigger);
505
+ return {
506
+ async ask(request): Promise<AskOutcome> {
507
+ if (chosen.run) throw new WorktreeChosen();
508
+ // The chat moved to its worktree while this reply ran, so what this
509
+ // reply asks is judged by the main clone's profile and its directory.
510
+ // The reply ends and is answered again in the worktree.
511
+ if (await movedFrom(ctx, chatId, cwd)) {
512
+ chosen.run = true;
513
+ chosen.stop.abort();
514
+ throw new WorktreeChosen();
515
+ }
516
+ const write = isWriteQuestion(request);
517
+ const call = write ? worktreeCall(request) : undefined;
518
+ // An entry from an earlier Always allow lifts the question in any chat a person started.
519
+ if (person && call !== undefined && (await userLayer(ctx)).some((entry) => remembered(entry, call, cwd))) {
520
+ return { kind: "answered", answer: { choice: "allow_once" } };
521
+ }
522
+ const choices = person
523
+ ? [...WORKTREE_CHOICES]
524
+ : [WORKTREE_ALLOW_ONCE, WORKTREE_DENY, WORKTREE_YES];
525
+ const shaped: AskRequest = write
526
+ ? {
527
+ prompt: call === undefined ? WORKTREE_QUESTION : worktreeQuestion(call),
528
+ choices,
529
+ choiceInfo: worktreeChoiceInfo(choices),
530
+ ...(request.resume === undefined ? {} : { resume: worktreeResume(request, call) }),
531
+ ...(request.onTimeout === undefined ? {} : { onTimeout: request.onTimeout }),
532
+ ...(request.graceSecs === undefined ? {} : { graceSecs: request.graceSecs }),
533
+ }
534
+ : request;
535
+ // A question open when the chat moves to its worktree ends with the reply.
536
+ const outcome = await Promise.race([
537
+ inner.ask(shaped),
538
+ new Promise<never>((_resolve, reject) => {
539
+ const end = (): void => reject(new WorktreeChosen());
540
+ if (chosen.stop.signal.aborted) end();
541
+ else chosen.stop.signal.addEventListener("abort", end, { once: true });
542
+ }),
543
+ ]);
544
+ if (outcome.kind === "timeout") return outcome;
545
+ const answer = outcome.answer;
546
+ if (shaped === request) return outcome;
547
+ const action = worktreeAnswer(answer.choice);
548
+ const actor = answer.actor === undefined ? {} : { actor: answer.actor };
549
+ if (action === "allow_once") {
550
+ return { kind: "answered", answer: { choice: "allow_once", ...actor } };
551
+ }
552
+ if (action === "allow_always" && person) {
553
+ if (call !== undefined) await rememberAlways(ctx, call, cwd);
554
+ return { kind: "answered", answer: { choice: "allow_always", ...actor } };
555
+ }
556
+ if (action === "worktree") {
557
+ // Opening a worktree keeps this call out of the main clone. The reply
558
+ // ends here; the worktree flow starts the answer again there.
559
+ chosen.run = true;
560
+ chosen.stop.abort();
561
+ throw new WorktreeChosen();
562
+ }
563
+ // Deny refuses as no did, and says why.
564
+ return { kind: "answered", answer: { choice: "reject_once", note: READ_ONLY_REFUSAL, ...actor } };
565
+ },
566
+ useGrant: (waitId) => inner.useGrant(waitId),
567
+ };
568
+ }
569
+
227
570
  /** What a late answer needs: the session, and no permission for the call. */
228
571
  function sessionOnly(resume: unknown): { readonly session: string } | null {
229
572
  if (isRecord(resume) && typeof resume.session === "string") {
@@ -273,6 +616,12 @@ export function imagesOf(pending: readonly Message[], harness: string, directory
273
616
  return images;
274
617
  }
275
618
 
619
+ /** The text a chat's first session starts with: the whole text, and its place alone. */
620
+ interface SessionContext {
621
+ readonly text: string;
622
+ readonly where: string;
623
+ }
624
+
276
625
  /** What a chat's `refresh` step gives back. */
277
626
  interface Live {
278
627
  readonly cwd: string;
@@ -280,6 +629,42 @@ interface Live {
280
629
  readonly skills: readonly string[];
281
630
  /** Servers the harness starts for the agent, by name, each as a command. */
282
631
  readonly mcpServers: Readonly<Record<string, JsonValue>>;
632
+ /** Whether the agent reads the owner's own configuration of that agent. */
633
+ readonly useOwnSettings: boolean;
634
+ /** A repository chat's starting text; a bot chat gives none. */
635
+ readonly context?: SessionContext | undefined;
636
+ /** Files put on the message as notes; a bot gives its memory index and instructions. */
637
+ readonly notes?: readonly NoteFile[] | undefined;
638
+ /** The level a chat that chose none starts at now; a bot gives its setting. */
639
+ readonly accessDefault?: AccessLevel | undefined;
640
+ /** False when the chat works in its main clone and no worktree is to be offered. */
641
+ readonly worktreeOffer?: boolean | undefined;
642
+ /** A plugin step to call after the round ends, when the chat's refresh step names one. */
643
+ readonly after?: string | undefined;
644
+ }
645
+
646
+ function sessionContextOf(value: unknown): SessionContext | undefined {
647
+ if (!isRecord(value) || typeof value.text !== "string" || typeof value.where !== "string") return undefined;
648
+ return { text: value.text, where: value.where };
649
+ }
650
+
651
+ /** The text to put before this round's prompt: the whole text for a new session, its place after a move. */
652
+ function contextFor(chat: ChatData, live: Live, session: string | undefined): string | undefined {
653
+ if (live.context === undefined) return undefined;
654
+ if (session === undefined) return live.context.text;
655
+ if (chat.contextCwd !== undefined && chat.contextCwd !== live.cwd) return live.context.where;
656
+ return undefined;
657
+ }
658
+
659
+ /** The context the last reply of this session ended with, when it reported one. */
660
+ function lastContextUsed(messages: readonly Message[], session: string | undefined): number | undefined {
661
+ if (session === undefined) return undefined;
662
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
663
+ const message = messages[index];
664
+ if (message?.role !== "assistant" || message.context === undefined) continue;
665
+ return message.session === session ? message.context.used : undefined;
666
+ }
667
+ return undefined;
283
668
  }
284
669
 
285
670
  /**
@@ -293,7 +678,13 @@ async function liveSettings(
293
678
  object: RunObject,
294
679
  runStep: NonNullable<StepContext["runStep"]>,
295
680
  ): Promise<Live | PluginStepResult> {
296
- const own: Live = { cwd: chat.cwd, access: chat.access, skills: chat.skills, mcpServers: {} };
681
+ const own: Live = {
682
+ cwd: chat.cwd,
683
+ access: chat.access,
684
+ skills: chat.skills,
685
+ mcpServers: {},
686
+ useOwnSettings: false,
687
+ };
297
688
  if (chat.refresh === undefined) return own;
298
689
  if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(chat.refresh)) {
299
690
  return failed("settings", `"${chat.refresh}", which gives this chat's settings, is not loaded`);
@@ -311,11 +702,21 @@ async function liveSettings(
311
702
  if (typeof data.cwd !== "string" || data.cwd.length === 0 || !isRecord(data.access) || !Array.isArray(data.skills)) {
312
703
  return failed("settings", "the chat's settings came back in a shape the chat cannot use");
313
704
  }
705
+ const context = sessionContextOf(data.context);
706
+ const notes = noteFilesOf(data.notes);
707
+ const after = typeof data.after === "string" && data.after.length > 0 ? data.after : undefined;
708
+ const accessDefault = isAccessLevel(data.accessDefault) ? data.accessDefault : undefined;
314
709
  return {
710
+ ...(accessDefault === undefined ? {} : { accessDefault }),
711
+ ...(data.worktreeOffer === false ? { worktreeOffer: false } : {}),
315
712
  cwd: data.cwd,
316
713
  access: data.access as Record<string, JsonValue>,
317
714
  skills: data.skills.filter((item): item is string => typeof item === "string"),
318
715
  mcpServers: isRecord(data.mcpServers) ? (data.mcpServers as Record<string, JsonValue>) : {},
716
+ useOwnSettings: data.useOwnSettings === true,
717
+ ...(context === undefined ? {} : { context }),
718
+ ...(notes === undefined ? {} : { notes }),
719
+ ...(after === undefined ? {} : { after }),
319
720
  };
320
721
  }
321
722
 
@@ -332,9 +733,27 @@ export function withAttachmentReads(
332
733
  return { ...access, readPaths: [...own, directory] };
333
734
  }
334
735
 
736
+ /**
737
+ * The profile with the chat's own directory denied: its live-level file is
738
+ * written by `chat:access`, never by the agent, at any level.
739
+ */
740
+ export function withLevelFileDeny(
741
+ access: Readonly<Record<string, JsonValue>>,
742
+ levelPath: string,
743
+ ): Readonly<Record<string, JsonValue>> {
744
+ const directory = dirname(levelPath);
745
+ const denied = Array.isArray(access.denyPaths)
746
+ ? access.denyPaths.filter((entry): entry is string => typeof entry === "string")
747
+ : [];
748
+ return denied.includes(directory) ? access : { ...access, denyPaths: [...denied, directory] };
749
+ }
750
+
335
751
  /** How much of a tool call's output a fact keeps; the rest goes to a file. */
336
752
  export const TOOL_OUTPUT_FACT_BYTES = 4 * 1024;
337
753
 
754
+ /** The longest failure line a transcript shows; the provider's message is cut to this. */
755
+ export const REPLY_FAILURE_MAX = 300;
756
+
338
757
  /** Cuts text to a byte count without splitting a character. */
339
758
  function cutUtf8(text: string, maxBytes: number): string {
340
759
  const bytes = new TextEncoder().encode(text);
@@ -357,27 +776,38 @@ export function toolOutputPath(home: string, chat: string, runId: string, callId
357
776
  /** The chat's own secret values, so nothing recorded or written can carry one. */
358
777
  export async function secretValues(ctx: Pick<StepContext, "secrets">): Promise<readonly string[]> {
359
778
  try {
360
- const values: string[] = [];
361
- for (const name of await ctx.secrets.names()) {
362
- const secret = await ctx.secrets.get(name);
363
- if (secret !== undefined) values.push(secret.reveal());
364
- }
365
- return values;
779
+ return await ctx.secrets.values();
366
780
  } catch {
367
781
  return [];
368
782
  }
369
783
  }
370
784
 
785
+ /** What the transcript says when a crash, stop or restart interrupted a reply. */
786
+ export const INTERRUPTED_NOTE = "The reply was stopped before it finished.";
787
+
788
+ /** One entry as `recordEntries` records it: a folded entry or a stopped line. */
789
+ type RecordedEntry =
790
+ | FoldEntry
791
+ | { readonly kind: "stopped"; readonly text: string; readonly interrupted?: true };
792
+
371
793
  /** The entries to record: what finished, and the reply a stopped run got only half way through. */
372
794
  function entriesToRecord(
373
795
  folded: FoldState,
374
- options: { readonly finalText?: string | undefined; readonly stopped: boolean },
796
+ options: {
797
+ readonly finalText?: string | undefined;
798
+ readonly stopped: boolean;
799
+ readonly interrupted?: boolean | undefined;
800
+ },
375
801
  secrets: readonly string[],
376
- ): readonly (FoldEntry | { readonly kind: "stopped"; readonly text: string })[] {
377
- const entries: (FoldEntry | { readonly kind: "stopped"; readonly text: string })[] = [...folded.entries];
802
+ ): readonly RecordedEntry[] {
803
+ const entries: RecordedEntry[] = [...folded.entries];
378
804
  // What is still only an increment is not an entry. A stopped run keeps the
379
805
  // text it got half way through; finished text and thinking are already above.
380
806
  if (options.stopped && folded.text.length > 0) entries.push({ kind: "stopped", text: folded.text });
807
+ // A recovered reply gets one line of its own, even when it wrote no text.
808
+ if (options.interrupted === true) {
809
+ entries.push({ kind: "stopped", text: INTERRUPTED_NOTE, interrupted: true });
810
+ }
381
811
  // The final reply is a chat.message of its own; its text is not an entry too.
382
812
  if (options.finalText !== undefined) {
383
813
  const final = options.finalText.trim();
@@ -398,11 +828,17 @@ async function entryData(
398
828
  ctx: StepContext,
399
829
  chat: string,
400
830
  runId: string,
401
- entry: FoldEntry | { readonly kind: "stopped"; readonly text: string },
831
+ entry: RecordedEntry,
402
832
  secrets: readonly string[],
403
833
  ): Promise<EntryData> {
404
834
  if (entry.kind !== "tool") {
405
- return { runId, kind: entry.kind, text: maskSecrets(entry.text, secrets) };
835
+ return {
836
+ runId,
837
+ kind: entry.kind,
838
+ text: maskSecrets(entry.text, secrets),
839
+ ...(entry.kind === "stopped" && entry.interrupted === true ? { interrupted: true } : {}),
840
+ ...(entry.kind === "stopped" || entry.at === undefined ? {} : { startedAt: entry.at }),
841
+ };
406
842
  }
407
843
  const output = entry.output === null ? null : maskSecrets(entry.output, secrets);
408
844
  const data: EntryData = {
@@ -441,14 +877,19 @@ async function recordEntries(
441
877
  ctx: StepContext,
442
878
  chat: string,
443
879
  folded: FoldState,
444
- options: { readonly finalText?: string | undefined; readonly stopped: boolean },
880
+ options: {
881
+ readonly finalText?: string | undefined;
882
+ readonly stopped: boolean;
883
+ readonly interrupted?: boolean | undefined;
884
+ },
445
885
  ): Promise<void> {
446
886
  const secrets = await secretValues(ctx);
447
887
  const wanted = entriesToRecord(folded, options, secrets);
448
888
  if (wanted.length === 0) return;
449
- const existing = allEntries(ctx.store, chat);
889
+ const read = readChat(ctx.store, chat);
890
+ const existing = read.entries;
450
891
  const lastReply = new Map<string, number>();
451
- for (const message of allMessages(ctx.store, chat)) {
892
+ for (const message of read.messages) {
452
893
  if (message.role !== "assistant" || message.runId === undefined) continue;
453
894
  lastReply.set(message.runId, Math.max(lastReply.get(message.runId) ?? 0, message.sequence));
454
895
  }
@@ -484,17 +925,377 @@ async function recordEntries(
484
925
  }
485
926
  }
486
927
 
928
+ /**
929
+ * The user's word for a provider's internal name. Only `harness` is rewritten:
930
+ * `run`, `step`, `flow` and `fact` are also ordinary English, and a provider's
931
+ * "run out of quota" must stay as it said it.
932
+ */
933
+ const PLAIN_WORDS: Readonly<Record<string, readonly [string, string]>> = {
934
+ harness: ["agent", "agents"],
935
+ };
936
+
937
+ /** Replaces an internal word in a provider's message with the word a person reads. */
938
+ function plainWords(text: string): string {
939
+ return text.replace(/\b(harness)(es)?\b/gi, (word, base: string, plural: string | undefined) => {
940
+ const pair = PLAIN_WORDS[base.toLowerCase()];
941
+ if (pair === undefined) return word;
942
+ const replacement = plural === undefined ? pair[0] : pair[1];
943
+ return word[0] === word[0]?.toUpperCase() ? `${replacement[0]?.toUpperCase() ?? ""}${replacement.slice(1)}` : replacement;
944
+ });
945
+ }
946
+
947
+ /** One plain line saying a reply failed, with the provider's message masked and cut short. */
948
+ export function replyFailureLine(message: string, secrets: readonly string[]): string {
949
+ const detail = plainWords(maskSecrets(message, secrets).replace(/\s+/g, " ").trim());
950
+ const line = detail.length === 0 ? "The reply failed." : `The reply failed: ${detail}`;
951
+ return line.length <= REPLY_FAILURE_MAX ? line : `${line.slice(0, REPLY_FAILURE_MAX - 1)}…`;
952
+ }
953
+
954
+ /**
955
+ * Why an empty reply ended, in plain words. A reply with no text but with usage
956
+ * reached the model; one with neither ended without calling it, and the agent's
957
+ * own message is the reason it gives.
958
+ */
959
+ function emptyReplyMessage(data: Readonly<Record<string, unknown>>): string {
960
+ const usage = usageOf(data.usage);
961
+ if (usage.tokens !== undefined || usage.costMicros !== undefined) return "the agent gave no reply";
962
+ const ended = "the agent ended without answering and without calling the model";
963
+ const reason = typeof data.message === "string" ? data.message.replace(/\s+/g, " ").trim() : "";
964
+ return reason.length === 0 ? ended : `${ended} (${reason})`;
965
+ }
966
+
967
+ /** How many empty failures in a row after `after` are for `oldest`; another failure or a stop ends the run. */
968
+ function emptyFailureStreak(entries: readonly Entry[], after: number, oldest: string): number {
969
+ let count = 0;
970
+ for (const entry of entries) {
971
+ if (entry.sequence <= after) continue;
972
+ if (entry.kind === "stopped") {
973
+ count = 0;
974
+ } else if (entry.kind === "failure") {
975
+ if (entry.reason === "empty" && entry.messageId === oldest) count += 1;
976
+ else count = 0;
977
+ }
978
+ }
979
+ return count;
980
+ }
981
+
982
+ /**
983
+ * Records a failure as one entry after the last person's message or reply. A
984
+ * rerun of the same run finds its failure and does not add another, even when
985
+ * the provider words it differently; every other failed run records its own,
986
+ * so a retried attempt that fails again does not leave the chat looking like
987
+ * it is still writing.
988
+ *
989
+ * An empty failure twice in a row for the same oldest message marks that
990
+ * message taken, so a message the agent never answers is not sent forever.
991
+ */
992
+ async function recordFailure(
993
+ ctx: StepContext,
994
+ chat: string,
995
+ reason: string,
996
+ message: string,
997
+ oldest?: string | undefined,
998
+ ): Promise<void> {
999
+ const text = replyFailureLine(message, await secretValues(ctx));
1000
+ const read = readChat(ctx.store, chat);
1001
+ let lastReply = 0;
1002
+ for (const item of read.messages) {
1003
+ if (item.role === "user") continue;
1004
+ lastReply = Math.max(lastReply, item.sequence);
1005
+ }
1006
+ const recorded = read.entries.some(
1007
+ (entry) => entry.kind === "failure" && entry.runId === ctx.runId,
1008
+ );
1009
+ if (!recorded) {
1010
+ const data: EntryData = {
1011
+ runId: ctx.runId,
1012
+ kind: "failure",
1013
+ text,
1014
+ reason,
1015
+ ...(oldest === undefined ? {} : { messageId: oldest }),
1016
+ };
1017
+ await ctx.facts.append({ type: ENTRY_FACT, object: chatRef(chat), data });
1018
+ }
1019
+ if (reason !== "empty" || oldest === undefined) return;
1020
+ const streak = emptyFailureStreak(readChat(ctx.store, chat).entries, lastReply, oldest);
1021
+ if (streak >= 2) await recordTaken(ctx, chat, ctx.runId, [oldest]);
1022
+ }
1023
+
1024
+ /**
1025
+ * Records messages an attempt took before it ended without a reply message, so
1026
+ * a later round does not give them to the agent again.
1027
+ */
1028
+ async function recordTaken(ctx: StepContext, chat: string, runId: string, ids: readonly string[]): Promise<void> {
1029
+ if (ids.length === 0) return;
1030
+ const facts = readChat(ctx.store, chat).facts;
1031
+ const seen = new Set(facts.flatMap((fact) => answeredOfFact(fact)));
1032
+ const fresh = ids.filter((id) => !seen.has(id));
1033
+ if (fresh.length === 0) return;
1034
+ await ctx.facts.append({
1035
+ type: ANSWER_FACT,
1036
+ object: chatRef(chat),
1037
+ data: { runId, ids: fresh },
1038
+ });
1039
+ }
1040
+
1041
+ /** Ends a reply as failed, after recording why in the chat. */
1042
+ async function failedReply(
1043
+ ctx: StepContext,
1044
+ chat: string,
1045
+ reason: string,
1046
+ message: string,
1047
+ oldest?: string | undefined,
1048
+ ): Promise<PluginStepResult> {
1049
+ await recordFailure(ctx, chat, reason, message, oldest);
1050
+ return failed(reason, message);
1051
+ }
1052
+
1053
+ /** The reason and message a failed step result carries. */
1054
+ function failureOf(result: PluginStepResult): { readonly reason: string; readonly message: string } {
1055
+ const data = isRecord(result.data) ? result.data : {};
1056
+ return {
1057
+ reason: typeof data.reason === "string" ? data.reason : "harness",
1058
+ message: typeof data.message === "string" ? data.message : `the agent ended "${result.result}"`,
1059
+ };
1060
+ }
1061
+
1062
+ /**
1063
+ * The inbox a chat passes to a harness that takes messages mid-run. It keeps
1064
+ * what arrives until the harness listens, then hands everything on in order,
1065
+ * and records only the messages the harness actually took. A take and a change
1066
+ * of the same message take the chat's queue lock in turn, so exactly one wins.
1067
+ * A message still waiting when the run ends is left for the next round.
1068
+ */
1069
+ interface ReplyInbox {
1070
+ readonly inbox: MessageInbox;
1071
+ send(id: string): void;
1072
+ /** The ids of the messages handed to the harness, in arrival order. */
1073
+ readonly handed: readonly string[];
1074
+ close(): Promise<void>;
1075
+ }
1076
+
1077
+ type Handed = "taken" | "left" | "wait";
1078
+
1079
+ function replyInbox(
1080
+ ctx: StepContext,
1081
+ chat: string,
1082
+ runId: string,
1083
+ skills: ReturnType<typeof readSkills>,
1084
+ loadsSkills: boolean,
1085
+ ): ReplyInbox {
1086
+ let listener: ((text: string) => boolean | void) | undefined;
1087
+ const waiting: string[] = [];
1088
+ const handed: string[] = [];
1089
+ let open = true;
1090
+ let pumping: Promise<void> | undefined;
1091
+
1092
+ const deliver = async (id: string): Promise<Handed> => {
1093
+ await queueTestHooks.beforeTake?.(id);
1094
+ return withQueueLock(ctx.home, chat, async () => {
1095
+ if (!open || listener === undefined) return "wait";
1096
+ const read = readChat(ctx.store, chat);
1097
+ if (takenIds(read.facts).has(id)) return "left";
1098
+ const message = read.messages.find((item) => item.id === id);
1099
+ if (message === undefined || message.role !== "user") return "left";
1100
+ if (listener(skillMessage(message.text, skills, loadsSkills)) === false) return "left";
1101
+ await takeLocked(ctx.store, ctx.facts, chat, runId, [id], "step:chat/reply", read);
1102
+ return "taken";
1103
+ });
1104
+ };
1105
+
1106
+ const pump = (): Promise<void> => {
1107
+ if (pumping !== undefined) return pumping;
1108
+ const task = Promise.resolve().then(async () => {
1109
+ try {
1110
+ while (open && listener !== undefined && waiting.length > 0) {
1111
+ const id = waiting[0];
1112
+ if (id === undefined) break;
1113
+ let outcome: Handed;
1114
+ try {
1115
+ outcome = await deliver(id);
1116
+ } catch (error) {
1117
+ await ctx.logger.write(
1118
+ `a message could not be handed to the agent: ${messageOf(error)}`,
1119
+ );
1120
+ outcome = "left";
1121
+ }
1122
+ if (outcome === "wait") break;
1123
+ if (waiting[0] === id) waiting.shift();
1124
+ if (outcome === "taken") handed.push(id);
1125
+ }
1126
+ } finally {
1127
+ pumping = undefined;
1128
+ if (open && listener !== undefined && waiting.length > 0) void pump();
1129
+ }
1130
+ });
1131
+ pumping = task;
1132
+ return task;
1133
+ };
1134
+
1135
+ return {
1136
+ inbox: {
1137
+ listen(next) {
1138
+ listener = next;
1139
+ void pump();
1140
+ return () => {
1141
+ if (listener === next) listener = undefined;
1142
+ };
1143
+ },
1144
+ },
1145
+ send(id) {
1146
+ if (!open) return;
1147
+ waiting.push(id);
1148
+ void pump();
1149
+ },
1150
+ handed,
1151
+ async close() {
1152
+ open = false;
1153
+ listener = undefined;
1154
+ waiting.length = 0;
1155
+ await pumping;
1156
+ },
1157
+ };
1158
+ }
1159
+
1160
+ /** Records that the reply step returned on its own, before its result enters the log. */
1161
+ async function recordAttemptEnd(ctx: StepContext, chat: string): Promise<void> {
1162
+ await ctx.facts.append({
1163
+ type: ATTEMPT_END_FACT,
1164
+ object: chatRef(chat),
1165
+ data: { runId: ctx.runId },
1166
+ });
1167
+ }
1168
+
1169
+ /**
1170
+ * Runs after a reply step a crash, stop or restart interrupted. It reads the
1171
+ * log the agent wrote and records the entries it finished, the half-written
1172
+ * text and one line saying the reply stopped, so `/retry` can continue the
1173
+ * chat from what was kept. A step that returned `interrupted` on its own
1174
+ * already recorded those and left its attempt fact, so this adds nothing.
1175
+ */
1176
+ export async function keepInterrupted(ctx: StepContext, _params: unknown): Promise<PluginStepResult> {
1177
+ const object = ctx.object;
1178
+ if (object === undefined || object.type !== CHAT_TYPE) {
1179
+ return failed("object", "chat:reply runs on a chat");
1180
+ }
1181
+ const stored = await ctx.store.get(CHAT_TYPE, object.id);
1182
+ if (stored === undefined) return { result: "done", data: {} };
1183
+ const chatRead = readChat(ctx.store, object.id);
1184
+ const messages = chatRead.messages;
1185
+ const facts = chatRead.facts;
1186
+ const pending = unanswered(messages, facts);
1187
+ const replied = messages.some((message) => message.role === "assistant" && message.runId === ctx.runId);
1188
+ if (replied && pending.length === 0) {
1189
+ // The reply entered the record before the crash and owes no message: there is nothing to mark.
1190
+ await syncChat(ctx, object.id, undefined);
1191
+ return { result: "done", data: { kept: false } };
1192
+ }
1193
+ if (facts.some((fact) => attemptEndedOfFact(fact) === ctx.runId)) {
1194
+ // The reply step ended on its own and recorded its entries first.
1195
+ return { result: "done", data: { kept: false } };
1196
+ }
1197
+ const chat = chatData(stored.data);
1198
+ const read = foldLogTail(agentLogPath(ctx.store.root, chat.harness, ctx.runId));
1199
+ const folded = read?.state ?? emptyFold;
1200
+ // The log holds every round of the run; a round whose reply is already in
1201
+ // the record is a prefix of it and is not recorded again.
1202
+ const prior = chatRead.entries.filter((entry) => entry.runId === ctx.runId).length;
1203
+ const current = prior === 0 ? folded : { ...folded, entries: folded.entries.slice(prior) };
1204
+ await recordEntries(ctx, object.id, current, { stopped: true, interrupted: true });
1205
+ // A run that ended on its own is recorded by its last round; one that was
1206
+ // stopped after writing still gets its changes recorded here.
1207
+ await runAfterStep(ctx, await afterStepOfRefresh(ctx, chat, object), object, "done");
1208
+ return { result: "done", data: { kept: true } };
1209
+ }
1210
+
1211
+ /**
1212
+ * Runs the step a chat's refresh data names after a round, once the round is
1213
+ * over. A plugin uses it to record what the round wrote (the memory plugin's
1214
+ * commit). A failure is logged, never put in the chat: the answer is already
1215
+ * written, and remembering it must not undo the answer.
1216
+ */
1217
+ async function runAfterStep(ctx: StepContext, step: string | undefined, object: RunObject, result: string | undefined): Promise<void> {
1218
+ if (step === undefined) return;
1219
+ if (result !== undefined && result !== "done" && result !== "failed") return;
1220
+ const runStep = ctx.runStep;
1221
+ if (runStep === undefined) return;
1222
+ if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(step)) {
1223
+ ctx.logger.write(`after ${step}: the step is not loaded\n`);
1224
+ return;
1225
+ }
1226
+ try {
1227
+ const outcome = await runStep(step, { chat: object.id }, { runId: ctx.runId, object, params: ctx.params, signal: ctx.signal });
1228
+ if (outcome.result !== "done") {
1229
+ const message = isRecord(outcome.data) && typeof outcome.data.message === "string" ? outcome.data.message : `it ended ${outcome.result}`;
1230
+ ctx.logger.write(`after ${step}: ${message}\n`);
1231
+ }
1232
+ } catch (error) {
1233
+ ctx.logger.write(`after ${step}: ${messageOf(error)}\n`);
1234
+ }
1235
+ }
1236
+
1237
+ /** The after step a chat's refresh step names now, read for a run that ended without a round. */
1238
+ async function afterStepOfRefresh(ctx: StepContext, chat: ChatData, object: RunObject): Promise<string | undefined> {
1239
+ if (chat.refresh === undefined) return undefined;
1240
+ const runStep = ctx.runStep;
1241
+ if (runStep === undefined) return undefined;
1242
+ if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(chat.refresh)) return undefined;
1243
+ try {
1244
+ const outcome = await runStep(chat.refresh, { chat: object.id }, { runId: ctx.runId, object, params: ctx.params, signal: ctx.signal });
1245
+ const data = isRecord(outcome.data) ? outcome.data : {};
1246
+ return outcome.result === "done" && typeof data.after === "string" && data.after.length > 0 ? data.after : undefined;
1247
+ } catch {
1248
+ return undefined;
1249
+ }
1250
+ }
1251
+
1252
+ /** What one round leaves for the work after it: the after step, and the note hashes it records. */
1253
+ interface ReplyState {
1254
+ after?: string | undefined;
1255
+ keepNotes?: (() => Promise<void>) | undefined;
1256
+ }
1257
+
487
1258
  /** Runs one round of an answer; see the file's comment. */
488
1259
  export async function runReply(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
1260
+ const state: ReplyState = {};
1261
+ let result: string | undefined;
1262
+ try {
1263
+ const outcome = await replyOnce(ctx, params, state);
1264
+ result = outcome.result;
1265
+ return outcome;
1266
+ } finally {
1267
+ const object = ctx.object;
1268
+ if (object !== undefined) {
1269
+ await runAfterStep(ctx, state.after, object, result);
1270
+ if (state.keepNotes !== undefined) {
1271
+ try {
1272
+ await state.keepNotes();
1273
+ } catch (error) {
1274
+ await ctx.logger.write(
1275
+ `the note hashes could not be recorded: ${messageOf(error)}\n`,
1276
+ );
1277
+ }
1278
+ }
1279
+ }
1280
+ }
1281
+ }
1282
+
1283
+ /** One round of an answer, before the after step runs. */
1284
+ async function replyOnce(
1285
+ ctx: StepContext,
1286
+ params: unknown,
1287
+ state: ReplyState,
1288
+ ): Promise<PluginStepResult> {
489
1289
  const object = ctx.object;
490
1290
  if (object === undefined || object.type !== CHAT_TYPE) {
491
1291
  return failed("object", "chat:reply runs on a chat");
492
1292
  }
493
1293
  const stored = await ctx.store.get(CHAT_TYPE, object.id);
494
1294
  if (stored === undefined) return failed("object", `there is no chat ${object.id}`);
495
- const chat = chatData(stored.data);
496
- const messages = allMessages(ctx.store, object.id);
497
- const pending = unanswered(messages);
1295
+ let chat = chatData(stored.data);
1296
+ const read = readChat(ctx.store, object.id);
1297
+ let messages = read.messages;
1298
+ let pending = unanswered(messages, read.facts);
498
1299
  if (pending.length === 0) {
499
1300
  // A run that stopped after recording a reply still owes the chat its model and cost.
500
1301
  await syncChat(ctx, object.id, undefined);
@@ -502,70 +1303,227 @@ export async function runReply(ctx: StepContext, params: unknown): Promise<Plugi
502
1303
  }
503
1304
 
504
1305
  const runStep = ctx.runStep;
505
- if (runStep === undefined) return failed("host", "the kernel did not offer a way to run the agent");
1306
+ const oldest = pending[0]?.id;
1307
+ if (runStep === undefined) return failedReply(ctx, object.id, "host", "the agent could not be started", oldest);
506
1308
  const use = `${chat.harness}/agent`;
507
1309
  if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(use)) {
508
- return failed("harness", `the agent "${chat.harness}" is not loaded`);
1310
+ return failedReply(ctx, object.id, "harness", `the agent "${chat.harness}" is not loaded`, oldest);
509
1311
  }
510
1312
 
511
1313
  // A model the agent cannot take fails the reply by name; it never falls back.
512
- if (chat.model !== undefined && ctx.harnessModels?.(chat.harness)?.list.includes(chat.model) !== true) {
513
- return failed("model", `the agent "${chat.harness}" cannot use the model "${chat.model}"`);
1314
+ // A harness that has not read its list yet gets one refresh to answer, so a
1315
+ // first reply is not refused only because the list was not there at load.
1316
+ if (chat.model !== undefined) {
1317
+ const models =
1318
+ ctx.harnessModelsReady !== undefined
1319
+ ? await ctx.harnessModelsReady(chat.harness)
1320
+ : ctx.harnessModels?.(chat.harness);
1321
+ if (!modelIds(models).includes(chat.model)) {
1322
+ return failedReply(ctx, object.id, "model", `the agent "${chat.harness}" cannot use the model "${chat.model}"`, oldest);
1323
+ }
514
1324
  }
515
- // The same for an effort: the agent's list is the only one that can take it.
1325
+ // The same for an effort: the agent's list is the only one that can take the
1326
+ // effort the chat chose; one equal to its stored default is inherited.
516
1327
  const efforts = ctx.harnessEfforts?.(chat.harness);
517
- if (chat.effort !== undefined && efforts?.list.includes(chat.effort) !== true) {
518
- return failed("effort", `the agent "${chat.harness}" cannot use the effort "${chat.effort}"`);
1328
+ const effort = chosenEffort(chat);
1329
+ if (effort !== undefined && efforts?.list.includes(effort) !== true) {
1330
+ return failedReply(ctx, object.id, "effort", `the agent "${chat.harness}" cannot use the effort "${effort}"`, oldest);
519
1331
  }
520
1332
  const effortFlag = efforts?.flag ?? (chat.harness === "pi" ? "--thinking" : "--effort");
521
1333
 
522
1334
  const settled = await liveSettings(ctx, chat, object, runStep);
523
- if ("result" in settled) return settled;
1335
+ if ("result" in settled) {
1336
+ const why = failureOf(settled);
1337
+ return failedReply(ctx, object.id, why.reason, why.message, oldest);
1338
+ }
524
1339
  const live = settled;
1340
+ state.after = live.after;
1341
+ // A chat that never chose a level follows the level its plugin starts chats
1342
+ // at now, so changing that setting moves it; a chosen level stays.
1343
+ if (live.accessDefault !== undefined && !chat.accessChosen && (chat.accessDefault !== live.accessDefault || chat.accessLevel !== live.accessDefault)) {
1344
+ const fresh = await ctx.store.get(CHAT_TYPE, object.id);
1345
+ if (fresh !== undefined && !chatData(fresh.data).accessChosen) {
1346
+ const next = { ...fresh.data, accessLevel: live.accessDefault, accessDefault: live.accessDefault };
1347
+ await ctx.store.put(CHAT_TYPE, object.id, next, "step:chat/reply");
1348
+ chat = chatData(next);
1349
+ }
1350
+ }
1351
+ // The notes this message may carry: a bot's memory index and instructions. A
1352
+ // file that cannot be read is logged and left out; it never fails the answer.
1353
+ const noteContents =
1354
+ live.notes === undefined
1355
+ ? []
1356
+ : await readNoteFiles(live.notes, live.cwd, (problem) => {
1357
+ void ctx.logger.write(`${problem}\n`);
1358
+ });
1359
+ // A level reaches the harness only through an agent that declares it can
1360
+ // carry it; an agent that cannot refuses the reply by name, never ignores it.
1361
+ const level = chat.accessLevel ?? "ask";
1362
+ const capabilities = ctx.harnessCapabilities?.(chat.harness);
1363
+ if (capabilities !== undefined && !(capabilities.accessLevels ?? []).includes(level)) {
1364
+ return failedReply(
1365
+ ctx,
1366
+ object.id,
1367
+ "access",
1368
+ `the agent "${chat.harness}" cannot carry the access level "${level}"`,
1369
+ oldest,
1370
+ );
1371
+ }
1372
+ const leveled = withAccessLevel(live.access, level);
1373
+ const skills = readSkills(live.skills);
1374
+ const loadsSkills = capabilities?.loadsSkills === true;
1375
+
1376
+ // A harness that takes messages mid-run is handed each ordinary message that
1377
+ // arrives while this round runs, after the tool calls already running. A
1378
+ // message with an attachment waits for the next round: the mid-run inbox
1379
+ // carries text, and its image or file reaches the agent as a first message does.
1380
+ const midRun =
1381
+ ctx.harnessCapabilities?.(chat.harness)?.takesMessagesMidRun === true
1382
+ ? replyInbox(ctx, object.id, ctx.runId, skills, loadsSkills)
1383
+ : undefined;
1384
+ const arrived = new Set<string>();
1385
+ let stopMidRun: (() => void) | undefined;
1386
+ if (midRun !== undefined) {
1387
+ const inbox = midRun;
1388
+ stopMidRun = ctx.store.subscribe(chatRef(object.id), {}, (fact) => {
1389
+ if (fact.type !== MESSAGE_FACT) return;
1390
+ const data = fact.data;
1391
+ if (data.role !== "user" || typeof data.id !== "string" || typeof data.text !== "string") return;
1392
+ arrived.add(data.id);
1393
+ if (attachmentsOf(data.attachments).length === 0) inbox.send(data.id);
1394
+ });
1395
+ // A message that came between the first read and this subscription is in
1396
+ // the facts now. It is delivered, not also put into the prompt.
1397
+ const fresh = readChat(ctx.store, object.id);
1398
+ messages = fresh.messages;
1399
+ pending = unanswered(messages, fresh.facts).filter((message) => !arrived.has(message.id));
1400
+ }
1401
+
1402
+ let stopWatching: (() => void) | undefined;
1403
+ const closeMidRun = async (): Promise<void> => {
1404
+ if (stopWatching !== undefined) {
1405
+ stopWatching();
1406
+ stopWatching = undefined;
1407
+ }
1408
+ if (stopMidRun !== undefined) {
1409
+ stopMidRun();
1410
+ stopMidRun = undefined;
1411
+ }
1412
+ await midRun?.close();
1413
+ };
525
1414
 
526
1415
  const resumed = isRecord(params) ? params : {};
527
1416
  const session =
528
1417
  typeof resumed.resumeSession === "string" ? resumed.resumeSession : currentSession(chat, messages);
529
- const readOnly = live.access.readOnly === true;
530
- let worktreeAsked = 0;
531
- const asker = readOnly
532
- ? readOnlyAsker(ctx, async () => {
533
- worktreeAsked += 1;
534
- await ctx.emit({
535
- type: WORKTREE_EVENT,
536
- key: `${ctx.runId}:${worktreeAsked}`,
537
- object: `${CHAT_TYPE}:${object.id}`,
538
- });
539
- })
540
- : undefined;
1418
+ // The context the last reply in this session ended with; a smaller one after
1419
+ // this reply means the agent compacted the session.
1420
+ const previousUsed = lastContextUsed(messages, session);
1421
+ const readOnly = leveled.readOnly === true;
1422
+ // The worktree question belongs to a repository chat; a bot chat at `plan`
1423
+ // is read-only without one.
1424
+ const worktreeChat =
1425
+ readOnly && live.worktreeOffer !== false && (chat.parent === undefined || chat.parent.startsWith("repo:"));
1426
+ const worktreeChosen = { run: false, stop: new AbortController() };
1427
+ // The live file holds the base profile; a level change rewrites only its level.
1428
+ let recheckBase: Readonly<Record<string, JsonValue>> = live.access;
1429
+ const withLevel = levelAsker(ctx, object.id, live.cwd, () => recheckBase, level, contextAsker(ctx));
1430
+ const asker = worktreeChat ? readOnlyAsker(ctx, object.id, live.cwd, worktreeChosen, withLevel) : withLevel;
1431
+ if (worktreeChat) {
1432
+ // A level change opens the worktree before it is recorded. This reply runs
1433
+ // in the main clone with the profile it started with, so when the chat has
1434
+ // moved it ends and is answered again there, rather than going on in the
1435
+ // main clone or asking again as read-only.
1436
+ stopWatching = ctx.store.subscribe(chatRef(object.id), {}, (fact) => {
1437
+ if (fact.type !== ACCESS_FACT || worktreeChosen.run) return;
1438
+ void movedFrom(ctx, object.id, live.cwd).then((moved) => {
1439
+ if (!moved || worktreeChosen.run) return;
1440
+ worktreeChosen.run = true;
1441
+ worktreeChosen.stop.abort();
1442
+ });
1443
+ });
1444
+ }
1445
+ // A worktree yes aborts `stop`, so the harness ends even if it swallows the
1446
+ // stop error; the reply still ends `done` below.
1447
+ const signal = worktreeChat ? AbortSignal.any([ctx.signal, worktreeChosen.stop.signal]) : ctx.signal;
541
1448
 
542
- // A "yes" that came back after the wait (the grace had passed) is the same
543
- // answer as one given live. A "no" carries the same refusal a live answer gets.
1449
+ // An answer that came back after the wait (the grace had passed) is the same
1450
+ // answer as one given live.
544
1451
  const late = answeredQuestion(params);
545
- const lateWorktree = readOnly && late !== undefined && isWorktreeQuestion(late.prompt);
546
- if (lateWorktree && late.choice === "yes") {
1452
+ const lateWorktree = worktreeChat && late !== undefined && isWorktreeQuestion(late.prompt);
1453
+ const lateAction = lateWorktree && late !== undefined ? worktreeAnswer(late.choice) : undefined;
1454
+ const lateCall = lateWorktree ? callFromGrants(ctx.access) ?? callFromQuestion(late?.prompt ?? "") : undefined;
1455
+ if (lateAction === "worktree") {
1456
+ // The reply that asked is already over. Open the worktree once, but do
1457
+ // not start another reply for the same message. The harness is not run,
1458
+ // so the mid-run inbox closes with this step.
1459
+ await closeMidRun();
547
1460
  await ctx.emit({
548
1461
  type: WORKTREE_EVENT,
549
- key: `${ctx.runId}:late`,
1462
+ key: "late",
550
1463
  object: `${CHAT_TYPE}:${object.id}`,
1464
+ data: { late: true },
551
1465
  });
1466
+ return { result: "done", data: { worktree: true } };
1467
+ }
1468
+ if (lateAction === "allow_always" && lateCall !== undefined && personStarted(ctx.trigger)) {
1469
+ await rememberAlways(ctx, lateCall, live.cwd);
552
1470
  }
553
1471
  const askAnswer =
554
- lateWorktree && late.choice !== "yes"
555
- ? {
556
- prompt: late.prompt,
557
- choice: late.choice,
558
- note: late.note === undefined ? READ_ONLY_REFUSAL : `${READ_ONLY_REFUSAL}\n${late.note}`,
559
- }
560
- : resumed.askAnswer;
1472
+ lateAction === undefined
1473
+ ? resumed.askAnswer
1474
+ : {
1475
+ prompt: late?.prompt ?? "",
1476
+ choice:
1477
+ lateAction === "allow_once"
1478
+ ? "allow_once"
1479
+ : lateAction === "allow_always"
1480
+ ? "allow_always"
1481
+ : "reject_once",
1482
+ ...(lateAction === "deny"
1483
+ ? { note: late?.note === undefined ? READ_ONLY_REFUSAL : `${READ_ONLY_REFUSAL}\n${late.note}` }
1484
+ : {}),
1485
+ };
561
1486
 
562
1487
  // The files sent with a message: images as input where the harness takes
563
1488
  // them, every file as a path, and the chat's own attachment directory open to reads.
564
1489
  const directory = attachmentDir(ctx.home, CHAT_TYPE, object.id);
565
- const images = imagesOf(pending, chat.harness, directory);
566
- const access = messages.some((message) => message.attachments.length > 0)
1490
+ const levelPath = accessLevelPath(ctx.home, object.id);
1491
+ const withReads = messages.some((message) => message.attachments.length > 0)
567
1492
  ? withAttachmentReads(live.access, directory)
568
1493
  : live.access;
1494
+ const baseAccess = withLevelFileDeny(withReads, levelPath);
1495
+ recheckBase = baseAccess;
1496
+ const base = withAccessLevel(baseAccess, level);
1497
+ try {
1498
+ await writeLiveAccess(levelPath, baseAccess, level);
1499
+ } catch (error) {
1500
+ await ctx.logger.write(
1501
+ `the live access level could not be written: ${messageOf(error)}`,
1502
+ );
1503
+ }
1504
+ // A late Allow once is for this run alone; a late Always allow also wrote the user layer.
1505
+ const lateEntry =
1506
+ (lateAction === "allow_once" || lateAction === "allow_always") && lateCall !== undefined
1507
+ ? alwaysAllowEntry(lateCall, live.cwd)
1508
+ : undefined;
1509
+ const existing = Array.isArray(base.alwaysAllow) ? base.alwaysAllow : [];
1510
+ const access = {
1511
+ ...(lateEntry === undefined
1512
+ ? base
1513
+ : {
1514
+ ...base,
1515
+ alwaysAllow: [
1516
+ ...existing,
1517
+ {
1518
+ kind: lateEntry.kind,
1519
+ value: lateEntry.value,
1520
+ cwd: lateEntry.cwd,
1521
+ ...(lateEntry.tool === undefined ? {} : { tool: lateEntry.tool }),
1522
+ },
1523
+ ],
1524
+ }),
1525
+ levelFile: levelPath,
1526
+ };
569
1527
 
570
1528
  // The harness hands each log line over as it writes it; the fold keeps what
571
1529
  // is finished and what is still being written. None of this is stored until
@@ -581,32 +1539,77 @@ export async function runReply(ctx: StepContext, params: unknown): Promise<Plugi
581
1539
  folded = foldLines([value], folded);
582
1540
  };
583
1541
 
1542
+ // The messages this round starts with are taken now, under the queue lock,
1543
+ // so a withdraw or change either comes before the run takes them or is
1544
+ // refused. A message withdrawn after the first read leaves the prompt.
1545
+ let locked: ChatRead | undefined;
1546
+ pending = await withQueueLock(ctx.home, object.id, async () => {
1547
+ const latest = readChat(ctx.store, object.id);
1548
+ locked = latest;
1549
+ const current = unanswered(latest.messages, latest.facts).filter(
1550
+ (message) => !arrived.has(message.id),
1551
+ );
1552
+ await takeLocked(
1553
+ ctx.store,
1554
+ ctx.facts,
1555
+ object.id,
1556
+ ctx.runId,
1557
+ current.map((message) => message.id),
1558
+ "step:chat/reply",
1559
+ latest,
1560
+ );
1561
+ return current;
1562
+ });
1563
+ if (pending.length === 0) {
1564
+ await closeMidRun();
1565
+ await syncChat(ctx, object.id, undefined);
1566
+ return { result: "done", data: { answered: 0 } };
1567
+ }
1568
+ const images = imagesOf(pending, chat.harness, directory);
1569
+
584
1570
  // The run is a fact before the agent starts: a view finds the step's log by it.
585
- if (latestRunOf(chatFacts(ctx.store, object.id)) !== ctx.runId) {
1571
+ if (locked === undefined || latestRunOf(locked.facts) !== ctx.runId) {
586
1572
  await ctx.facts.append({ type: RUN_FACT, object: chatRef(object.id), data: { runId: ctx.runId } });
587
1573
  }
588
1574
 
1575
+ const context = contextFor(chat, live, session);
1576
+ const carried =
1577
+ live.notes === undefined ? [] : notesToAttach(noteContents, chat.noteHashes, session);
1578
+ const noteText = carried.length === 0 ? undefined : noteBlock(carried);
1579
+ const messagePrompt = promptFor(
1580
+ pending.map((message) => ({ ...message, text: skillMessage(message.text, skills, loadsSkills) })),
1581
+ new Set(images.map((image) => image.path)),
1582
+ );
1583
+ const prompt = [context, noteText, messagePrompt]
1584
+ .filter((part): part is string => part !== undefined && part.length > 0)
1585
+ .join("\n\n");
589
1586
  let outcome: PluginStepResult;
590
1587
  try {
591
1588
  outcome = await runStep(
592
1589
  use,
593
1590
  {
594
- prompt: promptFor(pending, new Set(images.map((image) => image.path))),
1591
+ prompt,
595
1592
  ...(images.length === 0 ? {} : { images }),
596
1593
  cwd: live.cwd,
597
- ...(chat.model === undefined && chat.effort === undefined
1594
+ ...(chat.model === undefined && effort === undefined
598
1595
  ? {}
599
1596
  : {
600
1597
  args: [
601
1598
  ...(chat.model === undefined ? [] : ["--model", chat.model]),
602
- ...(chat.effort === undefined ? [] : [effortFlag, chat.effort]),
1599
+ ...(effort === undefined ? [] : [effortFlag, effort]),
603
1600
  ],
604
1601
  }),
605
- ...(chat.effort === undefined ? {} : { effort: chat.effort }),
1602
+ ...(effort === undefined ? {} : { effort }),
606
1603
  ...(live.skills.length === 0 ? {} : { skills: live.skills }),
607
1604
  // Operad's own tools, so the agent never runs the `operad` command.
608
1605
  operadTools: { home: ctx.home },
1606
+ ...(midRun === undefined ? {} : { inbox: midRun.inbox }),
1607
+ ...(chat.harness === "pi" || chat.harness === "claude" ? { keepWorker: true } : {}),
1608
+ // A chat retries a failed model request with pi's own bounded backoff;
1609
+ // a task keeps pi's retry off and uses dev's own waits and fallbacks.
1610
+ ...(chat.harness === "pi" ? { retry: true } : {}),
609
1611
  ...(Object.keys(live.mcpServers).length === 0 ? {} : { mcpServers: live.mcpServers }),
1612
+ ...(live.useOwnSettings ? { useOwnSettings: true } : {}),
610
1613
  ...(session === undefined ? {} : { resumeSession: session }),
611
1614
  ...(askAnswer === undefined ? {} : { askAnswer }),
612
1615
  },
@@ -617,18 +1620,43 @@ export async function runReply(ctx: StepContext, params: unknown): Promise<Plugi
617
1620
  params: ctx.params,
618
1621
  access,
619
1622
  ...(ctx.trigger === undefined ? {} : { trigger: ctx.trigger }),
620
- signal: ctx.signal,
1623
+ signal,
621
1624
  receiver,
622
- ...(asker === undefined ? {} : { asker }),
1625
+ asker,
623
1626
  },
624
1627
  );
625
1628
  } catch (error) {
1629
+ await closeMidRun();
1630
+ if (worktreeChosen.run || error instanceof WorktreeChosen) {
1631
+ await recordEntries(ctx, object.id, folded, { stopped: true });
1632
+ await ctx.emit({
1633
+ type: WORKTREE_EVENT,
1634
+ key: "open",
1635
+ object: `${CHAT_TYPE}:${object.id}`,
1636
+ });
1637
+ return { result: "done", data: { worktree: true } };
1638
+ }
1639
+ await recordEntries(ctx, object.id, folded, { stopped: true });
1640
+ await recordTaken(ctx, object.id, ctx.runId, midRun?.handed ?? []);
1641
+ return failedReply(ctx, object.id, "harness", messageOf(error), oldest);
1642
+ }
1643
+ if (worktreeChosen.run) {
1644
+ await closeMidRun();
626
1645
  await recordEntries(ctx, object.id, folded, { stopped: true });
627
- return failed("harness", messageOf(error));
1646
+ await ctx.emit({
1647
+ type: WORKTREE_EVENT,
1648
+ key: "open",
1649
+ object: `${CHAT_TYPE}:${object.id}`,
1650
+ });
1651
+ return { result: "done", data: { worktree: true } };
628
1652
  }
1653
+ // From here on the harness can no longer take a message: one that arrives
1654
+ // now stays unanswered and is answered by the next round.
1655
+ await closeMidRun();
629
1656
 
630
1657
  if (outcome.result === "waiting") {
631
1658
  await recordEntries(ctx, object.id, folded, { stopped: true });
1659
+ await recordTaken(ctx, object.id, ctx.runId, midRun?.handed ?? []);
632
1660
  return { result: "waiting", ...(outcome.data === undefined ? {} : { data: outcome.data }) };
633
1661
  }
634
1662
  const data = isRecord(outcome.data) ? outcome.data : {};
@@ -639,27 +1667,39 @@ export async function runReply(ctx: StepContext, params: unknown): Promise<Plugi
639
1667
  }
640
1668
  if (outcome.result === "interrupted") {
641
1669
  await recordEntries(ctx, object.id, folded, { stopped: true });
1670
+ await recordTaken(ctx, object.id, ctx.runId, midRun?.handed ?? []);
1671
+ await recordAttemptEnd(ctx, object.id);
642
1672
  return { result: "interrupted", data };
643
1673
  }
644
1674
  if (outcome.result !== "done") {
645
1675
  await recordEntries(ctx, object.id, folded, { stopped: true });
646
- return {
647
- result: "failed",
648
- data: {
649
- reason: typeof data.reason === "string" ? data.reason : "harness",
650
- message: typeof data.message === "string" ? data.message : `the agent ended "${outcome.result}"`,
651
- },
652
- };
1676
+ await recordTaken(ctx, object.id, ctx.runId, midRun?.handed ?? []);
1677
+ const why = failureOf(outcome);
1678
+ return failedReply(ctx, object.id, why.reason, why.message, oldest);
653
1679
  }
654
1680
  const said = typeof data.finalMessage === "string" ? data.finalMessage.trim() : "";
655
1681
  const text = maskSecrets(said, await secretValues(ctx));
656
1682
  if (text.length === 0) {
657
1683
  await recordEntries(ctx, object.id, folded, { stopped: true });
658
- return failed("empty", "the agent gave no reply");
1684
+ await recordTaken(ctx, object.id, ctx.runId, midRun?.handed ?? []);
1685
+ return failedReply(ctx, object.id, "empty", emptyReplyMessage(data), oldest);
659
1686
  }
660
1687
  const sessionId = typeof data.sessionId === "string" && data.sessionId.length > 0 ? data.sessionId : undefined;
661
1688
 
662
1689
  const usage = usageOf(data.usage);
1690
+ const timings = timingsOf(data.timings);
1691
+ const replyContext = replyContextOf(data.context);
1692
+ // A session is compacted when the agent says so, or when this reply ended with
1693
+ // less context than the one before it in the same session. The next message
1694
+ // then carries every note whole again.
1695
+ const compacted =
1696
+ data.compacted === true ||
1697
+ (previousUsed !== undefined && replyContext !== undefined && replyContext.used < previousUsed);
1698
+ const windows = ctx.harnessModels?.(chat.harness)?.windows;
1699
+ const window =
1700
+ replyContext?.window ??
1701
+ (usage.model === undefined ? undefined : windows?.[usage.model]) ??
1702
+ (chat.model === undefined ? undefined : windows?.[chat.model]);
663
1703
 
664
1704
  await recordEntries(ctx, object.id, folded, { finalText: text, stopped: false });
665
1705
 
@@ -672,16 +1712,44 @@ export async function runReply(ctx: StepContext, params: unknown): Promise<Plugi
672
1712
  text,
673
1713
  attachments: [],
674
1714
  source: { kind: chat.harness, ref: null },
675
- replyTo: pending.map((message) => message.id),
1715
+ replyTo: [...pending.map((message) => message.id), ...(midRun?.handed ?? [])],
676
1716
  runId: ctx.runId,
677
1717
  ...(sessionId === undefined ? {} : { session: sessionId }),
678
1718
  ...usage,
1719
+ ...(replyContext === undefined
1720
+ ? {}
1721
+ : { context: { used: replyContext.used, ...(window === undefined ? {} : { window }) } }),
1722
+ ...(timings === undefined ? {} : { timings }),
679
1723
  };
680
1724
  await ctx.facts.append({ type: MESSAGE_FACT, object: chatRef(object.id), data: reply });
681
1725
 
682
1726
  // The chat's own reference follows; read again, so a change made meanwhile stays.
683
- await syncChat(ctx, object.id, sessionId);
1727
+ await syncChat(ctx, object.id, sessionId, live.context === undefined ? undefined : live.cwd);
1728
+ if (live.notes !== undefined) {
1729
+ const keptSession = sessionId ?? session;
1730
+ state.keepNotes = async () => {
1731
+ // Read after the after step, so a change that step wrote (the memory
1732
+ // commit removing an untrusted index line) is what the session now knows.
1733
+ const fresh = compacted
1734
+ ? []
1735
+ : await readNoteFiles(live.notes ?? [], live.cwd, (problem) => {
1736
+ void ctx.logger.write(`${problem}\n`);
1737
+ });
1738
+ // A file this run's own tool calls wrote is what the session knows now;
1739
+ // any other change during the run belongs to the next message.
1740
+ const written = compacted ? new Set<string>() : notesWrittenHere(noteContents, folded.entries);
1741
+ await syncChat(
1742
+ ctx,
1743
+ object.id,
1744
+ undefined,
1745
+ undefined,
1746
+ noteHashesAfter(noteContents, fresh, written, keptSession, compacted),
1747
+ );
1748
+ };
1749
+ }
684
1750
 
685
- const left = unanswered(allMessages(ctx.store, object.id));
686
- return { result: left.length > 0 ? "more" : "done", data: { answered: pending.length, left: left.length } };
1751
+ const leftRead = readChat(ctx.store, object.id);
1752
+ const left = unanswered(leftRead.messages, leftRead.facts);
1753
+ const answered = pending.length + (midRun?.handed.length ?? 0);
1754
+ return { result: left.length > 0 ? "more" : "done", data: { answered, left: left.length } };
687
1755
  }