@operad-io/chat 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/reply.ts CHANGED
@@ -7,7 +7,7 @@
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, 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";
10
+ import { AskTimeoutError, type AgentCompaction, attachmentDir, isRecord, messageOf, modelIds, safeFileName, type AskOutcome, type AskRecheck, type AskRequest, type ChoiceInfo, type CostQuality, type JsonValue, type PluginFact, type PluginStepResult, type RunObject, type StepAsker, type StepContext, type UsageTokens } from "@operad-io/engine";
11
11
  import { isAccessLevel, match, MCP_TOOL, withAccessLevel, writeLiveAccess, type AccessLevel } from "@operad-io/access-match";
12
12
  import {
13
13
  appendAlwaysAllow,
@@ -23,6 +23,7 @@ import {
23
23
  type MessageInbox,
24
24
  } from "@operad-io/harness-process";
25
25
  import { readSkills, skillMessage } from "./skills.ts";
26
+ import { SEGMENT_TITLE_FACT, titleDue, titleLine } from "./segments.ts";
26
27
  import {
27
28
  ACCESS_FACT,
28
29
  ACCESS_LEVEL_INFO,
@@ -31,8 +32,22 @@ import {
31
32
  answeredOfFact,
32
33
  attachmentsOf,
33
34
  ATTEMPT_END_FACT,
35
+ BRIEF_FACT,
36
+ briefDue,
37
+ briefToCarry,
38
+ deliveriesToCarry,
39
+ deliveryBlock,
34
40
  attemptEndedOfFact,
35
41
  chatFacts,
42
+ COMMAND_FACT,
43
+ COMPACT_AT,
44
+ COMPACT_FACT,
45
+ COMPACT_FLUSH,
46
+ CHAT_TOO_FULL_LINE,
47
+ chatTooFull,
48
+ stillFull,
49
+ compactRequested,
50
+ type CommandData,
36
51
  IMAGE_TYPES,
37
52
  chatData,
38
53
  chosenEffort,
@@ -42,9 +57,11 @@ import {
42
57
  type Entry,
43
58
  chatRef,
44
59
  currentSession,
60
+ startsAfterNew,
45
61
  ENTRY_FACT,
46
62
  latestRunOf,
47
63
  MESSAGE_FACT,
64
+ sessionHoldsPrivate,
48
65
  RUN_FACT,
49
66
  newMessageId,
50
67
  promptFor,
@@ -55,12 +72,13 @@ import {
55
72
  usageOf,
56
73
  worseQuality,
57
74
  timingsOf,
75
+ memoryShownOf,
58
76
  CHAT_TYPE,
59
77
  type EntryData,
60
78
  type Message,
61
79
  type MessageData,
62
80
  } from "./model.ts";
63
- import { noteBlock, noteFilesOf, noteHashesAfter, notesToAttach, notesWrittenHere, readNoteFiles, type NoteFile } from "./notes.ts";
81
+ import { earlierRecordPointer, memoryUsedBy, noteBlock, noteFilesOf, noteHashesAfter, notesToAttach, notesWrittenHere, readNoteFiles, type NoteFile } from "./notes.ts";
64
82
  import { queueTestHooks, syncQueuedLocked, takeLocked, withQueueLock } from "./queue.ts";
65
83
  import { agentLogPath, foldLogTail } from "./tail.ts";
66
84
 
@@ -87,7 +105,8 @@ async function syncChat(
87
105
  let costMissing = false;
88
106
  let tokens: UsageTokens | undefined;
89
107
  let tokensMissing = false;
90
- for (const message of readChat(ctx.store, id).messages) {
108
+ const recorded = readChat(ctx.store, id);
109
+ for (const message of recorded.messages) {
91
110
  if (message.role !== "assistant") continue;
92
111
  if (message.model !== undefined) next.lastModel = message.model;
93
112
  if (message.costMicros === undefined) costMissing = true;
@@ -105,6 +124,25 @@ async function syncChat(
105
124
  };
106
125
  }
107
126
  }
127
+ // The call that built a brief for a new session is paid like a reply.
128
+ for (const fact of recorded.facts) {
129
+ if ((fact.type !== BRIEF_FACT && fact.type !== SEGMENT_TITLE_FACT) || fact.data.called !== true) continue;
130
+ const usage = usageOf(fact.data.usage);
131
+ if (usage.costMicros === undefined) costMissing = true;
132
+ else {
133
+ micros = (micros ?? 0) + usage.costMicros;
134
+ quality = worseQuality(quality, usage.costQuality);
135
+ }
136
+ if (usage.tokens === undefined) tokensMissing = true;
137
+ else {
138
+ tokens = {
139
+ input: (tokens?.input ?? 0) + usage.tokens.input,
140
+ output: (tokens?.output ?? 0) + usage.tokens.output,
141
+ cacheread: (tokens?.cacheread ?? 0) + usage.tokens.cacheread,
142
+ cachewrite: (tokens?.cachewrite ?? 0) + usage.tokens.cachewrite,
143
+ };
144
+ }
145
+ }
108
146
  if (micros !== undefined) {
109
147
  next.costMicros = micros;
110
148
  next.costQuality = costMissing ? worseQuality(quality, "incomplete") : quality;
@@ -117,6 +155,213 @@ async function syncChat(
117
155
  }
118
156
  }
119
157
 
158
+ /** What the agent is asked when a new session needs a brief. */
159
+ const BRIEF_PROMPT = [
160
+ "Write a short brief of this conversation for a new session that continues the work toward the goal below.",
161
+ "Cover: what was decided, the files touched, the open questions, and the goal.",
162
+ "Plain text, at most 300 words. Do not use any tool and do not start the work; answer with the brief only.",
163
+ ].join("\n");
164
+
165
+ /** What the agent is asked to name a segment. */
166
+ const TITLE_PROMPT = [
167
+ "Give a title of at most six words for the conversation below. Plain text on one line, no quotes.",
168
+ "Do not use any tool; answer with the title only.",
169
+ ].join("\n");
170
+
171
+ /** How much of each side of the first exchange the title call is shown. */
172
+ const TITLE_SOURCE_CHARS = 1500;
173
+
174
+ /**
175
+ * Names the segment whose first exchange has just ended, when it has no title:
176
+ * one cheap call with the first question and answer, on the agent's background
177
+ * model when it declares one. The reply is already a fact when this runs, so the
178
+ * reader has it; only the end of the step waits for the call. A call that cannot
179
+ * be made, or fails, leaves the first words of the question as the title, so a
180
+ * segment is named once and the call is never repeated.
181
+ */
182
+ async function nameSegment(
183
+ ctx: StepContext,
184
+ object: RunObject,
185
+ chat: ChatData,
186
+ runStep: StepContext["runStep"],
187
+ read: ChatRead,
188
+ title: string,
189
+ ): Promise<void> {
190
+ const due = titleDue(read.facts, read.messages, title);
191
+ if (due === undefined) return;
192
+ let text = "";
193
+ let called = false;
194
+ let usage: ReturnType<typeof usageOf> = {};
195
+ if (runStep !== undefined && chat.harness.length > 0 && ctx.stepLoaded?.(`${chat.harness}/agent`) !== false) {
196
+ try {
197
+ const live = await liveSettings(ctx, chat, object, runStep);
198
+ if (!("result" in live)) {
199
+ called = true;
200
+ const model = ctx.harnessCapabilities?.(chat.harness)?.backgroundModel ?? chat.model;
201
+ const outcome = await runStep(
202
+ `${chat.harness}/agent`,
203
+ {
204
+ prompt: `${TITLE_PROMPT}\n\nQuestion:\n${due.question.slice(0, TITLE_SOURCE_CHARS)}\n\nAnswer:\n${due.answer.slice(0, TITLE_SOURCE_CHARS)}`,
205
+ cwd: live.cwd,
206
+ ...(model === undefined ? {} : { args: ["--model", model] }),
207
+ operadTools: { home: ctx.home },
208
+ },
209
+ {
210
+ runId: `${ctx.runId}.title`,
211
+ cwd: live.cwd,
212
+ object,
213
+ params: ctx.params,
214
+ access: withAccessLevel(live.access, "plan"),
215
+ ...(ctx.trigger === undefined ? {} : { trigger: ctx.trigger }),
216
+ signal: ctx.signal,
217
+ asker: contextAsker(ctx),
218
+ },
219
+ );
220
+ const data = isRecord(outcome.data) ? outcome.data : {};
221
+ usage = usageOf(data.usage);
222
+ const said = typeof data.finalMessage === "string" ? data.finalMessage : "";
223
+ if (outcome.result === "done") text = titleLine(maskSecrets(said, await secretValues(ctx)));
224
+ }
225
+ } catch {
226
+ text = "";
227
+ }
228
+ }
229
+ // The words of the question are a title that costs nothing.
230
+ const first = titleLine(due.question.split("\n").find((line) => line.trim().length > 0) ?? "");
231
+ await ctx.facts.append({
232
+ type: SEGMENT_TITLE_FACT,
233
+ object: chatRef(object.id),
234
+ data: {
235
+ segment: due.segment,
236
+ text: text.length > 0 ? text : first.length > 0 ? first : "…",
237
+ called,
238
+ generated: text.length > 0,
239
+ usage: {
240
+ ...(usage.model === undefined ? {} : { model: usage.model }),
241
+ ...(usage.costMicros === undefined ? {} : { costMicros: usage.costMicros, costQuality: usage.costQuality ?? "estimated" }),
242
+ ...(usage.tokens === undefined ? {} : { tokens: { ...usage.tokens } }),
243
+ },
244
+ },
245
+ });
246
+ // The call is paid like a reply: the chat's cost counts it now.
247
+ if (called) await syncChat(ctx, object.id, undefined);
248
+ }
249
+
250
+ /**
251
+ * Builds the brief a `/new <goal>` left due: one agent call that resumes the old
252
+ * session and writes the brief, recorded with its cost like a reply's. A call
253
+ * that cannot be made, or fails, leaves a brief with the goal alone and the
254
+ * reason; the new session is never held back by it.
255
+ */
256
+ async function makeBrief(
257
+ ctx: StepContext,
258
+ object: RunObject,
259
+ chat: ChatData,
260
+ runStep: NonNullable<StepContext["runStep"]>,
261
+ facts: readonly PluginFact[],
262
+ ): Promise<void> {
263
+ const due = briefDue(facts);
264
+ if (due === undefined) return;
265
+ const callId = `brief:${due.sequence}`;
266
+ const startedAt = Date.now();
267
+ let text = "";
268
+ let failedWhy: string | undefined;
269
+ let usage: ReturnType<typeof usageOf> = {};
270
+ const called = due.from !== undefined;
271
+ if (due.from !== undefined) {
272
+ try {
273
+ const live = await liveSettings(ctx, chat, object, runStep);
274
+ const use = `${chat.harness}/agent`;
275
+ if ("result" in live) failedWhy = failureOf(live).message;
276
+ else if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(use)) {
277
+ failedWhy = `the agent "${chat.harness}" is not loaded`;
278
+ } else {
279
+ const efforts = ctx.harnessEfforts?.(chat.harness);
280
+ const asked = chosenEffort(chat);
281
+ const effort = asked !== undefined && efforts?.list.includes(asked) === true ? asked : undefined;
282
+ const effortFlag = efforts?.flag ?? (chat.harness === "pi" ? "--thinking" : "--effort");
283
+ const outcome = await runStep(
284
+ use,
285
+ {
286
+ prompt: `${BRIEF_PROMPT}\n\nGoal: ${due.goal}`,
287
+ cwd: live.cwd,
288
+ ...(chat.model === undefined && effort === undefined
289
+ ? {}
290
+ : {
291
+ args: [
292
+ ...(chat.model === undefined ? [] : ["--model", chat.model]),
293
+ ...(effort === undefined ? [] : [effortFlag, effort]),
294
+ ],
295
+ }),
296
+ ...(effort === undefined ? {} : { effort }),
297
+ operadTools: { home: ctx.home },
298
+ resumeSession: due.from,
299
+ },
300
+ {
301
+ // Its own log: the reply's tail and entries read the run's log.
302
+ runId: `${ctx.runId}.brief`,
303
+ cwd: live.cwd,
304
+ object,
305
+ params: ctx.params,
306
+ access: withAccessLevel(live.access, "plan"),
307
+ ...(ctx.trigger === undefined ? {} : { trigger: ctx.trigger }),
308
+ signal: ctx.signal,
309
+ asker: contextAsker(ctx),
310
+ },
311
+ );
312
+ const data = isRecord(outcome.data) ? outcome.data : {};
313
+ usage = usageOf(data.usage);
314
+ const said = typeof data.finalMessage === "string" ? data.finalMessage.trim() : "";
315
+ if (outcome.result === "done" && said.length > 0) text = maskSecrets(said, await secretValues(ctx));
316
+ else failedWhy = outcome.result === "done" ? "the agent gave no brief" : failureOf(outcome).message;
317
+ }
318
+ } catch (error) {
319
+ failedWhy = messageOf(error);
320
+ }
321
+ }
322
+ const secrets = await secretValues(ctx);
323
+ const reason = failedWhy === undefined ? undefined : replyFailureLine(failedWhy, secrets);
324
+ // One line in the chat, the same kind as a tool call: it opens to the brief.
325
+ const known = readChat(ctx.store, object.id).entries.some((entry) => entry.callId === callId);
326
+ if (!known) {
327
+ const data = await entryData(
328
+ ctx,
329
+ object.id,
330
+ ctx.runId,
331
+ {
332
+ kind: "tool",
333
+ callId,
334
+ toolName: "/new",
335
+ input: due.goal,
336
+ result: reason === undefined ? "done" : "failed",
337
+ at: startedAt,
338
+ durationMs: Date.now() - startedAt,
339
+ output: text.length === 0 ? null : text,
340
+ outputTruncated: false,
341
+ error: reason ?? null,
342
+ },
343
+ secrets,
344
+ );
345
+ await ctx.facts.append({ type: ENTRY_FACT, object: chatRef(object.id), data });
346
+ }
347
+ await ctx.facts.append({
348
+ type: BRIEF_FACT,
349
+ object: chatRef(object.id),
350
+ data: {
351
+ goal: maskSecrets(due.goal, secrets),
352
+ text,
353
+ called,
354
+ ...(reason === undefined ? {} : { failed: reason }),
355
+ usage: {
356
+ ...(usage.model === undefined ? {} : { model: usage.model }),
357
+ ...(usage.costMicros === undefined ? {} : { costMicros: usage.costMicros, costQuality: usage.costQuality ?? "estimated" }),
358
+ ...(usage.tokens === undefined ? {} : { tokens: { ...usage.tokens } }),
359
+ },
360
+ },
361
+ });
362
+ await syncChat(ctx, object.id, undefined);
363
+ }
364
+
120
365
  /** The question a read-only chat asks when the call is not known. */
121
366
  export const WORKTREE_QUESTION =
122
367
  "The agent wants to change code, and this chat is read-only. Open a worktree for it?";
@@ -641,6 +886,8 @@ interface Live {
641
886
  readonly worktreeOffer?: boolean | undefined;
642
887
  /** A plugin step to call after the round ends, when the chat's refresh step names one. */
643
888
  readonly after?: string | undefined;
889
+ /** The directories that are the bot's memory; a stretch that is not remembered reads them and writes none. */
890
+ readonly memoryPaths?: readonly string[] | undefined;
644
891
  }
645
892
 
646
893
  function sessionContextOf(value: unknown): SessionContext | undefined {
@@ -706,7 +953,11 @@ async function liveSettings(
706
953
  const notes = noteFilesOf(data.notes);
707
954
  const after = typeof data.after === "string" && data.after.length > 0 ? data.after : undefined;
708
955
  const accessDefault = isAccessLevel(data.accessDefault) ? data.accessDefault : undefined;
956
+ const memoryPaths = Array.isArray(data.memoryPaths)
957
+ ? data.memoryPaths.filter((item): item is string => typeof item === "string" && item.length > 0)
958
+ : undefined;
709
959
  return {
960
+ ...(memoryPaths === undefined || memoryPaths.length === 0 ? {} : { memoryPaths }),
710
961
  ...(accessDefault === undefined ? {} : { accessDefault }),
711
962
  ...(data.worktreeOffer === false ? { worktreeOffer: false } : {}),
712
963
  cwd: data.cwd,
@@ -733,6 +984,27 @@ export function withAttachmentReads(
733
984
  return { ...access, readPaths: [...own, directory] };
734
985
  }
735
986
 
987
+ /**
988
+ * The profile with the bot's memory directories read-only: denied for writing,
989
+ * with a read path through the deny, as a wiki the bot may not write is. It is
990
+ * what keeps a stretch that is not remembered from writing a note, whatever
991
+ * the model is asked (ADR 0026 D23).
992
+ */
993
+ export function withMemoryReadOnly(
994
+ access: Readonly<Record<string, JsonValue>>,
995
+ directories: readonly string[],
996
+ ): Readonly<Record<string, JsonValue>> {
997
+ const strings = (value: JsonValue | undefined): string[] =>
998
+ Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === "string") : [];
999
+ const denied = strings(access.denyPaths);
1000
+ const readable = strings(access.readPaths);
1001
+ return {
1002
+ ...access,
1003
+ denyPaths: [...denied, ...directories.filter((path) => !denied.includes(path))],
1004
+ readPaths: [...readable, ...directories.filter((path) => !readable.includes(path))],
1005
+ };
1006
+ }
1007
+
736
1008
  /**
737
1009
  * The profile with the chat's own directory denied: its live-level file is
738
1010
  * written by `chat:access`, never by the agent, at any level.
@@ -1000,7 +1272,7 @@ async function recordFailure(
1000
1272
  const read = readChat(ctx.store, chat);
1001
1273
  let lastReply = 0;
1002
1274
  for (const item of read.messages) {
1003
- if (item.role === "user") continue;
1275
+ if (item.role === "user" || item.role === "recap") continue;
1004
1276
  lastReply = Math.max(lastReply, item.sequence);
1005
1277
  }
1006
1278
  const recorded = read.entries.some(
@@ -1038,6 +1310,11 @@ async function recordTaken(ctx: StepContext, chat: string, runId: string, ids: r
1038
1310
  });
1039
1311
  }
1040
1312
 
1313
+ /** Records that the session was compacted, and whether its context is still over the share of the window. */
1314
+ async function recordCompacted(ctx: StepContext, chat: string, full: boolean): Promise<void> {
1315
+ await ctx.facts.append({ type: COMPACT_FACT, object: chatRef(chat), data: { kind: "compacted", full, runId: ctx.runId } });
1316
+ }
1317
+
1041
1318
  /** Ends a reply as failed, after recording why in the chat. */
1042
1319
  async function failedReply(
1043
1320
  ctx: StepContext,
@@ -1214,26 +1491,34 @@ export async function keepInterrupted(ctx: StepContext, _params: unknown): Promi
1214
1491
  * commit). A failure is logged, never put in the chat: the answer is already
1215
1492
  * written, and remembering it must not undo the answer.
1216
1493
  */
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;
1494
+ async function runAfterStep(ctx: StepContext, step: string | undefined, object: RunObject, result: string | undefined): Promise<Readonly<Record<string, unknown>> | undefined> {
1495
+ if (step === undefined) return undefined;
1496
+ if (result !== undefined && result !== "done" && result !== "failed") return undefined;
1220
1497
  const runStep = ctx.runStep;
1221
- if (runStep === undefined) return;
1498
+ if (runStep === undefined) return undefined;
1222
1499
  if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(step)) {
1223
- ctx.logger.write(`after ${step}: the step is not loaded\n`);
1224
- return;
1500
+ await ctx.logger.write(`after ${step}: the step is not loaded\n`);
1501
+ return undefined;
1225
1502
  }
1226
1503
  try {
1227
1504
  const outcome = await runStep(step, { chat: object.id }, { runId: ctx.runId, object, params: ctx.params, signal: ctx.signal });
1228
1505
  if (outcome.result !== "done") {
1229
1506
  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`);
1507
+ await ctx.logger.write(`after ${step}: ${message}\n`);
1508
+ return undefined;
1231
1509
  }
1510
+ return isRecord(outcome.data) ? outcome.data : undefined;
1232
1511
  } catch (error) {
1233
- ctx.logger.write(`after ${step}: ${messageOf(error)}\n`);
1512
+ await ctx.logger.write(`after ${step}: ${messageOf(error)}\n`);
1513
+ return undefined;
1234
1514
  }
1235
1515
  }
1236
1516
 
1517
+ /** The notes an after step says it wrote: the `wrote` list of its data, each a file and a summary. */
1518
+ function wroteOf(data: Readonly<Record<string, unknown>> | undefined): readonly { readonly file: string; readonly summary: string }[] {
1519
+ return memoryShownOf({ wrote: data?.wrote })?.wrote ?? [];
1520
+ }
1521
+
1237
1522
  /** The after step a chat's refresh step names now, read for a run that ended without a round. */
1238
1523
  async function afterStepOfRefresh(ctx: StepContext, chat: ChatData, object: RunObject): Promise<string | undefined> {
1239
1524
  if (chat.refresh === undefined) return undefined;
@@ -1252,6 +1537,8 @@ async function afterStepOfRefresh(ctx: StepContext, chat: ChatData, object: RunO
1252
1537
  /** What one round leaves for the work after it: the after step, and the note hashes it records. */
1253
1538
  interface ReplyState {
1254
1539
  after?: string | undefined;
1540
+ /** Set once the after step ran before the reply was recorded, so the finally block does not run it twice. */
1541
+ afterRan?: boolean | undefined;
1255
1542
  keepNotes?: (() => Promise<void>) | undefined;
1256
1543
  }
1257
1544
 
@@ -1266,7 +1553,7 @@ export async function runReply(ctx: StepContext, params: unknown): Promise<Plugi
1266
1553
  } finally {
1267
1554
  const object = ctx.object;
1268
1555
  if (object !== undefined) {
1269
- await runAfterStep(ctx, state.after, object, result);
1556
+ if (state.afterRan !== true) await runAfterStep(ctx, state.after, object, result);
1270
1557
  if (state.keepNotes !== undefined) {
1271
1558
  try {
1272
1559
  await state.keepNotes();
@@ -1280,6 +1567,47 @@ export async function runReply(ctx: StepContext, params: unknown): Promise<Plugi
1280
1567
  }
1281
1568
  }
1282
1569
 
1570
+ /** What a compaction did, as the engine's data carries it. */
1571
+ function compactionOf(value: unknown): AgentCompaction | undefined {
1572
+ if (!isRecord(value) || typeof value.before !== "number") return undefined;
1573
+ return {
1574
+ reason: value.reason === "manual" ? "manual" : "threshold",
1575
+ before: value.before,
1576
+ ...(typeof value.after === "number" ? { after: value.after } : {}),
1577
+ flushed: value.flushed === true,
1578
+ };
1579
+ }
1580
+
1581
+ /** The tokens as a short figure: 90,000 is `90k`. */
1582
+ function tokenFigure(tokens: number): string {
1583
+ return tokens >= 1000 ? `${Math.round(tokens / 1000)}k` : String(tokens);
1584
+ }
1585
+
1586
+ /**
1587
+ * The line in the chat that says the context was compacted, or that there was
1588
+ * nothing to compact. It is a command-shaped entry so no client changes: never
1589
+ * part of the agent's prompt and never answered.
1590
+ */
1591
+ async function recordCompactionLine(
1592
+ ctx: StepContext,
1593
+ chat: string,
1594
+ harness: string,
1595
+ compaction: AgentCompaction | undefined,
1596
+ manual: boolean,
1597
+ ): Promise<void> {
1598
+ const outcome =
1599
+ compaction === undefined
1600
+ ? "Nothing was compacted: the context is too small, or the compaction failed."
1601
+ : `The context was compacted${compaction.after === undefined ? "" : ` from ${tokenFigure(compaction.before)} to about ${tokenFigure(compaction.after)} tokens`}${compaction.flushed ? ", after the agent wrote what to remember to memory" : ""}.`;
1602
+ const data: CommandData = {
1603
+ from: { via: harness, id: harness },
1604
+ command: manual ? "compact" : "compact (automatic)",
1605
+ outcome,
1606
+ ok: compaction !== undefined,
1607
+ };
1608
+ await ctx.facts.append({ type: COMMAND_FACT, object: chatRef(chat), data });
1609
+ }
1610
+
1283
1611
  /** One round of an answer, before the after step runs. */
1284
1612
  async function replyOnce(
1285
1613
  ctx: StepContext,
@@ -1293,17 +1621,32 @@ async function replyOnce(
1293
1621
  const stored = await ctx.store.get(CHAT_TYPE, object.id);
1294
1622
  if (stored === undefined) return failed("object", `there is no chat ${object.id}`);
1295
1623
  let chat = chatData(stored.data);
1296
- const read = readChat(ctx.store, object.id);
1624
+ let read = readChat(ctx.store, object.id);
1625
+ if (briefDue(read.facts) !== undefined) {
1626
+ if (ctx.runStep === undefined) return failedReply(ctx, object.id, "host", "the agent could not be started", undefined);
1627
+ await makeBrief(ctx, object, chat, ctx.runStep, read.facts);
1628
+ chat = chatData((await ctx.store.get(CHAT_TYPE, object.id))?.data ?? stored.data);
1629
+ read = readChat(ctx.store, object.id);
1630
+ }
1297
1631
  let messages = read.messages;
1298
1632
  let pending = unanswered(messages, read.facts);
1299
- if (pending.length === 0) {
1633
+ const compactAsked = chat.harness === "pi" && compactRequested(read.facts);
1634
+ if (pending.length === 0 && !compactAsked) {
1300
1635
  // A run that stopped after recording a reply still owes the chat its model and cost.
1301
1636
  await syncChat(ctx, object.id, undefined);
1302
1637
  return { result: "done", data: { answered: 0 } };
1303
1638
  }
1304
1639
 
1640
+ // A context that was still over the share right after its compaction would be
1641
+ // compacted again by every reply: the reply fails instead, and `/new` ends it.
1642
+ if (pending.length > 0 && chatTooFull(read.facts)) {
1643
+ return failedReply(ctx, object.id, "full", CHAT_TOO_FULL_LINE, pending[0]?.id);
1644
+ }
1645
+
1305
1646
  const runStep = ctx.runStep;
1306
1647
  const oldest = pending[0]?.id;
1648
+ // A `/compact` with nothing to answer is a run of its own: no prompt, no reply.
1649
+ let compactOnly = pending.length === 0;
1307
1650
  if (runStep === undefined) return failedReply(ctx, object.id, "host", "the agent could not be started", oldest);
1308
1651
  const use = `${chat.harness}/agent`;
1309
1652
  if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(use)) {
@@ -1414,7 +1757,7 @@ async function replyOnce(
1414
1757
 
1415
1758
  const resumed = isRecord(params) ? params : {};
1416
1759
  const session =
1417
- typeof resumed.resumeSession === "string" ? resumed.resumeSession : currentSession(chat, messages);
1760
+ typeof resumed.resumeSession === "string" ? resumed.resumeSession : currentSession(chat, messages, read.facts);
1418
1761
  // The context the last reply in this session ended with; a smaller one after
1419
1762
  // this reply means the agent compacted the session.
1420
1763
  const previousUsed = lastContextUsed(messages, session);
@@ -1488,9 +1831,14 @@ async function replyOnce(
1488
1831
  // them, every file as a path, and the chat's own attachment directory open to reads.
1489
1832
  const directory = attachmentDir(ctx.home, CHAT_TYPE, object.id);
1490
1833
  const levelPath = accessLevelPath(ctx.home, object.id);
1491
- const withReads = messages.some((message) => message.attachments.length > 0)
1834
+ const withAttachments = messages.some((message) => message.attachments.length > 0)
1492
1835
  ? withAttachmentReads(live.access, directory)
1493
1836
  : live.access;
1837
+ // A stretch that is not remembered leaves the bot's memory read-only for this reply.
1838
+ const withReads =
1839
+ chat.private === true && live.memoryPaths !== undefined
1840
+ ? withMemoryReadOnly(withAttachments, live.memoryPaths)
1841
+ : withAttachments;
1494
1842
  const baseAccess = withLevelFileDeny(withReads, levelPath);
1495
1843
  recheckBase = baseAccess;
1496
1844
  const base = withAccessLevel(baseAccess, level);
@@ -1560,7 +1908,8 @@ async function replyOnce(
1560
1908
  );
1561
1909
  return current;
1562
1910
  });
1563
- if (pending.length === 0) {
1911
+ compactOnly = pending.length === 0;
1912
+ if (pending.length === 0 && !compactAsked) {
1564
1913
  await closeMidRun();
1565
1914
  await syncChat(ctx, object.id, undefined);
1566
1915
  return { result: "done", data: { answered: 0 } };
@@ -1576,13 +1925,23 @@ async function replyOnce(
1576
1925
  const carried =
1577
1926
  live.notes === undefined ? [] : notesToAttach(noteContents, chat.noteHashes, session);
1578
1927
  const noteText = carried.length === 0 ? undefined : noteBlock(carried);
1928
+ const briefText = briefToCarry(messages, (locked as ChatRead | undefined)?.facts ?? read.facts);
1929
+ const deliveryText = deliveryBlock(deliveriesToCarry(messages, (locked as ChatRead | undefined)?.facts ?? read.facts));
1579
1930
  const messagePrompt = promptFor(
1580
1931
  pending.map((message) => ({ ...message, text: skillMessage(message.text, skills, loadsSkills) })),
1581
1932
  new Set(images.map((image) => image.path)),
1582
1933
  );
1583
- const prompt = [context, noteText, messagePrompt]
1584
- .filter((part): part is string => part !== undefined && part.length > 0)
1585
- .join("\n\n");
1934
+ // The first message after `/new` says the earlier record exists and how to read it.
1935
+ const pointer = startsAfterNew(read.facts, messages) ? earlierRecordPointer(object.id) : undefined;
1936
+ const prompt = compactOnly
1937
+ ? "compact"
1938
+ : [context, noteText, pointer, briefText, deliveryText, messagePrompt]
1939
+ .filter((part): part is string => part !== undefined && part.length > 0)
1940
+ .join("\n\n");
1941
+ if (compactAsked) {
1942
+ // The request is taken now, so a failed compaction is not tried again by each following reply.
1943
+ await ctx.facts.append({ type: COMPACT_FACT, object: chatRef(object.id), data: { kind: "taken", runId: ctx.runId } });
1944
+ }
1586
1945
  let outcome: PluginStepResult;
1587
1946
  try {
1588
1947
  outcome = await runStep(
@@ -1608,6 +1967,22 @@ async function replyOnce(
1608
1967
  // A chat retries a failed model request with pi's own bounded backoff;
1609
1968
  // a task keeps pi's retry off and uses dev's own waits and fallbacks.
1610
1969
  ...(chat.harness === "pi" ? { retry: true } : {}),
1970
+ // pi compacts when the context nears the window, after a silent turn
1971
+ // that lets a bot write to its memory first (ADR 0023 D12). A
1972
+ // `/compact` asks for it now.
1973
+ ...(chat.harness === "pi"
1974
+ ? {
1975
+ compact: {
1976
+ at: COMPACT_AT,
1977
+ // The flush writes what the whole session holds to memory, so a session
1978
+ // that holds a stretch that is not remembered gets none.
1979
+ ...(live.notes === undefined || chat.private === true || sessionHoldsPrivate(messages, read.facts)
1980
+ ? {}
1981
+ : { flush: COMPACT_FLUSH }),
1982
+ ...(compactAsked ? (compactOnly ? { only: true } : { now: true }) : {}),
1983
+ },
1984
+ }
1985
+ : {}),
1611
1986
  ...(Object.keys(live.mcpServers).length === 0 ? {} : { mcpServers: live.mcpServers }),
1612
1987
  ...(live.useOwnSettings ? { useOwnSettings: true } : {}),
1613
1988
  ...(session === undefined ? {} : { resumeSession: session }),
@@ -1677,6 +2052,21 @@ async function replyOnce(
1677
2052
  const why = failureOf(outcome);
1678
2053
  return failedReply(ctx, object.id, why.reason, why.message, oldest);
1679
2054
  }
2055
+ const compaction = compactionOf(data.compaction);
2056
+ if (compactOnly) {
2057
+ // No reply: the chat says whether the context was compacted, and the next
2058
+ // message carries the notes whole again, as after any compaction.
2059
+ const sessionDone = typeof data.sessionId === "string" && data.sessionId.length > 0 ? data.sessionId : session;
2060
+ await recordCompactionLine(ctx, object.id, chat.harness, compaction, true);
2061
+ if (compaction !== undefined) {
2062
+ const onlyContext = replyContextOf(data.context);
2063
+ const onlyWindow = onlyContext?.window ?? (chat.model === undefined ? undefined : ctx.harnessModels?.(chat.harness)?.windows?.[chat.model]);
2064
+ await recordCompacted(ctx, object.id, stillFull(compaction.after ?? onlyContext?.used, onlyWindow));
2065
+ }
2066
+ await ctx.facts.append({ type: COMPACT_FACT, object: chatRef(object.id), data: { kind: "done", runId: ctx.runId } });
2067
+ await syncChat(ctx, object.id, sessionDone, undefined, compaction === undefined ? undefined : { ...(sessionDone === undefined ? {} : { session: sessionDone }), files: {} });
2068
+ return { result: "done", data: { answered: 0, compacted: compaction !== undefined } };
2069
+ }
1680
2070
  const said = typeof data.finalMessage === "string" ? data.finalMessage.trim() : "";
1681
2071
  const text = maskSecrets(said, await secretValues(ctx));
1682
2072
  if (text.length === 0) {
@@ -1703,6 +2093,24 @@ async function replyOnce(
1703
2093
 
1704
2094
  await recordEntries(ctx, object.id, folded, { finalText: text, stopped: false });
1705
2095
 
2096
+ // The memory commit runs before the reply is recorded, so the reply names
2097
+ // the notes the run wrote. It runs once, after the last round of a run: a
2098
+ // round that leaves messages to answer leaves it to the round after, and the
2099
+ // end of the step does not run it again.
2100
+ let afterData: Readonly<Record<string, unknown>> | undefined;
2101
+ if (state.after !== undefined) {
2102
+ const taken = new Set([...pending.map((message) => message.id), ...(midRun?.handed ?? [])]);
2103
+ const before = readChat(ctx.store, object.id);
2104
+ const moreToAnswer =
2105
+ unanswered(before.messages, before.facts).some((message) => !taken.has(message.id)) ||
2106
+ (chat.harness === "pi" && compactRequested(before.facts));
2107
+ if (!moreToAnswer) {
2108
+ afterData = await runAfterStep(ctx, state.after, object, "done");
2109
+ state.afterRan = true;
2110
+ }
2111
+ }
2112
+ const memory = memoryShownOf({ wrote: wroteOf(afterData), used: memoryUsedBy(carried, folded.entries) });
2113
+
1706
2114
  // The reply is a fact before the step counts as done: a rerun reads it and
1707
2115
  // does not answer the same messages twice.
1708
2116
  const reply: MessageData = {
@@ -1713,6 +2121,8 @@ async function replyOnce(
1713
2121
  attachments: [],
1714
2122
  source: { kind: chat.harness, ref: null },
1715
2123
  replyTo: [...pending.map((message) => message.id), ...(midRun?.handed ?? [])],
2124
+ // The answer to a message of the stretch is part of it.
2125
+ ...(chat.private === true || pending.some((message) => message.private === true) ? { private: true as const } : {}),
1716
2126
  runId: ctx.runId,
1717
2127
  ...(sessionId === undefined ? {} : { session: sessionId }),
1718
2128
  ...usage,
@@ -1720,8 +2130,14 @@ async function replyOnce(
1720
2130
  ? {}
1721
2131
  : { context: { used: replyContext.used, ...(window === undefined ? {} : { window }) } }),
1722
2132
  ...(timings === undefined ? {} : { timings }),
2133
+ ...(memory === undefined ? {} : { memory }),
1723
2134
  };
1724
2135
  await ctx.facts.append({ type: MESSAGE_FACT, object: chatRef(object.id), data: reply });
2136
+ // After the reply, one short line says the context was compacted.
2137
+ if (compaction !== undefined) {
2138
+ await recordCompactionLine(ctx, object.id, chat.harness, compaction, compactAsked);
2139
+ await recordCompacted(ctx, object.id, stillFull(compaction.after ?? replyContext?.used, window));
2140
+ }
1725
2141
 
1726
2142
  // The chat's own reference follows; read again, so a change made meanwhile stays.
1727
2143
  await syncChat(ctx, object.id, sessionId, live.context === undefined ? undefined : live.cwd);
@@ -1749,7 +2165,10 @@ async function replyOnce(
1749
2165
  }
1750
2166
 
1751
2167
  const leftRead = readChat(ctx.store, object.id);
2168
+ await nameSegment(ctx, object, chat, ctx.runStep, leftRead, chat.title);
1752
2169
  const left = unanswered(leftRead.messages, leftRead.facts);
1753
2170
  const answered = pending.length + (midRun?.handed.length ?? 0);
1754
- return { result: left.length > 0 ? "more" : "done", data: { answered, left: left.length } };
2171
+ // A `/compact` that came in during this reply is taken by the next round.
2172
+ const askedMeanwhile = chat.harness === "pi" && compactRequested(chatFacts(ctx.store, object.id));
2173
+ return { result: left.length > 0 || askedMeanwhile ? "more" : "done", data: { answered, left: left.length } };
1755
2174
  }