@operad-io/chat 0.1.0 → 0.2.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,95 @@ 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
+ /**
483
+ * The asker a read-only chat's harness gets: a question about writing a file
484
+ * becomes the worktree question, which may let this call run once, remember it
485
+ * with Always allow, refuse it, or open a worktree; any other question goes
486
+ * where it would have gone.
487
+ *
488
+ * Choosing the worktree stops the harness at once through `stop`, even when it
489
+ * swallows the thrown stop: the reply that asked has ended (ADR 0028 D3).
490
+ */
491
+ function readOnlyAsker(
492
+ ctx: StepContext,
493
+ cwd: string,
494
+ chosen: { run: boolean; readonly stop: AbortController },
495
+ inner: StepAsker,
496
+ ): StepAsker {
497
+ const person = personStarted(ctx.trigger);
498
+ return {
499
+ async ask(request): Promise<AskOutcome> {
500
+ if (chosen.run) throw new WorktreeChosen();
501
+ const write = isWriteQuestion(request);
502
+ const call = write ? worktreeCall(request) : undefined;
503
+ // An entry from an earlier Always allow lifts the question in any chat a person started.
504
+ if (person && call !== undefined && (await userLayer(ctx)).some((entry) => remembered(entry, call, cwd))) {
505
+ return { kind: "answered", answer: { choice: "allow_once" } };
506
+ }
507
+ const choices = person
508
+ ? [...WORKTREE_CHOICES]
509
+ : [WORKTREE_ALLOW_ONCE, WORKTREE_DENY, WORKTREE_YES];
510
+ const shaped: AskRequest = write
511
+ ? {
512
+ prompt: call === undefined ? WORKTREE_QUESTION : worktreeQuestion(call),
513
+ choices,
514
+ choiceInfo: worktreeChoiceInfo(choices),
515
+ ...(request.resume === undefined ? {} : { resume: worktreeResume(request, call) }),
516
+ ...(request.onTimeout === undefined ? {} : { onTimeout: request.onTimeout }),
517
+ ...(request.graceSecs === undefined ? {} : { graceSecs: request.graceSecs }),
518
+ }
519
+ : request;
520
+ const outcome = await inner.ask(shaped);
521
+ if (outcome.kind === "timeout") return outcome;
522
+ const answer = outcome.answer;
523
+ if (shaped === request) return outcome;
524
+ const action = worktreeAnswer(answer.choice);
525
+ const actor = answer.actor === undefined ? {} : { actor: answer.actor };
526
+ if (action === "allow_once") {
527
+ return { kind: "answered", answer: { choice: "allow_once", ...actor } };
528
+ }
529
+ if (action === "allow_always" && person) {
530
+ if (call !== undefined) await rememberAlways(ctx, call, cwd);
531
+ return { kind: "answered", answer: { choice: "allow_always", ...actor } };
532
+ }
533
+ if (action === "worktree") {
534
+ // Opening a worktree keeps this call out of the main clone. The reply
535
+ // ends here; the worktree flow starts the answer again there.
536
+ chosen.run = true;
537
+ chosen.stop.abort();
538
+ throw new WorktreeChosen();
539
+ }
540
+ // Deny refuses as no did, and says why.
541
+ return { kind: "answered", answer: { choice: "reject_once", note: READ_ONLY_REFUSAL, ...actor } };
542
+ },
543
+ useGrant: (waitId) => inner.useGrant(waitId),
544
+ };
545
+ }
546
+
227
547
  /** What a late answer needs: the session, and no permission for the call. */
228
548
  function sessionOnly(resume: unknown): { readonly session: string } | null {
229
549
  if (isRecord(resume) && typeof resume.session === "string") {
@@ -273,6 +593,12 @@ export function imagesOf(pending: readonly Message[], harness: string, directory
273
593
  return images;
274
594
  }
275
595
 
596
+ /** The text a chat's first session starts with: the whole text, and its place alone. */
597
+ interface SessionContext {
598
+ readonly text: string;
599
+ readonly where: string;
600
+ }
601
+
276
602
  /** What a chat's `refresh` step gives back. */
277
603
  interface Live {
278
604
  readonly cwd: string;
@@ -280,6 +606,40 @@ interface Live {
280
606
  readonly skills: readonly string[];
281
607
  /** Servers the harness starts for the agent, by name, each as a command. */
282
608
  readonly mcpServers: Readonly<Record<string, JsonValue>>;
609
+ /** Whether the agent reads the owner's own configuration of that agent. */
610
+ readonly useOwnSettings: boolean;
611
+ /** A repository chat's starting text; a bot chat gives none. */
612
+ readonly context?: SessionContext | undefined;
613
+ /** Files put on the message as notes; a bot gives its memory index and instructions. */
614
+ readonly notes?: readonly NoteFile[] | undefined;
615
+ /** The level a chat that chose none starts at now; a bot gives its setting. */
616
+ readonly accessDefault?: AccessLevel | undefined;
617
+ /** A plugin step to call after the round ends, when the chat's refresh step names one. */
618
+ readonly after?: string | undefined;
619
+ }
620
+
621
+ function sessionContextOf(value: unknown): SessionContext | undefined {
622
+ if (!isRecord(value) || typeof value.text !== "string" || typeof value.where !== "string") return undefined;
623
+ return { text: value.text, where: value.where };
624
+ }
625
+
626
+ /** The text to put before this round's prompt: the whole text for a new session, its place after a move. */
627
+ function contextFor(chat: ChatData, live: Live, session: string | undefined): string | undefined {
628
+ if (live.context === undefined) return undefined;
629
+ if (session === undefined) return live.context.text;
630
+ if (chat.contextCwd !== undefined && chat.contextCwd !== live.cwd) return live.context.where;
631
+ return undefined;
632
+ }
633
+
634
+ /** The context the last reply of this session ended with, when it reported one. */
635
+ function lastContextUsed(messages: readonly Message[], session: string | undefined): number | undefined {
636
+ if (session === undefined) return undefined;
637
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
638
+ const message = messages[index];
639
+ if (message?.role !== "assistant" || message.context === undefined) continue;
640
+ return message.session === session ? message.context.used : undefined;
641
+ }
642
+ return undefined;
283
643
  }
284
644
 
285
645
  /**
@@ -293,7 +653,13 @@ async function liveSettings(
293
653
  object: RunObject,
294
654
  runStep: NonNullable<StepContext["runStep"]>,
295
655
  ): Promise<Live | PluginStepResult> {
296
- const own: Live = { cwd: chat.cwd, access: chat.access, skills: chat.skills, mcpServers: {} };
656
+ const own: Live = {
657
+ cwd: chat.cwd,
658
+ access: chat.access,
659
+ skills: chat.skills,
660
+ mcpServers: {},
661
+ useOwnSettings: false,
662
+ };
297
663
  if (chat.refresh === undefined) return own;
298
664
  if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(chat.refresh)) {
299
665
  return failed("settings", `"${chat.refresh}", which gives this chat's settings, is not loaded`);
@@ -311,11 +677,20 @@ async function liveSettings(
311
677
  if (typeof data.cwd !== "string" || data.cwd.length === 0 || !isRecord(data.access) || !Array.isArray(data.skills)) {
312
678
  return failed("settings", "the chat's settings came back in a shape the chat cannot use");
313
679
  }
680
+ const context = sessionContextOf(data.context);
681
+ const notes = noteFilesOf(data.notes);
682
+ const after = typeof data.after === "string" && data.after.length > 0 ? data.after : undefined;
683
+ const accessDefault = isAccessLevel(data.accessDefault) ? data.accessDefault : undefined;
314
684
  return {
685
+ ...(accessDefault === undefined ? {} : { accessDefault }),
315
686
  cwd: data.cwd,
316
687
  access: data.access as Record<string, JsonValue>,
317
688
  skills: data.skills.filter((item): item is string => typeof item === "string"),
318
689
  mcpServers: isRecord(data.mcpServers) ? (data.mcpServers as Record<string, JsonValue>) : {},
690
+ useOwnSettings: data.useOwnSettings === true,
691
+ ...(context === undefined ? {} : { context }),
692
+ ...(notes === undefined ? {} : { notes }),
693
+ ...(after === undefined ? {} : { after }),
319
694
  };
320
695
  }
321
696
 
@@ -332,9 +707,27 @@ export function withAttachmentReads(
332
707
  return { ...access, readPaths: [...own, directory] };
333
708
  }
334
709
 
710
+ /**
711
+ * The profile with the chat's own directory denied: its live-level file is
712
+ * written by `chat:access`, never by the agent, at any level.
713
+ */
714
+ export function withLevelFileDeny(
715
+ access: Readonly<Record<string, JsonValue>>,
716
+ levelPath: string,
717
+ ): Readonly<Record<string, JsonValue>> {
718
+ const directory = dirname(levelPath);
719
+ const denied = Array.isArray(access.denyPaths)
720
+ ? access.denyPaths.filter((entry): entry is string => typeof entry === "string")
721
+ : [];
722
+ return denied.includes(directory) ? access : { ...access, denyPaths: [...denied, directory] };
723
+ }
724
+
335
725
  /** How much of a tool call's output a fact keeps; the rest goes to a file. */
336
726
  export const TOOL_OUTPUT_FACT_BYTES = 4 * 1024;
337
727
 
728
+ /** The longest failure line a transcript shows; the provider's message is cut to this. */
729
+ export const REPLY_FAILURE_MAX = 300;
730
+
338
731
  /** Cuts text to a byte count without splitting a character. */
339
732
  function cutUtf8(text: string, maxBytes: number): string {
340
733
  const bytes = new TextEncoder().encode(text);
@@ -357,27 +750,38 @@ export function toolOutputPath(home: string, chat: string, runId: string, callId
357
750
  /** The chat's own secret values, so nothing recorded or written can carry one. */
358
751
  export async function secretValues(ctx: Pick<StepContext, "secrets">): Promise<readonly string[]> {
359
752
  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;
753
+ return await ctx.secrets.values();
366
754
  } catch {
367
755
  return [];
368
756
  }
369
757
  }
370
758
 
759
+ /** What the transcript says when a crash, stop or restart interrupted a reply. */
760
+ export const INTERRUPTED_NOTE = "The reply was stopped before it finished.";
761
+
762
+ /** One entry as `recordEntries` records it: a folded entry or a stopped line. */
763
+ type RecordedEntry =
764
+ | FoldEntry
765
+ | { readonly kind: "stopped"; readonly text: string; readonly interrupted?: true };
766
+
371
767
  /** The entries to record: what finished, and the reply a stopped run got only half way through. */
372
768
  function entriesToRecord(
373
769
  folded: FoldState,
374
- options: { readonly finalText?: string | undefined; readonly stopped: boolean },
770
+ options: {
771
+ readonly finalText?: string | undefined;
772
+ readonly stopped: boolean;
773
+ readonly interrupted?: boolean | undefined;
774
+ },
375
775
  secrets: readonly string[],
376
- ): readonly (FoldEntry | { readonly kind: "stopped"; readonly text: string })[] {
377
- const entries: (FoldEntry | { readonly kind: "stopped"; readonly text: string })[] = [...folded.entries];
776
+ ): readonly RecordedEntry[] {
777
+ const entries: RecordedEntry[] = [...folded.entries];
378
778
  // What is still only an increment is not an entry. A stopped run keeps the
379
779
  // text it got half way through; finished text and thinking are already above.
380
780
  if (options.stopped && folded.text.length > 0) entries.push({ kind: "stopped", text: folded.text });
781
+ // A recovered reply gets one line of its own, even when it wrote no text.
782
+ if (options.interrupted === true) {
783
+ entries.push({ kind: "stopped", text: INTERRUPTED_NOTE, interrupted: true });
784
+ }
381
785
  // The final reply is a chat.message of its own; its text is not an entry too.
382
786
  if (options.finalText !== undefined) {
383
787
  const final = options.finalText.trim();
@@ -398,11 +802,17 @@ async function entryData(
398
802
  ctx: StepContext,
399
803
  chat: string,
400
804
  runId: string,
401
- entry: FoldEntry | { readonly kind: "stopped"; readonly text: string },
805
+ entry: RecordedEntry,
402
806
  secrets: readonly string[],
403
807
  ): Promise<EntryData> {
404
808
  if (entry.kind !== "tool") {
405
- return { runId, kind: entry.kind, text: maskSecrets(entry.text, secrets) };
809
+ return {
810
+ runId,
811
+ kind: entry.kind,
812
+ text: maskSecrets(entry.text, secrets),
813
+ ...(entry.kind === "stopped" && entry.interrupted === true ? { interrupted: true } : {}),
814
+ ...(entry.kind === "stopped" || entry.at === undefined ? {} : { startedAt: entry.at }),
815
+ };
406
816
  }
407
817
  const output = entry.output === null ? null : maskSecrets(entry.output, secrets);
408
818
  const data: EntryData = {
@@ -441,14 +851,19 @@ async function recordEntries(
441
851
  ctx: StepContext,
442
852
  chat: string,
443
853
  folded: FoldState,
444
- options: { readonly finalText?: string | undefined; readonly stopped: boolean },
854
+ options: {
855
+ readonly finalText?: string | undefined;
856
+ readonly stopped: boolean;
857
+ readonly interrupted?: boolean | undefined;
858
+ },
445
859
  ): Promise<void> {
446
860
  const secrets = await secretValues(ctx);
447
861
  const wanted = entriesToRecord(folded, options, secrets);
448
862
  if (wanted.length === 0) return;
449
- const existing = allEntries(ctx.store, chat);
863
+ const read = readChat(ctx.store, chat);
864
+ const existing = read.entries;
450
865
  const lastReply = new Map<string, number>();
451
- for (const message of allMessages(ctx.store, chat)) {
866
+ for (const message of read.messages) {
452
867
  if (message.role !== "assistant" || message.runId === undefined) continue;
453
868
  lastReply.set(message.runId, Math.max(lastReply.get(message.runId) ?? 0, message.sequence));
454
869
  }
@@ -484,17 +899,377 @@ async function recordEntries(
484
899
  }
485
900
  }
486
901
 
902
+ /**
903
+ * The user's word for a provider's internal name. Only `harness` is rewritten:
904
+ * `run`, `step`, `flow` and `fact` are also ordinary English, and a provider's
905
+ * "run out of quota" must stay as it said it.
906
+ */
907
+ const PLAIN_WORDS: Readonly<Record<string, readonly [string, string]>> = {
908
+ harness: ["agent", "agents"],
909
+ };
910
+
911
+ /** Replaces an internal word in a provider's message with the word a person reads. */
912
+ function plainWords(text: string): string {
913
+ return text.replace(/\b(harness)(es)?\b/gi, (word, base: string, plural: string | undefined) => {
914
+ const pair = PLAIN_WORDS[base.toLowerCase()];
915
+ if (pair === undefined) return word;
916
+ const replacement = plural === undefined ? pair[0] : pair[1];
917
+ return word[0] === word[0]?.toUpperCase() ? `${replacement[0]?.toUpperCase() ?? ""}${replacement.slice(1)}` : replacement;
918
+ });
919
+ }
920
+
921
+ /** One plain line saying a reply failed, with the provider's message masked and cut short. */
922
+ export function replyFailureLine(message: string, secrets: readonly string[]): string {
923
+ const detail = plainWords(maskSecrets(message, secrets).replace(/\s+/g, " ").trim());
924
+ const line = detail.length === 0 ? "The reply failed." : `The reply failed: ${detail}`;
925
+ return line.length <= REPLY_FAILURE_MAX ? line : `${line.slice(0, REPLY_FAILURE_MAX - 1)}…`;
926
+ }
927
+
928
+ /**
929
+ * Why an empty reply ended, in plain words. A reply with no text but with usage
930
+ * reached the model; one with neither ended without calling it, and the agent's
931
+ * own message is the reason it gives.
932
+ */
933
+ function emptyReplyMessage(data: Readonly<Record<string, unknown>>): string {
934
+ const usage = usageOf(data.usage);
935
+ if (usage.tokens !== undefined || usage.costMicros !== undefined) return "the agent gave no reply";
936
+ const ended = "the agent ended without answering and without calling the model";
937
+ const reason = typeof data.message === "string" ? data.message.replace(/\s+/g, " ").trim() : "";
938
+ return reason.length === 0 ? ended : `${ended} (${reason})`;
939
+ }
940
+
941
+ /** How many empty failures in a row after `after` are for `oldest`; another failure or a stop ends the run. */
942
+ function emptyFailureStreak(entries: readonly Entry[], after: number, oldest: string): number {
943
+ let count = 0;
944
+ for (const entry of entries) {
945
+ if (entry.sequence <= after) continue;
946
+ if (entry.kind === "stopped") {
947
+ count = 0;
948
+ } else if (entry.kind === "failure") {
949
+ if (entry.reason === "empty" && entry.messageId === oldest) count += 1;
950
+ else count = 0;
951
+ }
952
+ }
953
+ return count;
954
+ }
955
+
956
+ /**
957
+ * Records a failure as one entry after the last person's message or reply. A
958
+ * rerun of the same run finds its failure and does not add another, even when
959
+ * the provider words it differently; every other failed run records its own,
960
+ * so a retried attempt that fails again does not leave the chat looking like
961
+ * it is still writing.
962
+ *
963
+ * An empty failure twice in a row for the same oldest message marks that
964
+ * message taken, so a message the agent never answers is not sent forever.
965
+ */
966
+ async function recordFailure(
967
+ ctx: StepContext,
968
+ chat: string,
969
+ reason: string,
970
+ message: string,
971
+ oldest?: string | undefined,
972
+ ): Promise<void> {
973
+ const text = replyFailureLine(message, await secretValues(ctx));
974
+ const read = readChat(ctx.store, chat);
975
+ let lastReply = 0;
976
+ for (const item of read.messages) {
977
+ if (item.role === "user") continue;
978
+ lastReply = Math.max(lastReply, item.sequence);
979
+ }
980
+ const recorded = read.entries.some(
981
+ (entry) => entry.kind === "failure" && entry.runId === ctx.runId,
982
+ );
983
+ if (!recorded) {
984
+ const data: EntryData = {
985
+ runId: ctx.runId,
986
+ kind: "failure",
987
+ text,
988
+ reason,
989
+ ...(oldest === undefined ? {} : { messageId: oldest }),
990
+ };
991
+ await ctx.facts.append({ type: ENTRY_FACT, object: chatRef(chat), data });
992
+ }
993
+ if (reason !== "empty" || oldest === undefined) return;
994
+ const streak = emptyFailureStreak(readChat(ctx.store, chat).entries, lastReply, oldest);
995
+ if (streak >= 2) await recordTaken(ctx, chat, ctx.runId, [oldest]);
996
+ }
997
+
998
+ /**
999
+ * Records messages an attempt took before it ended without a reply message, so
1000
+ * a later round does not give them to the agent again.
1001
+ */
1002
+ async function recordTaken(ctx: StepContext, chat: string, runId: string, ids: readonly string[]): Promise<void> {
1003
+ if (ids.length === 0) return;
1004
+ const facts = readChat(ctx.store, chat).facts;
1005
+ const seen = new Set(facts.flatMap((fact) => answeredOfFact(fact)));
1006
+ const fresh = ids.filter((id) => !seen.has(id));
1007
+ if (fresh.length === 0) return;
1008
+ await ctx.facts.append({
1009
+ type: ANSWER_FACT,
1010
+ object: chatRef(chat),
1011
+ data: { runId, ids: fresh },
1012
+ });
1013
+ }
1014
+
1015
+ /** Ends a reply as failed, after recording why in the chat. */
1016
+ async function failedReply(
1017
+ ctx: StepContext,
1018
+ chat: string,
1019
+ reason: string,
1020
+ message: string,
1021
+ oldest?: string | undefined,
1022
+ ): Promise<PluginStepResult> {
1023
+ await recordFailure(ctx, chat, reason, message, oldest);
1024
+ return failed(reason, message);
1025
+ }
1026
+
1027
+ /** The reason and message a failed step result carries. */
1028
+ function failureOf(result: PluginStepResult): { readonly reason: string; readonly message: string } {
1029
+ const data = isRecord(result.data) ? result.data : {};
1030
+ return {
1031
+ reason: typeof data.reason === "string" ? data.reason : "harness",
1032
+ message: typeof data.message === "string" ? data.message : `the agent ended "${result.result}"`,
1033
+ };
1034
+ }
1035
+
1036
+ /**
1037
+ * The inbox a chat passes to a harness that takes messages mid-run. It keeps
1038
+ * what arrives until the harness listens, then hands everything on in order,
1039
+ * and records only the messages the harness actually took. A take and a change
1040
+ * of the same message take the chat's queue lock in turn, so exactly one wins.
1041
+ * A message still waiting when the run ends is left for the next round.
1042
+ */
1043
+ interface ReplyInbox {
1044
+ readonly inbox: MessageInbox;
1045
+ send(id: string): void;
1046
+ /** The ids of the messages handed to the harness, in arrival order. */
1047
+ readonly handed: readonly string[];
1048
+ close(): Promise<void>;
1049
+ }
1050
+
1051
+ type Handed = "taken" | "left" | "wait";
1052
+
1053
+ function replyInbox(
1054
+ ctx: StepContext,
1055
+ chat: string,
1056
+ runId: string,
1057
+ skills: ReturnType<typeof readSkills>,
1058
+ loadsSkills: boolean,
1059
+ ): ReplyInbox {
1060
+ let listener: ((text: string) => boolean | void) | undefined;
1061
+ const waiting: string[] = [];
1062
+ const handed: string[] = [];
1063
+ let open = true;
1064
+ let pumping: Promise<void> | undefined;
1065
+
1066
+ const deliver = async (id: string): Promise<Handed> => {
1067
+ await queueTestHooks.beforeTake?.(id);
1068
+ return withQueueLock(ctx.home, chat, async () => {
1069
+ if (!open || listener === undefined) return "wait";
1070
+ const read = readChat(ctx.store, chat);
1071
+ if (takenIds(read.facts).has(id)) return "left";
1072
+ const message = read.messages.find((item) => item.id === id);
1073
+ if (message === undefined || message.role !== "user") return "left";
1074
+ if (listener(skillMessage(message.text, skills, loadsSkills)) === false) return "left";
1075
+ await takeLocked(ctx.store, ctx.facts, chat, runId, [id], "step:chat/reply", read);
1076
+ return "taken";
1077
+ });
1078
+ };
1079
+
1080
+ const pump = (): Promise<void> => {
1081
+ if (pumping !== undefined) return pumping;
1082
+ const task = Promise.resolve().then(async () => {
1083
+ try {
1084
+ while (open && listener !== undefined && waiting.length > 0) {
1085
+ const id = waiting[0];
1086
+ if (id === undefined) break;
1087
+ let outcome: Handed;
1088
+ try {
1089
+ outcome = await deliver(id);
1090
+ } catch (error) {
1091
+ await ctx.logger.write(
1092
+ `a message could not be handed to the agent: ${messageOf(error)}`,
1093
+ );
1094
+ outcome = "left";
1095
+ }
1096
+ if (outcome === "wait") break;
1097
+ if (waiting[0] === id) waiting.shift();
1098
+ if (outcome === "taken") handed.push(id);
1099
+ }
1100
+ } finally {
1101
+ pumping = undefined;
1102
+ if (open && listener !== undefined && waiting.length > 0) void pump();
1103
+ }
1104
+ });
1105
+ pumping = task;
1106
+ return task;
1107
+ };
1108
+
1109
+ return {
1110
+ inbox: {
1111
+ listen(next) {
1112
+ listener = next;
1113
+ void pump();
1114
+ return () => {
1115
+ if (listener === next) listener = undefined;
1116
+ };
1117
+ },
1118
+ },
1119
+ send(id) {
1120
+ if (!open) return;
1121
+ waiting.push(id);
1122
+ void pump();
1123
+ },
1124
+ handed,
1125
+ async close() {
1126
+ open = false;
1127
+ listener = undefined;
1128
+ waiting.length = 0;
1129
+ await pumping;
1130
+ },
1131
+ };
1132
+ }
1133
+
1134
+ /** Records that the reply step returned on its own, before its result enters the log. */
1135
+ async function recordAttemptEnd(ctx: StepContext, chat: string): Promise<void> {
1136
+ await ctx.facts.append({
1137
+ type: ATTEMPT_END_FACT,
1138
+ object: chatRef(chat),
1139
+ data: { runId: ctx.runId },
1140
+ });
1141
+ }
1142
+
1143
+ /**
1144
+ * Runs after a reply step a crash, stop or restart interrupted. It reads the
1145
+ * log the agent wrote and records the entries it finished, the half-written
1146
+ * text and one line saying the reply stopped, so `/retry` can continue the
1147
+ * chat from what was kept. A step that returned `interrupted` on its own
1148
+ * already recorded those and left its attempt fact, so this adds nothing.
1149
+ */
1150
+ export async function keepInterrupted(ctx: StepContext, _params: unknown): Promise<PluginStepResult> {
1151
+ const object = ctx.object;
1152
+ if (object === undefined || object.type !== CHAT_TYPE) {
1153
+ return failed("object", "chat:reply runs on a chat");
1154
+ }
1155
+ const stored = await ctx.store.get(CHAT_TYPE, object.id);
1156
+ if (stored === undefined) return { result: "done", data: {} };
1157
+ const chatRead = readChat(ctx.store, object.id);
1158
+ const messages = chatRead.messages;
1159
+ const facts = chatRead.facts;
1160
+ const pending = unanswered(messages, facts);
1161
+ const replied = messages.some((message) => message.role === "assistant" && message.runId === ctx.runId);
1162
+ if (replied && pending.length === 0) {
1163
+ // The reply entered the record before the crash and owes no message: there is nothing to mark.
1164
+ await syncChat(ctx, object.id, undefined);
1165
+ return { result: "done", data: { kept: false } };
1166
+ }
1167
+ if (facts.some((fact) => attemptEndedOfFact(fact) === ctx.runId)) {
1168
+ // The reply step ended on its own and recorded its entries first.
1169
+ return { result: "done", data: { kept: false } };
1170
+ }
1171
+ const chat = chatData(stored.data);
1172
+ const read = foldLogTail(agentLogPath(ctx.store.root, chat.harness, ctx.runId));
1173
+ const folded = read?.state ?? emptyFold;
1174
+ // The log holds every round of the run; a round whose reply is already in
1175
+ // the record is a prefix of it and is not recorded again.
1176
+ const prior = chatRead.entries.filter((entry) => entry.runId === ctx.runId).length;
1177
+ const current = prior === 0 ? folded : { ...folded, entries: folded.entries.slice(prior) };
1178
+ await recordEntries(ctx, object.id, current, { stopped: true, interrupted: true });
1179
+ // A run that ended on its own is recorded by its last round; one that was
1180
+ // stopped after writing still gets its changes recorded here.
1181
+ await runAfterStep(ctx, await afterStepOfRefresh(ctx, chat, object), object, "done");
1182
+ return { result: "done", data: { kept: true } };
1183
+ }
1184
+
1185
+ /**
1186
+ * Runs the step a chat's refresh data names after a round, once the round is
1187
+ * over. A plugin uses it to record what the round wrote (the memory plugin's
1188
+ * commit). A failure is logged, never put in the chat: the answer is already
1189
+ * written, and remembering it must not undo the answer.
1190
+ */
1191
+ async function runAfterStep(ctx: StepContext, step: string | undefined, object: RunObject, result: string | undefined): Promise<void> {
1192
+ if (step === undefined) return;
1193
+ if (result !== undefined && result !== "done" && result !== "failed") return;
1194
+ const runStep = ctx.runStep;
1195
+ if (runStep === undefined) return;
1196
+ if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(step)) {
1197
+ ctx.logger.write(`after ${step}: the step is not loaded\n`);
1198
+ return;
1199
+ }
1200
+ try {
1201
+ const outcome = await runStep(step, { chat: object.id }, { runId: ctx.runId, object, params: ctx.params, signal: ctx.signal });
1202
+ if (outcome.result !== "done") {
1203
+ const message = isRecord(outcome.data) && typeof outcome.data.message === "string" ? outcome.data.message : `it ended ${outcome.result}`;
1204
+ ctx.logger.write(`after ${step}: ${message}\n`);
1205
+ }
1206
+ } catch (error) {
1207
+ ctx.logger.write(`after ${step}: ${messageOf(error)}\n`);
1208
+ }
1209
+ }
1210
+
1211
+ /** The after step a chat's refresh step names now, read for a run that ended without a round. */
1212
+ async function afterStepOfRefresh(ctx: StepContext, chat: ChatData, object: RunObject): Promise<string | undefined> {
1213
+ if (chat.refresh === undefined) return undefined;
1214
+ const runStep = ctx.runStep;
1215
+ if (runStep === undefined) return undefined;
1216
+ if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(chat.refresh)) return undefined;
1217
+ try {
1218
+ const outcome = await runStep(chat.refresh, { chat: object.id }, { runId: ctx.runId, object, params: ctx.params, signal: ctx.signal });
1219
+ const data = isRecord(outcome.data) ? outcome.data : {};
1220
+ return outcome.result === "done" && typeof data.after === "string" && data.after.length > 0 ? data.after : undefined;
1221
+ } catch {
1222
+ return undefined;
1223
+ }
1224
+ }
1225
+
1226
+ /** What one round leaves for the work after it: the after step, and the note hashes it records. */
1227
+ interface ReplyState {
1228
+ after?: string | undefined;
1229
+ keepNotes?: (() => Promise<void>) | undefined;
1230
+ }
1231
+
487
1232
  /** Runs one round of an answer; see the file's comment. */
488
1233
  export async function runReply(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
1234
+ const state: ReplyState = {};
1235
+ let result: string | undefined;
1236
+ try {
1237
+ const outcome = await replyOnce(ctx, params, state);
1238
+ result = outcome.result;
1239
+ return outcome;
1240
+ } finally {
1241
+ const object = ctx.object;
1242
+ if (object !== undefined) {
1243
+ await runAfterStep(ctx, state.after, object, result);
1244
+ if (state.keepNotes !== undefined) {
1245
+ try {
1246
+ await state.keepNotes();
1247
+ } catch (error) {
1248
+ await ctx.logger.write(
1249
+ `the note hashes could not be recorded: ${messageOf(error)}\n`,
1250
+ );
1251
+ }
1252
+ }
1253
+ }
1254
+ }
1255
+ }
1256
+
1257
+ /** One round of an answer, before the after step runs. */
1258
+ async function replyOnce(
1259
+ ctx: StepContext,
1260
+ params: unknown,
1261
+ state: ReplyState,
1262
+ ): Promise<PluginStepResult> {
489
1263
  const object = ctx.object;
490
1264
  if (object === undefined || object.type !== CHAT_TYPE) {
491
1265
  return failed("object", "chat:reply runs on a chat");
492
1266
  }
493
1267
  const stored = await ctx.store.get(CHAT_TYPE, object.id);
494
1268
  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);
1269
+ let chat = chatData(stored.data);
1270
+ const read = readChat(ctx.store, object.id);
1271
+ let messages = read.messages;
1272
+ let pending = unanswered(messages, read.facts);
498
1273
  if (pending.length === 0) {
499
1274
  // A run that stopped after recording a reply still owes the chat its model and cost.
500
1275
  await syncChat(ctx, object.id, undefined);
@@ -502,70 +1277,207 @@ export async function runReply(ctx: StepContext, params: unknown): Promise<Plugi
502
1277
  }
503
1278
 
504
1279
  const runStep = ctx.runStep;
505
- if (runStep === undefined) return failed("host", "the kernel did not offer a way to run the agent");
1280
+ const oldest = pending[0]?.id;
1281
+ if (runStep === undefined) return failedReply(ctx, object.id, "host", "the agent could not be started", oldest);
506
1282
  const use = `${chat.harness}/agent`;
507
1283
  if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(use)) {
508
- return failed("harness", `the agent "${chat.harness}" is not loaded`);
1284
+ return failedReply(ctx, object.id, "harness", `the agent "${chat.harness}" is not loaded`, oldest);
509
1285
  }
510
1286
 
511
1287
  // 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}"`);
1288
+ // A harness that has not read its list yet gets one refresh to answer, so a
1289
+ // first reply is not refused only because the list was not there at load.
1290
+ if (chat.model !== undefined) {
1291
+ const models =
1292
+ ctx.harnessModelsReady !== undefined
1293
+ ? await ctx.harnessModelsReady(chat.harness)
1294
+ : ctx.harnessModels?.(chat.harness);
1295
+ if (!modelIds(models).includes(chat.model)) {
1296
+ return failedReply(ctx, object.id, "model", `the agent "${chat.harness}" cannot use the model "${chat.model}"`, oldest);
1297
+ }
514
1298
  }
515
- // The same for an effort: the agent's list is the only one that can take it.
1299
+ // The same for an effort: the agent's list is the only one that can take the
1300
+ // effort the chat chose; one equal to its stored default is inherited.
516
1301
  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}"`);
1302
+ const effort = chosenEffort(chat);
1303
+ if (effort !== undefined && efforts?.list.includes(effort) !== true) {
1304
+ return failedReply(ctx, object.id, "effort", `the agent "${chat.harness}" cannot use the effort "${effort}"`, oldest);
519
1305
  }
520
1306
  const effortFlag = efforts?.flag ?? (chat.harness === "pi" ? "--thinking" : "--effort");
521
1307
 
522
1308
  const settled = await liveSettings(ctx, chat, object, runStep);
523
- if ("result" in settled) return settled;
1309
+ if ("result" in settled) {
1310
+ const why = failureOf(settled);
1311
+ return failedReply(ctx, object.id, why.reason, why.message, oldest);
1312
+ }
524
1313
  const live = settled;
1314
+ state.after = live.after;
1315
+ // A chat that never chose a level follows the level its plugin starts chats
1316
+ // at now, so changing that setting moves it; a chosen level stays.
1317
+ if (live.accessDefault !== undefined && !chat.accessChosen && (chat.accessDefault !== live.accessDefault || chat.accessLevel !== live.accessDefault)) {
1318
+ const fresh = await ctx.store.get(CHAT_TYPE, object.id);
1319
+ if (fresh !== undefined && !chatData(fresh.data).accessChosen) {
1320
+ const next = { ...fresh.data, accessLevel: live.accessDefault, accessDefault: live.accessDefault };
1321
+ await ctx.store.put(CHAT_TYPE, object.id, next, "step:chat/reply");
1322
+ chat = chatData(next);
1323
+ }
1324
+ }
1325
+ // The notes this message may carry: a bot's memory index and instructions. A
1326
+ // file that cannot be read is logged and left out; it never fails the answer.
1327
+ const noteContents =
1328
+ live.notes === undefined
1329
+ ? []
1330
+ : await readNoteFiles(live.notes, live.cwd, (problem) => {
1331
+ void ctx.logger.write(`${problem}\n`);
1332
+ });
1333
+ // A level reaches the harness only through an agent that declares it can
1334
+ // carry it; an agent that cannot refuses the reply by name, never ignores it.
1335
+ const level = chat.accessLevel ?? "ask";
1336
+ const capabilities = ctx.harnessCapabilities?.(chat.harness);
1337
+ if (capabilities !== undefined && !(capabilities.accessLevels ?? []).includes(level)) {
1338
+ return failedReply(
1339
+ ctx,
1340
+ object.id,
1341
+ "access",
1342
+ `the agent "${chat.harness}" cannot carry the access level "${level}"`,
1343
+ oldest,
1344
+ );
1345
+ }
1346
+ const leveled = withAccessLevel(live.access, level);
1347
+ const skills = readSkills(live.skills);
1348
+ const loadsSkills = capabilities?.loadsSkills === true;
1349
+
1350
+ // A harness that takes messages mid-run is handed each ordinary message that
1351
+ // arrives while this round runs, after the tool calls already running. A
1352
+ // message with an attachment waits for the next round: the mid-run inbox
1353
+ // carries text, and its image or file reaches the agent as a first message does.
1354
+ const midRun =
1355
+ ctx.harnessCapabilities?.(chat.harness)?.takesMessagesMidRun === true
1356
+ ? replyInbox(ctx, object.id, ctx.runId, skills, loadsSkills)
1357
+ : undefined;
1358
+ const arrived = new Set<string>();
1359
+ let stopMidRun: (() => void) | undefined;
1360
+ if (midRun !== undefined) {
1361
+ const inbox = midRun;
1362
+ stopMidRun = ctx.store.subscribe(chatRef(object.id), {}, (fact) => {
1363
+ if (fact.type !== MESSAGE_FACT) return;
1364
+ const data = fact.data;
1365
+ if (data.role !== "user" || typeof data.id !== "string" || typeof data.text !== "string") return;
1366
+ arrived.add(data.id);
1367
+ if (attachmentsOf(data.attachments).length === 0) inbox.send(data.id);
1368
+ });
1369
+ // A message that came between the first read and this subscription is in
1370
+ // the facts now. It is delivered, not also put into the prompt.
1371
+ const fresh = readChat(ctx.store, object.id);
1372
+ messages = fresh.messages;
1373
+ pending = unanswered(messages, fresh.facts).filter((message) => !arrived.has(message.id));
1374
+ }
1375
+
1376
+ const closeMidRun = async (): Promise<void> => {
1377
+ if (stopMidRun !== undefined) {
1378
+ stopMidRun();
1379
+ stopMidRun = undefined;
1380
+ }
1381
+ await midRun?.close();
1382
+ };
525
1383
 
526
1384
  const resumed = isRecord(params) ? params : {};
527
1385
  const session =
528
1386
  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;
1387
+ // The context the last reply in this session ended with; a smaller one after
1388
+ // this reply means the agent compacted the session.
1389
+ const previousUsed = lastContextUsed(messages, session);
1390
+ const readOnly = leveled.readOnly === true;
1391
+ // The worktree question belongs to a repository chat; a bot chat at `plan`
1392
+ // is read-only without one.
1393
+ const worktreeChat = readOnly && (chat.parent === undefined || chat.parent.startsWith("repo:"));
1394
+ const worktreeChosen = { run: false, stop: new AbortController() };
1395
+ // The live file holds the base profile; a level change rewrites only its level.
1396
+ let recheckBase: Readonly<Record<string, JsonValue>> = live.access;
1397
+ const withLevel = levelAsker(ctx, object.id, live.cwd, () => recheckBase, level, contextAsker(ctx));
1398
+ const asker = worktreeChat ? readOnlyAsker(ctx, live.cwd, worktreeChosen, withLevel) : withLevel;
1399
+ // A worktree yes aborts `stop`, so the harness ends even if it swallows the
1400
+ // stop error; the reply still ends `done` below.
1401
+ const signal = worktreeChat ? AbortSignal.any([ctx.signal, worktreeChosen.stop.signal]) : ctx.signal;
541
1402
 
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.
1403
+ // An answer that came back after the wait (the grace had passed) is the same
1404
+ // answer as one given live.
544
1405
  const late = answeredQuestion(params);
545
- const lateWorktree = readOnly && late !== undefined && isWorktreeQuestion(late.prompt);
546
- if (lateWorktree && late.choice === "yes") {
1406
+ const lateWorktree = worktreeChat && late !== undefined && isWorktreeQuestion(late.prompt);
1407
+ const lateAction = lateWorktree && late !== undefined ? worktreeAnswer(late.choice) : undefined;
1408
+ const lateCall = lateWorktree ? callFromGrants(ctx.access) ?? callFromQuestion(late?.prompt ?? "") : undefined;
1409
+ if (lateAction === "worktree") {
1410
+ // The reply that asked is already over. Open the worktree once, but do
1411
+ // not start another reply for the same message. The harness is not run,
1412
+ // so the mid-run inbox closes with this step.
1413
+ await closeMidRun();
547
1414
  await ctx.emit({
548
1415
  type: WORKTREE_EVENT,
549
- key: `${ctx.runId}:late`,
1416
+ key: "late",
550
1417
  object: `${CHAT_TYPE}:${object.id}`,
1418
+ data: { late: true },
551
1419
  });
1420
+ return { result: "done", data: { worktree: true } };
1421
+ }
1422
+ if (lateAction === "allow_always" && lateCall !== undefined && personStarted(ctx.trigger)) {
1423
+ await rememberAlways(ctx, lateCall, live.cwd);
552
1424
  }
553
1425
  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;
1426
+ lateAction === undefined
1427
+ ? resumed.askAnswer
1428
+ : {
1429
+ prompt: late?.prompt ?? "",
1430
+ choice:
1431
+ lateAction === "allow_once"
1432
+ ? "allow_once"
1433
+ : lateAction === "allow_always"
1434
+ ? "allow_always"
1435
+ : "reject_once",
1436
+ ...(lateAction === "deny"
1437
+ ? { note: late?.note === undefined ? READ_ONLY_REFUSAL : `${READ_ONLY_REFUSAL}\n${late.note}` }
1438
+ : {}),
1439
+ };
561
1440
 
562
1441
  // The files sent with a message: images as input where the harness takes
563
1442
  // them, every file as a path, and the chat's own attachment directory open to reads.
564
1443
  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)
1444
+ const levelPath = accessLevelPath(ctx.home, object.id);
1445
+ const withReads = messages.some((message) => message.attachments.length > 0)
567
1446
  ? withAttachmentReads(live.access, directory)
568
1447
  : live.access;
1448
+ const baseAccess = withLevelFileDeny(withReads, levelPath);
1449
+ recheckBase = baseAccess;
1450
+ const base = withAccessLevel(baseAccess, level);
1451
+ try {
1452
+ await writeLiveAccess(levelPath, baseAccess, level);
1453
+ } catch (error) {
1454
+ await ctx.logger.write(
1455
+ `the live access level could not be written: ${messageOf(error)}`,
1456
+ );
1457
+ }
1458
+ // A late Allow once is for this run alone; a late Always allow also wrote the user layer.
1459
+ const lateEntry =
1460
+ (lateAction === "allow_once" || lateAction === "allow_always") && lateCall !== undefined
1461
+ ? alwaysAllowEntry(lateCall, live.cwd)
1462
+ : undefined;
1463
+ const existing = Array.isArray(base.alwaysAllow) ? base.alwaysAllow : [];
1464
+ const access = {
1465
+ ...(lateEntry === undefined
1466
+ ? base
1467
+ : {
1468
+ ...base,
1469
+ alwaysAllow: [
1470
+ ...existing,
1471
+ {
1472
+ kind: lateEntry.kind,
1473
+ value: lateEntry.value,
1474
+ cwd: lateEntry.cwd,
1475
+ ...(lateEntry.tool === undefined ? {} : { tool: lateEntry.tool }),
1476
+ },
1477
+ ],
1478
+ }),
1479
+ levelFile: levelPath,
1480
+ };
569
1481
 
570
1482
  // The harness hands each log line over as it writes it; the fold keeps what
571
1483
  // is finished and what is still being written. None of this is stored until
@@ -581,32 +1493,77 @@ export async function runReply(ctx: StepContext, params: unknown): Promise<Plugi
581
1493
  folded = foldLines([value], folded);
582
1494
  };
583
1495
 
1496
+ // The messages this round starts with are taken now, under the queue lock,
1497
+ // so a withdraw or change either comes before the run takes them or is
1498
+ // refused. A message withdrawn after the first read leaves the prompt.
1499
+ let locked: ChatRead | undefined;
1500
+ pending = await withQueueLock(ctx.home, object.id, async () => {
1501
+ const latest = readChat(ctx.store, object.id);
1502
+ locked = latest;
1503
+ const current = unanswered(latest.messages, latest.facts).filter(
1504
+ (message) => !arrived.has(message.id),
1505
+ );
1506
+ await takeLocked(
1507
+ ctx.store,
1508
+ ctx.facts,
1509
+ object.id,
1510
+ ctx.runId,
1511
+ current.map((message) => message.id),
1512
+ "step:chat/reply",
1513
+ latest,
1514
+ );
1515
+ return current;
1516
+ });
1517
+ if (pending.length === 0) {
1518
+ await closeMidRun();
1519
+ await syncChat(ctx, object.id, undefined);
1520
+ return { result: "done", data: { answered: 0 } };
1521
+ }
1522
+ const images = imagesOf(pending, chat.harness, directory);
1523
+
584
1524
  // 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) {
1525
+ if (locked === undefined || latestRunOf(locked.facts) !== ctx.runId) {
586
1526
  await ctx.facts.append({ type: RUN_FACT, object: chatRef(object.id), data: { runId: ctx.runId } });
587
1527
  }
588
1528
 
1529
+ const context = contextFor(chat, live, session);
1530
+ const carried =
1531
+ live.notes === undefined ? [] : notesToAttach(noteContents, chat.noteHashes, session);
1532
+ const noteText = carried.length === 0 ? undefined : noteBlock(carried);
1533
+ const messagePrompt = promptFor(
1534
+ pending.map((message) => ({ ...message, text: skillMessage(message.text, skills, loadsSkills) })),
1535
+ new Set(images.map((image) => image.path)),
1536
+ );
1537
+ const prompt = [context, noteText, messagePrompt]
1538
+ .filter((part): part is string => part !== undefined && part.length > 0)
1539
+ .join("\n\n");
589
1540
  let outcome: PluginStepResult;
590
1541
  try {
591
1542
  outcome = await runStep(
592
1543
  use,
593
1544
  {
594
- prompt: promptFor(pending, new Set(images.map((image) => image.path))),
1545
+ prompt,
595
1546
  ...(images.length === 0 ? {} : { images }),
596
1547
  cwd: live.cwd,
597
- ...(chat.model === undefined && chat.effort === undefined
1548
+ ...(chat.model === undefined && effort === undefined
598
1549
  ? {}
599
1550
  : {
600
1551
  args: [
601
1552
  ...(chat.model === undefined ? [] : ["--model", chat.model]),
602
- ...(chat.effort === undefined ? [] : [effortFlag, chat.effort]),
1553
+ ...(effort === undefined ? [] : [effortFlag, effort]),
603
1554
  ],
604
1555
  }),
605
- ...(chat.effort === undefined ? {} : { effort: chat.effort }),
1556
+ ...(effort === undefined ? {} : { effort }),
606
1557
  ...(live.skills.length === 0 ? {} : { skills: live.skills }),
607
1558
  // Operad's own tools, so the agent never runs the `operad` command.
608
1559
  operadTools: { home: ctx.home },
1560
+ ...(midRun === undefined ? {} : { inbox: midRun.inbox }),
1561
+ ...(chat.harness === "pi" || chat.harness === "claude" ? { keepWorker: true } : {}),
1562
+ // A chat retries a failed model request with pi's own bounded backoff;
1563
+ // a task keeps pi's retry off and uses dev's own waits and fallbacks.
1564
+ ...(chat.harness === "pi" ? { retry: true } : {}),
609
1565
  ...(Object.keys(live.mcpServers).length === 0 ? {} : { mcpServers: live.mcpServers }),
1566
+ ...(live.useOwnSettings ? { useOwnSettings: true } : {}),
610
1567
  ...(session === undefined ? {} : { resumeSession: session }),
611
1568
  ...(askAnswer === undefined ? {} : { askAnswer }),
612
1569
  },
@@ -617,18 +1574,43 @@ export async function runReply(ctx: StepContext, params: unknown): Promise<Plugi
617
1574
  params: ctx.params,
618
1575
  access,
619
1576
  ...(ctx.trigger === undefined ? {} : { trigger: ctx.trigger }),
620
- signal: ctx.signal,
1577
+ signal,
621
1578
  receiver,
622
- ...(asker === undefined ? {} : { asker }),
1579
+ asker,
623
1580
  },
624
1581
  );
625
1582
  } catch (error) {
1583
+ await closeMidRun();
1584
+ if (worktreeChosen.run || error instanceof WorktreeChosen) {
1585
+ await recordEntries(ctx, object.id, folded, { stopped: true });
1586
+ await ctx.emit({
1587
+ type: WORKTREE_EVENT,
1588
+ key: "open",
1589
+ object: `${CHAT_TYPE}:${object.id}`,
1590
+ });
1591
+ return { result: "done", data: { worktree: true } };
1592
+ }
1593
+ await recordEntries(ctx, object.id, folded, { stopped: true });
1594
+ await recordTaken(ctx, object.id, ctx.runId, midRun?.handed ?? []);
1595
+ return failedReply(ctx, object.id, "harness", messageOf(error), oldest);
1596
+ }
1597
+ if (worktreeChosen.run) {
1598
+ await closeMidRun();
626
1599
  await recordEntries(ctx, object.id, folded, { stopped: true });
627
- return failed("harness", messageOf(error));
1600
+ await ctx.emit({
1601
+ type: WORKTREE_EVENT,
1602
+ key: "open",
1603
+ object: `${CHAT_TYPE}:${object.id}`,
1604
+ });
1605
+ return { result: "done", data: { worktree: true } };
628
1606
  }
1607
+ // From here on the harness can no longer take a message: one that arrives
1608
+ // now stays unanswered and is answered by the next round.
1609
+ await closeMidRun();
629
1610
 
630
1611
  if (outcome.result === "waiting") {
631
1612
  await recordEntries(ctx, object.id, folded, { stopped: true });
1613
+ await recordTaken(ctx, object.id, ctx.runId, midRun?.handed ?? []);
632
1614
  return { result: "waiting", ...(outcome.data === undefined ? {} : { data: outcome.data }) };
633
1615
  }
634
1616
  const data = isRecord(outcome.data) ? outcome.data : {};
@@ -639,27 +1621,39 @@ export async function runReply(ctx: StepContext, params: unknown): Promise<Plugi
639
1621
  }
640
1622
  if (outcome.result === "interrupted") {
641
1623
  await recordEntries(ctx, object.id, folded, { stopped: true });
1624
+ await recordTaken(ctx, object.id, ctx.runId, midRun?.handed ?? []);
1625
+ await recordAttemptEnd(ctx, object.id);
642
1626
  return { result: "interrupted", data };
643
1627
  }
644
1628
  if (outcome.result !== "done") {
645
1629
  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
- };
1630
+ await recordTaken(ctx, object.id, ctx.runId, midRun?.handed ?? []);
1631
+ const why = failureOf(outcome);
1632
+ return failedReply(ctx, object.id, why.reason, why.message, oldest);
653
1633
  }
654
1634
  const said = typeof data.finalMessage === "string" ? data.finalMessage.trim() : "";
655
1635
  const text = maskSecrets(said, await secretValues(ctx));
656
1636
  if (text.length === 0) {
657
1637
  await recordEntries(ctx, object.id, folded, { stopped: true });
658
- return failed("empty", "the agent gave no reply");
1638
+ await recordTaken(ctx, object.id, ctx.runId, midRun?.handed ?? []);
1639
+ return failedReply(ctx, object.id, "empty", emptyReplyMessage(data), oldest);
659
1640
  }
660
1641
  const sessionId = typeof data.sessionId === "string" && data.sessionId.length > 0 ? data.sessionId : undefined;
661
1642
 
662
1643
  const usage = usageOf(data.usage);
1644
+ const timings = timingsOf(data.timings);
1645
+ const replyContext = replyContextOf(data.context);
1646
+ // A session is compacted when the agent says so, or when this reply ended with
1647
+ // less context than the one before it in the same session. The next message
1648
+ // then carries every note whole again.
1649
+ const compacted =
1650
+ data.compacted === true ||
1651
+ (previousUsed !== undefined && replyContext !== undefined && replyContext.used < previousUsed);
1652
+ const windows = ctx.harnessModels?.(chat.harness)?.windows;
1653
+ const window =
1654
+ replyContext?.window ??
1655
+ (usage.model === undefined ? undefined : windows?.[usage.model]) ??
1656
+ (chat.model === undefined ? undefined : windows?.[chat.model]);
663
1657
 
664
1658
  await recordEntries(ctx, object.id, folded, { finalText: text, stopped: false });
665
1659
 
@@ -672,16 +1666,44 @@ export async function runReply(ctx: StepContext, params: unknown): Promise<Plugi
672
1666
  text,
673
1667
  attachments: [],
674
1668
  source: { kind: chat.harness, ref: null },
675
- replyTo: pending.map((message) => message.id),
1669
+ replyTo: [...pending.map((message) => message.id), ...(midRun?.handed ?? [])],
676
1670
  runId: ctx.runId,
677
1671
  ...(sessionId === undefined ? {} : { session: sessionId }),
678
1672
  ...usage,
1673
+ ...(replyContext === undefined
1674
+ ? {}
1675
+ : { context: { used: replyContext.used, ...(window === undefined ? {} : { window }) } }),
1676
+ ...(timings === undefined ? {} : { timings }),
679
1677
  };
680
1678
  await ctx.facts.append({ type: MESSAGE_FACT, object: chatRef(object.id), data: reply });
681
1679
 
682
1680
  // The chat's own reference follows; read again, so a change made meanwhile stays.
683
- await syncChat(ctx, object.id, sessionId);
1681
+ await syncChat(ctx, object.id, sessionId, live.context === undefined ? undefined : live.cwd);
1682
+ if (live.notes !== undefined) {
1683
+ const keptSession = sessionId ?? session;
1684
+ state.keepNotes = async () => {
1685
+ // Read after the after step, so a change that step wrote (the memory
1686
+ // commit removing an untrusted index line) is what the session now knows.
1687
+ const fresh = compacted
1688
+ ? []
1689
+ : await readNoteFiles(live.notes ?? [], live.cwd, (problem) => {
1690
+ void ctx.logger.write(`${problem}\n`);
1691
+ });
1692
+ // A file this run's own tool calls wrote is what the session knows now;
1693
+ // any other change during the run belongs to the next message.
1694
+ const written = compacted ? new Set<string>() : notesWrittenHere(noteContents, folded.entries);
1695
+ await syncChat(
1696
+ ctx,
1697
+ object.id,
1698
+ undefined,
1699
+ undefined,
1700
+ noteHashesAfter(noteContents, fresh, written, keptSession, compacted),
1701
+ );
1702
+ };
1703
+ }
684
1704
 
685
- const left = unanswered(allMessages(ctx.store, object.id));
686
- return { result: left.length > 0 ? "more" : "done", data: { answered: pending.length, left: left.length } };
1705
+ const leftRead = readChat(ctx.store, object.id);
1706
+ const left = unanswered(leftRead.messages, leftRead.facts);
1707
+ const answered = pending.length + (midRun?.handed.length ?? 0);
1708
+ return { result: left.length > 0 ? "more" : "done", data: { answered, left: left.length } };
687
1709
  }