@howaboua/pi-durable-context 0.10.0 → 0.13.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.
@@ -12,7 +12,11 @@ import {
12
12
  import { defineExtension } from "@earendil-works/pi-durable";
13
13
 
14
14
  // packages/context/src/admission.ts
15
- import { ConversationBusy, defineTask as defineTask2 } from "@earendil-works/pi-durable";
15
+ import {
16
+ ConversationBusy,
17
+ defineTask as defineTask2,
18
+ LiveDoc as LiveDoc4
19
+ } from "@earendil-works/pi-durable";
16
20
 
17
21
  // packages/context/src/lifecycle.ts
18
22
  import {
@@ -144,8 +148,12 @@ async function until(watch, predicate, signal) {
144
148
  await new Promise((resolve, reject) => {
145
149
  abort = () => reject(signal.reason);
146
150
  signal.addEventListener("abort", abort, { once: true });
147
- watch.start(async (value) => {
148
- if (value && predicate(value))
151
+ watch.start(async (call) => {
152
+ if (call.kind === "failed") {
153
+ reject(call.error);
154
+ return;
155
+ }
156
+ if (predicate(call.value))
149
157
  resolve();
150
158
  });
151
159
  if (signal.aborted)
@@ -153,8 +161,8 @@ async function until(watch, predicate, signal) {
153
161
  else if (watch.value && predicate(watch.value))
154
162
  resolve();
155
163
  watch.closed.then((end) => {
156
- if (end.reason !== "stopped")
157
- reject(new Error(`Context watch ended: ${end.reason}`));
164
+ if (end.kind !== "stopped")
165
+ reject(end.kind === "failed" || end.kind === "listener_error" ? end.error : new Error(`Context watch ended: ${end.kind}`));
158
166
  });
159
167
  });
160
168
  } finally {
@@ -182,11 +190,67 @@ async function cancelPlacedInput(host, conv, id, context) {
182
190
  // packages/context/src/note-store.ts
183
191
  import {
184
192
  createSession,
185
- defineDoc as defineDoc3,
193
+ defineDoc as defineDoc4,
186
194
  defineDocFamily as defineDocFamily2,
187
195
  GenerationTask,
196
+ ToolTask as ToolTask2
197
+ } from "@earendil-works/pi-durable";
198
+
199
+ // packages/execution/src/tool-origin.ts
200
+ import {
201
+ defineDoc as defineDoc3,
188
202
  ToolTask
189
203
  } from "@earendil-works/pi-durable";
204
+ var ToolOriginDoc = defineDoc3({
205
+ kind: "howaboua.tool-origin",
206
+ version: 1,
207
+ scope: "task",
208
+ checkpointWhen: () => false,
209
+ initial: () => ({})
210
+ });
211
+ async function admittedExecutionCall(tx, conversation, child) {
212
+ const task = await tx.task(child);
213
+ if (task?.conversationId !== conversation || task.kind === ToolTask.definition.name || task.owner === undefined)
214
+ return;
215
+ const owner = await tx.task(task.owner);
216
+ if (owner?.conversationId !== conversation || owner.owner !== undefined)
217
+ return;
218
+ const origin = (await tx.doc(ToolOriginDoc, child)).origin;
219
+ if (origin?.conversationId !== conversation)
220
+ return;
221
+ const root = await tx.task(origin.taskId);
222
+ if (root?.conversationId !== conversation || root.kind !== ToolTask.definition.name)
223
+ return;
224
+ const input = root.input;
225
+ if (input.kind !== "nested" && input.callId === origin.callId)
226
+ return { cell: owner.id, tool: root.id, call: origin.callId };
227
+ }
228
+ async function admittedToolRound(tx, conversation, child) {
229
+ let id = child;
230
+ while (id !== undefined) {
231
+ const task = await tx.task(id);
232
+ if (!task || task.conversationId !== conversation)
233
+ return;
234
+ if (task.kind === ToolTask.definition.name) {
235
+ const input = task.input;
236
+ if (input.kind !== "nested")
237
+ return input.assistant;
238
+ } else if (id !== child) {
239
+ return;
240
+ }
241
+ const origin = (await tx.doc(ToolOriginDoc, id)).origin;
242
+ if (origin) {
243
+ if (origin.conversationId !== conversation)
244
+ return;
245
+ const root = await tx.task(origin.taskId);
246
+ if (root?.conversationId !== conversation || root.kind !== ToolTask.definition.name)
247
+ return;
248
+ const input = root.input;
249
+ return input.kind !== "nested" && input.callId === origin.callId ? input.assistant : undefined;
250
+ }
251
+ id = task.owner;
252
+ }
253
+ }
190
254
 
191
255
  // packages/context/src/query-input.ts
192
256
  var actions = {
@@ -241,13 +305,20 @@ function normalizeQueryInput(namespace, input) {
241
305
  if (!input || typeof input !== "object" || Array.isArray(input))
242
306
  throw new Error("Supply an action object; use {} for help");
243
307
  const params = { ...input };
308
+ if (namespace === "history" && params["action"] === undefined && "query" in params)
309
+ params["action"] = "search";
244
310
  const aliases = actions[namespace];
245
311
  const action = aliases[String(params["action"])] ?? params["action"];
246
312
  if (action !== undefined)
247
313
  params["action"] = action;
248
314
  if (namespace === "notes") {
249
- if (action === "write" || action === "append")
315
+ alias(params, "address", "path");
316
+ if (action === "read")
317
+ alias(params, "end_line", "stop_line");
318
+ if (action === "write" || action === "append") {
250
319
  alias(params, "content", "text");
320
+ alias(params, "body", "text");
321
+ }
251
322
  if (action === "list" || action === "search") {
252
323
  alias(params, "prefix", "path");
253
324
  alias(params, "path_prefix", "path");
@@ -260,6 +331,8 @@ function normalizeQueryInput(namespace, input) {
260
331
  alias(params, "max_results", "limit");
261
332
  }
262
333
  const used = usedPresentation[`${namespace}:${String(action)}`] ?? [];
334
+ if (namespace === "history" && action !== "read")
335
+ delete params["offset_chars"];
263
336
  for (const hint of presentation)
264
337
  if (!used.includes(hint))
265
338
  delete params[hint];
@@ -276,7 +349,7 @@ function isNoteWrite(input) {
276
349
  }
277
350
 
278
351
  // packages/context/src/note-store.ts
279
- var NotesState = defineDoc3({
352
+ var NotesState = defineDoc4({
280
353
  kind: "howaboua.context.notes-state",
281
354
  version: 1,
282
355
  scope: "conversation",
@@ -295,7 +368,7 @@ var NoteFile = defineDocFamily2({
295
368
  fork: "asOf",
296
369
  initial: () => ({ text: "" })
297
370
  });
298
- var WriteReceipt = defineDoc3({
371
+ var WriteReceipt = defineDoc4({
299
372
  kind: "howaboua.context.note-write-receipt",
300
373
  version: 1,
301
374
  scope: "task",
@@ -311,14 +384,30 @@ async function requireNotesWindow(tx, id) {
311
384
  async function readNoteText(tx, id, path) {
312
385
  return (await tx.doc(NoteFile, id, path, null)).text;
313
386
  }
314
- async function notesAreFresh(tx, id) {
387
+ async function freshNote(tx, id) {
315
388
  const userEntry = await latestUserEntry(tx, id);
316
389
  const window = await tx.doc(WindowState, id);
317
390
  const state = await tx.doc(NotesState, id);
318
391
  const fresh = window.window !== undefined && state.lastWrite !== undefined && (state.lastAttempt === undefined || state.lastAttempt === state.lastWrite.taskId) && state.lastWrite.windowId === window.window.id && state.lastWrite.userEntry === userEntry;
319
- if (!fresh || !state.lastWrite)
392
+ return fresh ? state.lastWrite : undefined;
393
+ }
394
+ async function successfulTask(tx, id, owner) {
395
+ const task = await tx.task(id);
396
+ if (!task || owner !== undefined && task.owner !== owner || task.abortRequested || task.state.status !== "terminal" || task.state.outcome.status !== "completed")
320
397
  return false;
321
- let owner = state.lastWrite.taskId;
398
+ const result = task.state.outcome.result;
399
+ return !(result && typeof result === "object" && !Array.isArray(result) && result["isError"] === true);
400
+ }
401
+ async function sameCellCheckpoint(tx, id, request, execution) {
402
+ const saved = await freshNote(tx, id);
403
+ if (saved?.execution?.cell === execution.cell && saved.execution.tool === execution.tool && saved.execution.call === execution.call && saved.taskId < request && await successfulTask(tx, saved.taskId, execution.cell))
404
+ return saved.taskId;
405
+ }
406
+ async function notesAreFresh(tx, id) {
407
+ const lastWrite = await freshNote(tx, id);
408
+ if (!lastWrite)
409
+ return false;
410
+ let owner = lastWrite.taskId;
322
411
  while (owner !== undefined) {
323
412
  const task = await tx.task(owner);
324
413
  if (!task)
@@ -331,7 +420,7 @@ async function notesAreFresh(tx, id) {
331
420
  if (result && typeof result === "object" && !Array.isArray(result)) {
332
421
  if (result["isError"] === true)
333
422
  return false;
334
- if (task.kind === ToolTask.definition.name && "entryId" in result) {
423
+ if (task.kind === ToolTask2.definition.name && "entryId" in result) {
335
424
  const entryId = result["entryId"];
336
425
  if (typeof entryId === "number") {
337
426
  const entry = await tx.entry(entryId);
@@ -346,11 +435,11 @@ async function notesAreFresh(tx, id) {
346
435
  do {
347
436
  const page = await tx.scanTasks({
348
437
  conversationId: id,
349
- kind: ToolTask.definition.name,
438
+ kind: ToolTask2.definition.name,
350
439
  order: "descending"
351
440
  }, 64, cursor);
352
441
  for (const task of page.items) {
353
- if (task.id <= state.lastWrite.taskId)
442
+ if (task.id <= lastWrite.taskId)
354
443
  return true;
355
444
  const input = task.input;
356
445
  let call = input.kind === "nested" ? input.call : undefined;
@@ -365,6 +454,59 @@ async function notesAreFresh(tx, id) {
365
454
  } while (cursor !== undefined);
366
455
  return true;
367
456
  }
457
+ async function isCurrentCheckpoint(tx, id, checkpoint) {
458
+ return (await freshNote(tx, id))?.taskId === checkpoint;
459
+ }
460
+ async function latestNoteRound(tx, id) {
461
+ const saved = (await tx.doc(NotesState, id)).lastWrite;
462
+ if (!saved)
463
+ return;
464
+ let owner = saved.taskId;
465
+ let savedAssistant = saved.assistantEntry;
466
+ while (owner !== undefined) {
467
+ const task = await tx.task(owner);
468
+ if (!task || task.kind === GenerationTask.definition.name)
469
+ break;
470
+ if (task.kind === ToolTask2.definition.name) {
471
+ const call = task.input;
472
+ if (call.kind !== "nested")
473
+ savedAssistant = call.assistant;
474
+ }
475
+ owner = task.owner;
476
+ }
477
+ return savedAssistant;
478
+ }
479
+ async function notesPrecedeRequest(tx, id, request) {
480
+ const requesting = await tx.task(request);
481
+ if (requesting?.kind !== ToolTask2.definition.name)
482
+ return false;
483
+ const input = requesting.input;
484
+ if (input.kind === "nested")
485
+ return false;
486
+ const savedAssistant = await latestNoteRound(tx, id);
487
+ if (savedAssistant === undefined)
488
+ return false;
489
+ const completed = new Map;
490
+ let cursor;
491
+ do {
492
+ const page = await tx.scanEntries({ conversationId: id, maxEntryId: input.assistant }, 64, cursor);
493
+ for (const entry of page.items) {
494
+ if (entry.id === input.assistant)
495
+ continue;
496
+ for (const message of entry.model ?? []) {
497
+ if (message.role === "toolResult")
498
+ completed.set(message.toolCallId, !message.isError);
499
+ if (message.role !== "assistant")
500
+ continue;
501
+ const calls = message.content.filter((block) => block.type === "toolCall");
502
+ if (calls.length)
503
+ return entry.id === savedAssistant && calls.every((call) => completed.has(call.id) && (call.name !== "notes" || !isNoteWrite(call.arguments) || completed.get(call.id) === true));
504
+ }
505
+ }
506
+ cursor = page.next;
507
+ } while (cursor !== undefined);
508
+ return false;
509
+ }
368
510
  async function beginNoteWrite(tx, id, taskId) {
369
511
  const receipt = await tx.doc(WriteReceipt, taskId);
370
512
  if (receipt.attempted || receipt.file)
@@ -401,9 +543,13 @@ async function mutateNote(tx, input) {
401
543
  nextCatalog.push(metadata);
402
544
  else
403
545
  nextCatalog[index] = metadata;
546
+ const assistantEntry = await admittedToolRound(tx, input.conversationId, input.taskId);
547
+ const execution = await admittedExecutionCall(tx, input.conversationId, input.taskId);
404
548
  const freshness = {
405
549
  windowId,
406
550
  userEntry,
551
+ ...assistantEntry === undefined ? {} : { assistantEntry },
552
+ ...execution === undefined ? {} : { execution },
407
553
  taskId: input.taskId,
408
554
  updatedAt
409
555
  };
@@ -425,7 +571,7 @@ function noteMetadata(file) {
425
571
  async function renderNotesThreadHint(reader, id, context, maxBytes = 4000) {
426
572
  const state = await reader.snapshot(NotesState, id, context);
427
573
  const files = [...state?.files ?? []].sort((left, right) => right.updatedAt - left.updatedAt || left.path.localeCompare(right.path));
428
- const header = "Recent notes (up to 5, most-recent first). More may exist; use notes list or search:";
574
+ const header = "Recent notes in virtual storage (up to 5, most-recent first). More may exist; use notes list or search:";
429
575
  const lines = [];
430
576
  for (const file of files) {
431
577
  if (lines.length >= 5)
@@ -452,13 +598,24 @@ async function startInstruction(tx, id, owner, kind, content, now) {
452
598
  return;
453
599
  await tx.appendEntry(id, {
454
600
  kind,
455
- model: [{ role: "system", content, timestamp: now }]
601
+ model: [
602
+ { role: "system", content, timestamp: now },
603
+ {
604
+ role: "user",
605
+ content: "[Context management request] Carry out the context instructions above.",
606
+ timestamp: now
607
+ }
608
+ ]
456
609
  });
457
610
  const generation = await tx.createTask(GenerationTask2, {}, {
458
611
  ownership: { kind: "task", taskId: owner },
459
612
  conversationId: id
460
613
  });
461
- (await tx.doc(LiveDoc2, id)).run = { taskId: generation, inputs: [] };
614
+ (await tx.doc(LiveDoc2, id)).run = {
615
+ taskId: generation,
616
+ inputs: [],
617
+ turns: 0
618
+ };
462
619
  return generation;
463
620
  }
464
621
  async function waitInstruction(host, id, generation, context) {
@@ -514,9 +671,9 @@ async function instructionAnswer(tx, id) {
514
671
 
515
672
  // packages/context/src/rollover-preparation.ts
516
673
  import {
517
- defineDoc as defineDoc4
674
+ defineDoc as defineDoc5
518
675
  } from "@earendil-works/pi-durable";
519
- var RolloverPreparation = defineDoc4({
676
+ var RolloverPreparation = defineDoc5({
520
677
  kind: "howaboua.context.rollover-preparation",
521
678
  version: 1,
522
679
  scope: "task",
@@ -581,6 +738,95 @@ async function prepareRollover(conversation, taskId, callback, request, ready, c
581
738
  return { head };
582
739
  }
583
740
 
741
+ // packages/context/src/rollover-tail.ts
742
+ function visibleConversation(message) {
743
+ if (message.role === "user")
744
+ return message;
745
+ if (message.role !== "assistant")
746
+ return;
747
+ const content = message.content.filter((part) => part.type === "text");
748
+ if (!content.length)
749
+ return;
750
+ return content.length === message.content.length ? message : { ...message, content, stopReason: "stop" };
751
+ }
752
+ function completeMessages(carriers) {
753
+ const complete = new Set;
754
+ let group;
755
+ const finish = () => {
756
+ if (group && group.calls.size === group.results.size) {
757
+ complete.add(group.assistant);
758
+ for (const result of group.results.values())
759
+ complete.add(result);
760
+ }
761
+ group = undefined;
762
+ };
763
+ for (const carrier of carriers) {
764
+ if (carrier.control)
765
+ continue;
766
+ for (const message of carrier.messages) {
767
+ if (message.role === "assistant") {
768
+ finish();
769
+ const calls = message.content.flatMap((part) => part.type === "toolCall" ? [[part.id, part.name]] : []);
770
+ const byId = new Map(calls);
771
+ if (byId.size !== calls.length)
772
+ continue;
773
+ group = {
774
+ assistant: message,
775
+ calls: byId,
776
+ results: new Map
777
+ };
778
+ } else if (message.role === "user") {
779
+ finish();
780
+ } else if (message.role === "toolResult" && group?.calls.get(message.toolCallId) === message.toolName && !group.results.has(message.toolCallId)) {
781
+ group.results.set(message.toolCallId, message);
782
+ }
783
+ }
784
+ }
785
+ finish();
786
+ return complete;
787
+ }
788
+ async function projectRolloverTail(conv, mode, context) {
789
+ const { head, tip } = await conv.commit(async (tx) => ({
790
+ head: await latestNoteRound(tx, conv.id),
791
+ tip: await latestContextEntry(tx, conv.id)
792
+ }), context);
793
+ if (head === undefined || tip === null || head >= tip)
794
+ return;
795
+ const view = await conv.context(context, { at: tip });
796
+ const start = view.entries.findIndex((entry) => entry.id === head && entry.head === undefined);
797
+ if (start < 0)
798
+ return;
799
+ const carriers = view.entries.slice(start).map((entry, index) => ({
800
+ id: entry.id,
801
+ messages: view.contributions[start + index] ?? [],
802
+ control: entry.kind === "pi.system" || entry.kind.startsWith("howaboua.context.")
803
+ }));
804
+ const complete = completeMessages(carriers);
805
+ const saved = carriers[0]?.messages.find((message) => message.role === "assistant");
806
+ const last = carriers.findLast((carrier) => !carrier.control && carrier.messages.length > 0)?.messages.at(-1);
807
+ if (!saved || !complete.has(saved) || last?.role !== "assistant" || last.stopReason !== "stop" || last.content.some((part) => part.type === "toolCall"))
808
+ return;
809
+ const edits = [];
810
+ for (const carrier of carriers) {
811
+ if (!carrier.messages.length)
812
+ continue;
813
+ const messages = carrier.control ? [] : carrier.messages.flatMap((message) => {
814
+ if (message.role === "system")
815
+ return [];
816
+ const projected = mode === "full" && complete.has(message) ? message : visibleConversation(message);
817
+ return projected ? [projected] : [];
818
+ });
819
+ if (!messages.length)
820
+ edits.push({ target: carrier.id, action: "omit" });
821
+ else if (messages.length !== carrier.messages.length || messages.some((message, index) => message !== carrier.messages[index]))
822
+ edits.push({ target: carrier.id, action: "replace", messages });
823
+ }
824
+ return { head, tip, edits };
825
+ }
826
+ async function rolloverTailMatches(tx, conv, tail) {
827
+ return tail.tip === await latestContextEntry(tx, conv.id) && tail.head === await latestNoteRound(tx, conv.id);
828
+ }
829
+
584
830
  // packages/context/src/rollover.ts
585
831
  var checkpointPrompt = "Save the task state in notes, then finish your reply. A new window opens automatically after your reply; do not call new_context. If saving fails, report the error.";
586
832
  var key = (task) => `context:checkpoint:${task}`;
@@ -607,7 +853,7 @@ async function completedFreshNotes(host, id, context) {
607
853
  } while (cursor !== undefined);
608
854
  return done;
609
855
  }
610
- function createRollover(host, beforeRollover) {
856
+ function createRollover(host, beforeRollover, tailMode = "off") {
611
857
  return defineTask({
612
858
  name: ROLLOVER_TASK,
613
859
  version: 1,
@@ -622,7 +868,7 @@ function createRollover(host, beforeRollover) {
622
868
  await Promise.all(tasks.map((id) => runtime.waitForTask(id, context)));
623
869
  }
624
870
  const fresh = await completedFreshNotes(host(), conv.id, context);
625
- if (fresh) {
871
+ if (fresh && (tailMode === "off" || task.input.reason === "idle" || await projectRolloverTail(conv, tailMode, context))) {
626
872
  await runtime.commit(() => ({ status: "running", checkpoint: { phase: "rotate" } }), context);
627
873
  return;
628
874
  }
@@ -723,14 +969,18 @@ function createRollover(host, beforeRollover) {
723
969
  return completed && await nativeIdle(tx, task.conversationId) && (await foreignTasks(tx, task.conversationId)).length === 0 && await notesAreFresh(tx, task.conversationId);
724
970
  };
725
971
  const current = await runtime.snapshot(WindowState, task.conversationId, context);
726
- const preparation = await prepareRollover(conv, task.id, beforeRollover, {
972
+ const keepsTail = tailMode !== "off" && task.input.reason !== "tool";
973
+ const tail = keepsTail ? await projectRolloverTail(conv, tailMode, context) : undefined;
974
+ const preparation = keepsTail && !tail ? {
975
+ error: "No eligible saved checkpoint tail; the current window is unchanged"
976
+ } : await prepareRollover(conv, task.id, beforeRollover, {
727
977
  conversationId: task.conversationId,
728
978
  windowId: current?.window?.id ?? "",
729
979
  nextWindowId: task.input.windowId,
730
980
  reason: task.input.reason
731
- }, ready, context);
981
+ }, async (tx) => await ready(tx) && (!tail || await rolloverTailMatches(tx, conv, tail)), context);
732
982
  await runtime.commit(async (tx) => {
733
- const safe = !preparation.error && await ready(tx) && (preparation.head === undefined || preparation.head === await latestContextEntry(tx, task.conversationId));
983
+ const safe = !preparation.error && await ready(tx) && (!tail || await rolloverTailMatches(tx, conv, tail)) && (preparation.head === undefined || preparation.head === await latestContextEntry(tx, task.conversationId));
734
984
  const state = await tx.doc(WindowState, task.conversationId);
735
985
  if (!safe || !state.window) {
736
986
  delete state.transition;
@@ -753,7 +1003,7 @@ function createRollover(host, beforeRollover) {
753
1003
  };
754
1004
  const entry = await tx.appendEntry(WindowEntry, task.conversationId, {
755
1005
  data: window,
756
- head: "self"
1006
+ ...tail ? { head: tail.head, edits: tail.edits } : { head: "self" }
757
1007
  });
758
1008
  state.window = window;
759
1009
  state.entry = entry.id;
@@ -994,7 +1244,8 @@ function createInput(host, rollover, idleMs) {
994
1244
  const userEntry = await latestUserEntry(tx, task.conversationId);
995
1245
  const idle = await nativeIdle(tx, task.conversationId);
996
1246
  const state = await tx.doc(WindowState, task.conversationId);
997
- if (idle && !state.transition)
1247
+ const answered = !idle && settled.status === "done" && (await tx.doc(LiveDoc4, task.conversationId)).run?.afterRun !== undefined && settled.answer === await latestContextEntry(tx, task.conversationId);
1248
+ if ((idle || answered) && !state.transition)
998
1249
  state.settlement = {
999
1250
  observedAt: runtime.now(),
1000
1251
  userEntry,
@@ -1063,9 +1314,9 @@ import {
1063
1314
  import { Type as Type2 } from "typebox";
1064
1315
 
1065
1316
  // internal/context-visibility.ts
1066
- import { createSession as createSession2, defineDoc as defineDoc5 } from "@earendil-works/pi-durable";
1317
+ import { createSession as createSession2, defineDoc as defineDoc6 } from "@earendil-works/pi-durable";
1067
1318
  var SHARED_GROUP = "shared";
1068
- var ContextVisibility = defineDoc5({
1319
+ var ContextVisibility = defineDoc6({
1069
1320
  kind: "howaboua.context.visibility",
1070
1321
  version: 1,
1071
1322
  scope: "conversation",
@@ -1219,21 +1470,6 @@ import {
1219
1470
  // packages/context/src/tool-contract.ts
1220
1471
  import { Type } from "typebox";
1221
1472
  import { Check } from "typebox/value";
1222
- var HISTORY_ACTIONS = [
1223
- "help",
1224
- "list_windows",
1225
- "list",
1226
- "read",
1227
- "search"
1228
- ];
1229
- var NOTES_ACTIONS = [
1230
- "help",
1231
- "list",
1232
- "read",
1233
- "search",
1234
- "append",
1235
- "write"
1236
- ];
1237
1473
  var contextOutputLimits = { maxBytes: Infinity, maxLines: Infinity };
1238
1474
  function contextTextSlice(text, offset, limit) {
1239
1475
  if (offset > 0 && (text.codePointAt(offset - 1) ?? 0) > 65535)
@@ -1258,7 +1494,13 @@ var target = Type.Optional(Type.String({
1258
1494
  description: "Durable conversation ID; defaults to caller"
1259
1495
  }));
1260
1496
  var historyParameters = Type.Object({
1261
- action: Type.Optional(Type.Union(HISTORY_ACTIONS.map((action) => Type.Literal(action)))),
1497
+ action: Type.Optional(Type.Union([
1498
+ Type.Literal("help"),
1499
+ Type.Literal("list_windows"),
1500
+ Type.Literal("list"),
1501
+ Type.Literal("read"),
1502
+ Type.Literal("search")
1503
+ ])),
1262
1504
  target,
1263
1505
  item_id: Type.Optional(Type.String()),
1264
1506
  agent_name: Type.Optional(nullableString),
@@ -1283,7 +1525,14 @@ var historyParameters = Type.Object({
1283
1525
  }))
1284
1526
  }, { additionalProperties: false });
1285
1527
  var notesParameters = Type.Object({
1286
- action: Type.Optional(Type.Union(NOTES_ACTIONS.map((action) => Type.Literal(action)))),
1528
+ action: Type.Optional(Type.Union([
1529
+ Type.Literal("help"),
1530
+ Type.Literal("list"),
1531
+ Type.Literal("read"),
1532
+ Type.Literal("search"),
1533
+ Type.Literal("append"),
1534
+ Type.Literal("write")
1535
+ ])),
1287
1536
  target,
1288
1537
  agent_name: Type.Optional(nullableString),
1289
1538
  file_order: Type.Optional(Type.Union([Type.Literal("ascending"), Type.Literal("descending")])),
@@ -1295,7 +1544,7 @@ var notesParameters = Type.Object({
1295
1544
  limit: Type.Optional(positiveInteger),
1296
1545
  max_matches_per_file: Type.Optional(positiveInteger),
1297
1546
  path: Type.Optional(Type.Union([Type.String(), Type.Null()], {
1298
- description: "File for read/write/append; prefix for list/search"
1547
+ description: "Virtual note path, not a project file; prefix for list/search"
1299
1548
  })),
1300
1549
  query: Type.Optional(Type.String()),
1301
1550
  recent_file_first: Type.Optional(Type.Boolean()),
@@ -1305,11 +1554,23 @@ var notesParameters = Type.Object({
1305
1554
  offset_chars: Type.Optional(Type.Integer({ minimum: 0 })),
1306
1555
  text: Type.Optional(Type.String())
1307
1556
  }, { additionalProperties: false });
1308
- var newContextParameters = Type.Object({ role: Type.Optional(Type.String({ minLength: 1 })) }, { additionalProperties: false });
1309
- function prepareNewContextArguments(input) {
1557
+ function newContextParameters(taskCompletionRollover) {
1558
+ return Type.Object({
1559
+ ...taskCompletionRollover ? {
1560
+ resume: Type.Optional(Type.Boolean({
1561
+ description: "False: finish this reply, then wait in a fresh window"
1562
+ }))
1563
+ } : {},
1564
+ role: Type.Optional(Type.String({
1565
+ minLength: 1,
1566
+ description: "Configured model-role ID, not an agent name or handoff text"
1567
+ }))
1568
+ }, { additionalProperties: false });
1569
+ }
1570
+ function prepareNewContextArguments(input, taskCompletionRollover) {
1310
1571
  const args = input ?? {};
1311
- if (!Check(newContextParameters, args))
1312
- throw new Error('Use {} to keep the current model, or {role: "name"} for a configured role.');
1572
+ if (!Check(newContextParameters(taskCompletionRollover), args))
1573
+ throw new Error(taskCompletionRollover ? 'Use {}, {role: "name"}, or set resume to false after completing the task.' : 'Use {} to keep the current role, or {role: "name"} for a configured model-role ID.');
1313
1574
  return args;
1314
1575
  }
1315
1576
  function prepareNotesArguments(input) {
@@ -1368,6 +1629,9 @@ function contextToolHelp(namespace, args, rankedHistory = false) {
1368
1629
  throw new Error("Help accepts only action: help");
1369
1630
  const fields = namespace === "notes" ? notesFields : historyFields;
1370
1631
  return {
1632
+ ...namespace === "notes" ? {
1633
+ results: "list: files; search: files[].matches; read: file.content or file=null; write/append: file.path"
1634
+ } : {},
1371
1635
  actions: Object.fromEntries(Object.entries(fields).map(([action, names]) => [
1372
1636
  action,
1373
1637
  names.map((name) => (name === "path" ? ["read", "write", "append"].includes(action) : ["text", "query", "item_id"].includes(name)) || action === "read" && name === "window_id" ? name : `${name}?`).join(" ")
@@ -1375,13 +1639,13 @@ function contextToolHelp(namespace, args, rankedHistory = false) {
1375
1639
  target: "Durable conversation ID; defaults to caller; reads require the same Context visibility group; write own",
1376
1640
  ...namespace === "notes" ? {
1377
1641
  writes: "write replaces; append adds",
1378
- paths: "Paths are relative to /notes; target selects a conversation, read-only unless your own",
1642
+ paths: "Virtual note paths, inaccessible to filesystem tools. Relative to /notes; target selects a conversation, read-only unless your own",
1379
1643
  usage: '{ "action": "read", "path": "checkpoint" }',
1380
1644
  ranges: "start_line/stop_line inclusive, 1-based; negative counts from end; 0/null/omitted uses first/last line; out-of-range clamps; reversed range returns empty content",
1381
1645
  paging: "read returns the full selected lines by default. Optional limit_chars and offset_chars select a page; continue with next_offset_chars and the same line range",
1382
1646
  defaults: "list limit 20; search limit/max_matches_per_file 20; positive limits capped at 100; list name ascending; search name ascending, recent_file_first sorts created_at descending"
1383
1647
  } : {
1384
- usage: "Search earlier conversation, don't browse it. Pass returned IDs unchanged",
1648
+ usage: "With query, action defaults to search. Search past chat, don't browse it. Pass returned IDs unchanged",
1385
1649
  search: rankedHistory ? "Own earlier conversation: user/assistant visible text, all keywords, case/accent-insensitive, relevance order. Explicit live/tool/metadata scopes or agent_name: case-sensitive literal substring. list/read retain the full transcript. recent_first=true uses newest first" : "Case-sensitive literal substring. recent_first=true uses newest first"
1386
1650
  }
1387
1651
  };
@@ -1611,7 +1875,7 @@ var refreshFailures = new WeakMap;
1611
1875
  function createHistoryTool(options) {
1612
1876
  const tool = defineTool({
1613
1877
  name: "history",
1614
- description: "Search earlier conversation",
1878
+ description: "Search past chat",
1615
1879
  parameters: historyParameters,
1616
1880
  structuredOutputSchema: Type2.Object({}, { additionalProperties: true }),
1617
1881
  prepareArguments: prepareHistoryArguments,
@@ -1878,13 +2142,15 @@ async function waitForInputPlacement(host, id, context) {
1878
2142
  revision++;
1879
2143
  wake?.();
1880
2144
  };
1881
- const unsubscribe = host.harness.subscribeCommits((publication) => {
1882
- if (publication.changes.some((change) => change.type === "task" && change.value.id === id || change.type === "submission" && change.value.requestId === requestId))
2145
+ const observation = host.harness.observeCommits({
2146
+ advance(publication) {
2147
+ if (publication.changes.some((change) => change.type === "task" && change.value.id === id || change.type === "submission" && change.value.requestId === requestId))
2148
+ changed();
2149
+ },
2150
+ end() {
2151
+ closing = true;
1883
2152
  changed();
1884
- });
1885
- const stopClose = host.harness.subscribeClose(() => {
1886
- closing = true;
1887
- changed();
2153
+ }
1888
2154
  });
1889
2155
  try {
1890
2156
  while (true) {
@@ -1931,8 +2197,7 @@ async function waitForInputPlacement(host, id, context) {
1931
2197
  });
1932
2198
  }
1933
2199
  } finally {
1934
- unsubscribe();
1935
- stopClose();
2200
+ observation.detach();
1936
2201
  }
1937
2202
  }
1938
2203
 
@@ -1975,7 +2240,7 @@ function normalize(input, prefix) {
1975
2240
  function createNotesTool(options) {
1976
2241
  const tool = defineTool2({
1977
2242
  name: "notes",
1978
- description: "Persistent notes for handing off task state between context windows",
2243
+ description: "Virtual filesystem task checkpoints",
1979
2244
  parameters: notesParameters,
1980
2245
  structuredOutputSchema: Type3.Object({}, { additionalProperties: true }),
1981
2246
  prepareArguments: prepareNotesArguments,
@@ -2115,15 +2380,21 @@ function lineIndex(value, count, fallback) {
2115
2380
  // packages/context/src/policy.ts
2116
2381
  import {
2117
2382
  CompactionTask,
2118
- defineDoc as defineDoc6,
2383
+ defineDoc as defineDoc8,
2119
2384
  defineTool as defineTool3,
2120
2385
  GenerationTask as GenerationTask3,
2121
2386
  hook,
2122
2387
  section,
2123
- ToolTask as ToolTask2
2388
+ ToolTask as ToolTask3
2124
2389
  } from "@earendil-works/pi-durable";
2125
2390
  import { Type as Type4 } from "typebox";
2126
2391
 
2392
+ // packages/context/src/deferred-rollover.ts
2393
+ import {
2394
+ defineDoc as defineDoc7,
2395
+ LiveDoc as LiveDoc5
2396
+ } from "@earendil-works/pi-durable";
2397
+
2127
2398
  // packages/context/src/model-roles.ts
2128
2399
  import {
2129
2400
  AgentDoc
@@ -2146,7 +2417,7 @@ async function readRoles(catalog, id, context) {
2146
2417
  reasoning
2147
2418
  }));
2148
2419
  }
2149
- async function renderModelRoles(catalog, id, context) {
2420
+ async function renderModelRoles(catalog, id, selected, context) {
2150
2421
  let roles;
2151
2422
  try {
2152
2423
  roles = await readRoles(catalog, id, context);
@@ -2157,7 +2428,8 @@ async function renderModelRoles(catalog, id, context) {
2157
2428
  if (!roles.length)
2158
2429
  return "No model roles are available. Call new_context without role.";
2159
2430
  return [
2160
- 'Roles are user preferences, not capability limits. Switch only for a clear, sustained change of task or scope, not a single specialised prompt. Any model can do general work. Consider an available subagent for a bounded specialist detour. Save notes, then call new_context({role: "name"}); omit role to keep the current model.',
2431
+ `Current role: ${selected ?? "none"}`,
2432
+ 'Roles set focus, not permissions. Switch before a substantial phase that fits another role better. Keep the current role for a brief detour or when no role fits better. Save decisions, evidence paths and the next step in notes immediately before new_context({role: "name"}); omit role to keep the current role.',
2161
2433
  ...roles.map((role) => `- ${role.id}: ${role.description}`)
2162
2434
  ].join(`
2163
2435
  `);
@@ -2189,6 +2461,98 @@ async function roleSourceMatches(tx, id, role) {
2189
2461
  return current.model?.provider === role.source.model?.provider && current.model?.modelId === role.source.model?.modelId && (current.thinkingLevel ?? "off") === role.source.thinkingLevel;
2190
2462
  }
2191
2463
 
2464
+ // packages/context/src/deferred-rollover.ts
2465
+ var ToolWindow = defineDoc7({
2466
+ kind: "howaboua.context.tool-window",
2467
+ version: 1,
2468
+ scope: "task",
2469
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
2470
+ initial: () => ({})
2471
+ });
2472
+ var DeferredWindow = defineDoc7({
2473
+ kind: "howaboua.context.deferred-window",
2474
+ version: 1,
2475
+ scope: "conversation",
2476
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
2477
+ history: "latest",
2478
+ fork: "initial",
2479
+ initial: () => ({})
2480
+ });
2481
+ async function finishesInFreshWindow(api, context) {
2482
+ const deferred = await api.snapshot(DeferredWindow, api.conversationId, context);
2483
+ if (!deferred?.pending)
2484
+ return false;
2485
+ const live = await api.snapshot(LiveDoc5, api.conversationId, context);
2486
+ return live?.run?.taskId === api.taskId && live.run.inputs.includes(deferred.pending.input);
2487
+ }
2488
+ async function armDeferredWindow(conv, generation, ready, context) {
2489
+ await conv.commit(async (tx) => {
2490
+ const receipt = await tx.doc(ToolWindow, generation);
2491
+ const live = await tx.doc(LiveDoc5, conv.id);
2492
+ const input = live.run?.inputs[0];
2493
+ if (live.run?.taskId === generation && input !== undefined && receipt.request?.resume === false && await ready(tx))
2494
+ (await tx.doc(DeferredWindow, conv.id)).pending = {
2495
+ input,
2496
+ request: receipt.request
2497
+ };
2498
+ }, context);
2499
+ }
2500
+ function deferredRolloverHooks(host, beforeRollover, cut) {
2501
+ return {
2502
+ async onYield(_answer, api, context) {
2503
+ if (!await finishesInFreshWindow(api, context))
2504
+ return;
2505
+ const id = api.conversationId;
2506
+ const conv = await conversation(host(), id, context);
2507
+ await conv.commit(async (tx) => {
2508
+ const pending = (await tx.doc(DeferredWindow, id)).pending;
2509
+ const live = await tx.doc(LiveDoc5, id);
2510
+ if (pending && live.run?.taskId === api.taskId && live.run.inputs.includes(pending.input))
2511
+ (await tx.doc(ToolWindow, api.taskId)).request = pending.request;
2512
+ }, context);
2513
+ },
2514
+ async afterRun(run, api, context) {
2515
+ const pending = await api.snapshot(ToolWindow, api.taskId, context);
2516
+ if (run.reason !== "answer" || pending?.request?.resume !== false || pending.finished)
2517
+ return;
2518
+ const id = api.conversationId;
2519
+ const conv = await conversation(host(), id, context);
2520
+ const ready = async (tx) => {
2521
+ const receipt = await tx.doc(ToolWindow, api.taskId);
2522
+ const live = await tx.doc(LiveDoc5, id);
2523
+ const state = await tx.doc(WindowState, id);
2524
+ return !receipt.finished && receipt.request?.resume === false && live.run?.taskId === api.taskId && live.run.afterRun !== undefined && !(await tx.task(api.taskId))?.abortRequested && !state.transition && state.window?.id === receipt.request.window.previous && run.answer === await latestContextEntry(tx, id) && await notesAreFresh(tx, id) && (!receipt.request.role || await roleSourceMatches(tx, id, receipt.request.role)) && (await foreignTasks(tx, id)).every((task) => task === api.taskId);
2525
+ };
2526
+ const prep = await prepareRollover(conv, api.taskId, beforeRollover, {
2527
+ conversationId: id,
2528
+ windowId: pending.request.window.previous ?? "",
2529
+ nextWindowId: pending.request.window.id,
2530
+ reason: "tool"
2531
+ }, ready, context);
2532
+ await conv.commit(async (tx) => {
2533
+ const receipt = await tx.doc(ToolWindow, api.taskId);
2534
+ if (!receipt.request || receipt.finished)
2535
+ return;
2536
+ const safe = !prep.error && await ready(tx);
2537
+ receipt.finished = true;
2538
+ const deferred = await tx.doc(DeferredWindow, id);
2539
+ if (deferred.pending?.request.tool === receipt.request.tool)
2540
+ delete deferred.pending;
2541
+ if (safe)
2542
+ await cut(tx, id, receipt.request);
2543
+ else
2544
+ await tx.appendEntry(id, {
2545
+ kind: "howaboua.context.rollover-skipped",
2546
+ data: {
2547
+ windowId: receipt.request.window.id,
2548
+ reason: prep.error ?? "Conversation changed before the completed reply could roll over"
2549
+ }
2550
+ });
2551
+ }, context);
2552
+ }
2553
+ };
2554
+ }
2555
+
2192
2556
  // packages/context/src/usage.ts
2193
2557
  import { estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
2194
2558
  async function contextUsage(conversation, models, context, answer) {
@@ -2250,14 +2614,14 @@ function reportedTokens(message) {
2250
2614
  function checkpointGuidance(newContextRequests) {
2251
2615
  const rollover = newContextRequests === "off" ? "Agent-requested context windows are disabled." : newContextRequests === "pi-limits" ? "Request a new context window only when the host reports eligible history." : "Before requesting a new context window, save current state and wait for the write to succeed.";
2252
2616
  return [
2253
- "Notes are recovery state, not a diary. Write checkpoints and reports to relative paths in your own notes. Delegates do likewise and return their note paths. Keep one concise, authoritative note per task or topic at a stable path. Task checkpoints cover request, constraints, decisions, status, next steps and history IDs. Use write to replace stale state and mark completion. Link to existing notes instead of copying or summarising their contents. Recording isn't permission to implement.",
2254
- `Batch saves at meaningful milestones, not every reply or intermediate step. ${rollover} For handoffs, save current state and wait for success; include the checkpoint path. After rollover, read the checkpoint, then only needed links. Don't reread notes still in context unless they may have changed. Use history for missing details. If no checkpoint is available, use history to recover missing context.`,
2255
- "Previous skill reads don't carry into this window. Read the skills needed for the current task."
2617
+ "Notes are recovery state, not a diary. Virtual note paths are inaccessible to filesystem tools. Do not store project files or deliverables there. Create notes with relative paths. Maintain one authoritative checkpoint per task or topic with request, constraints, decisions, status, next steps and relevant history IDs. Use notes write to create or replace stale state at milestones, task switches and completion; use append to add to it. Link existing notes instead of duplicating content. Recording does not authorise implementation.",
2618
+ `Do not save every reply or intermediate step. ${rollover} Before handoffs, save the checkpoint and wait for success; include its path. Subagents must maintain their own notes and return paths. After rollover, use notes read to recover the checkpoint, then only necessary links. Do not reread unchanged notes. Use history for missing details.`,
2619
+ "Skill reads do not survive rollover. Reread required skills."
2256
2620
  ].join(`
2257
2621
 
2258
2622
  `);
2259
2623
  }
2260
- var YieldAdvisory = defineDoc6({
2624
+ var YieldAdvisory = defineDoc8({
2261
2625
  kind: "howaboua.context.yield-advisory",
2262
2626
  version: 1,
2263
2627
  scope: "task",
@@ -2274,7 +2638,7 @@ function createContextPolicy(options) {
2274
2638
  const sections = [
2275
2639
  section("context", () => checkpointGuidance(options.newContextRequests)),
2276
2640
  ...options.newContextRequests === "off" || !options.modelRoles ? [] : [
2277
- section("context-roles", (input, context) => renderModelRoles(options.modelRoles, input.conversationId, context))
2641
+ section("context-roles", async (input, context) => renderModelRoles(options.modelRoles, input.conversationId, (await input.read.snapshot(WindowState, input.conversationId, context))?.selectedRole, context))
2278
2642
  ],
2279
2643
  section("context-state", async (input, context) => {
2280
2644
  const [state, hints] = await Promise.all([
@@ -2368,16 +2732,20 @@ function createContextPolicy(options) {
2368
2732
  await refreshRankedHistory(await conversation(api.conversationId, context), options.rankedHistory, context);
2369
2733
  },
2370
2734
  async afterTools(_assistant, _results, api, context) {
2735
+ if (options.taskCompletionRollover && await finishesInFreshWindow(api, context))
2736
+ return;
2371
2737
  await remind(api, context);
2372
2738
  },
2373
2739
  async onYield(answer, api, context) {
2374
2740
  if (options.rankedHistory)
2375
2741
  await refreshRankedHistory(await conversation(api.conversationId, context), options.rankedHistory, context);
2742
+ if (options.taskCompletionRollover && await finishesInFreshWindow(api, context))
2743
+ return;
2376
2744
  const text = await remind(api, context, answer);
2377
- return text ? { continue: text } : undefined;
2745
+ return text ? { kind: "continue", continue: text } : undefined;
2378
2746
  }
2379
2747
  }),
2380
- hook(ToolTask2, {
2748
+ hook(ToolTask3, {
2381
2749
  async beforeTool(_call, api, context) {
2382
2750
  await options.ensureWindow(api.conversationId, context);
2383
2751
  },
@@ -2388,7 +2756,7 @@ function createContextPolicy(options) {
2388
2756
  }),
2389
2757
  hook(CompactionTask, {
2390
2758
  async beforeCompact(compaction) {
2391
- return compaction.reason === "overflow" ? undefined : { decline: true };
2759
+ return compaction.reason === "overflow" ? undefined : { kind: "decline" };
2392
2760
  }
2393
2761
  })
2394
2762
  ];
@@ -2398,39 +2766,68 @@ function createContextPolicy(options) {
2398
2766
  // packages/context/src/tool-rollover.ts
2399
2767
  import {
2400
2768
  configure,
2401
- defineDoc as defineDoc7,
2402
2769
  defineTool as defineTool4,
2403
2770
  GenerationTask as GenerationTask4,
2404
2771
  hook as hook2,
2405
2772
  InboxDoc as InboxDoc2,
2406
- LiveDoc as LiveDoc4
2773
+ LiveDoc as LiveDoc6
2407
2774
  } from "@earendil-works/pi-durable";
2408
- var ToolWindow = defineDoc7({
2409
- kind: "howaboua.context.tool-window",
2410
- version: 1,
2411
- scope: "task",
2412
- checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
2413
- initial: () => ({})
2414
- });
2775
+ async function requestAdmission(tx, id, tool) {
2776
+ const live = await tx.doc(LiveDoc6, id);
2777
+ const slot = live.tools?.length === 1 ? live.tools[0] : undefined;
2778
+ if (live.run && slot) {
2779
+ if (slot.taskId === tool)
2780
+ return { run: live.run };
2781
+ const execution = await admittedExecutionCall(tx, id, tool);
2782
+ if (execution && execution.tool === slot.taskId && execution.call === slot.callId)
2783
+ return { run: live.run, execution };
2784
+ }
2785
+ throw new Error("Call new_context alone or after a successful notes write in the same foreground cell");
2786
+ }
2787
+ async function checkpointSettled(tx, id, request) {
2788
+ if (!await notesAreFresh(tx, id))
2789
+ return false;
2790
+ const nested = request.nested;
2791
+ return nested ? await successfulTask(tx, request.tool, nested.cell) && await successfulTask(tx, nested.cell) && await isCurrentCheckpoint(tx, id, nested.checkpoint) : notesPrecedeRequest(tx, id, request.tool);
2792
+ }
2415
2793
  function createToolRollover(host, now, policy) {
2794
+ async function cut(tx, id, request) {
2795
+ const state = await tx.doc(WindowState, id);
2796
+ if (request.role) {
2797
+ state.selectedRole = request.role.id;
2798
+ await configure(tx, id, {
2799
+ model: request.role.model,
2800
+ thinkingLevel: request.role.thinkingLevel
2801
+ });
2802
+ }
2803
+ const window = { ...request.window, startedAt: now() };
2804
+ const entry = await tx.appendEntry(WindowEntry, id, {
2805
+ data: window,
2806
+ head: "self"
2807
+ });
2808
+ state.window = window;
2809
+ state.entry = entry.id;
2810
+ state.reminded = 0;
2811
+ delete state.settlement;
2812
+ }
2416
2813
  const tool = defineTool4({
2417
2814
  name: "new_context",
2418
- description: "Start fresh from saved notes; recover earlier conversation through history. Save notes first and call alone",
2419
- parameters: newContextParameters,
2420
- prepareArguments: prepareNewContextArguments,
2815
+ description: "Start fresh context window. Must save notes first and call alone",
2816
+ parameters: newContextParameters(policy.taskCompletionRollover),
2817
+ prepareArguments: (input) => prepareNewContextArguments(input, policy.taskCompletionRollover),
2421
2818
  replay: "safe",
2422
- callers: ["model"],
2819
+ callers: ["model", "tools"],
2423
2820
  executionMode: "sequential",
2424
2821
  async execute(args, api, context) {
2425
2822
  if (policy.newContextRequests === "pi-limits") {
2426
- const live = await api.snapshot(LiveDoc4, api.conversationId, context);
2427
- if (!live?.run || live.tools?.length !== 1 || live.tools[0]?.taskId !== api.taskId)
2428
- throw new Error("Call new_context alone in its native tool round");
2429
- const prior = live?.run ? await api.snapshot(ToolWindow, live.run.taskId, context) : undefined;
2823
+ const prior = await api.commit(async (tx) => {
2824
+ const { run } = await requestAdmission(tx, api.conversationId, api.taskId);
2825
+ return (await tx.doc(ToolWindow, run.taskId)).request?.tool === api.taskId;
2826
+ }, context);
2430
2827
  const hasEligibleContextHistory = policy.hasEligibleContextHistory;
2431
2828
  if (!hasEligibleContextHistory)
2432
2829
  throw new Error("pi-limits requires hasEligibleContextHistory from the host");
2433
- if (!prior?.request && !await hasEligibleContextHistory(api.conversationId, context))
2830
+ if (!prior && !await hasEligibleContextHistory(api.conversationId, context))
2434
2831
  return {
2435
2832
  output: [
2436
2833
  {
@@ -2443,26 +2840,41 @@ function createToolRollover(host, now, policy) {
2443
2840
  ]
2444
2841
  };
2445
2842
  }
2446
- const live = await api.snapshot(LiveDoc4, api.conversationId, context);
2843
+ const live = await api.snapshot(LiveDoc6, api.conversationId, context);
2447
2844
  const prior = live?.run ? await api.snapshot(ToolWindow, live.run.taskId, context) : undefined;
2448
- const role = prior?.request ? prior.request.role : args.role === undefined ? undefined : await prepareRole(policy.modelRoles, args.role, api.conversationId, await api.agent(context), api.models, context);
2845
+ const role = prior?.request?.tool === api.taskId ? prior.request.role : args.role === undefined ? undefined : await prepareRole(policy.modelRoles, args.role, api.conversationId, await api.agent(context), api.models, context);
2449
2846
  const result = await api.commit(async (tx) => {
2450
- const live = await tx.doc(LiveDoc4, api.conversationId);
2451
- if (!live.run || live.tools?.length !== 1 || live.tools[0]?.taskId !== api.taskId)
2452
- throw new Error("Call new_context alone in its native tool round");
2847
+ const { run, execution } = await requestAdmission(tx, api.conversationId, api.taskId);
2848
+ const deferred = policy.taskCompletionRollover ? (await tx.doc(DeferredWindow, api.conversationId)).pending : undefined;
2849
+ if (deferred && run.inputs.includes(deferred.input))
2850
+ throw new Error("A context rollover is already scheduled for this reply");
2851
+ if (args.resume === false && run.inputs.length === 0)
2852
+ throw new Error("A deferred rollover needs an active input submission");
2453
2853
  const state = await tx.doc(WindowState, api.conversationId);
2454
2854
  if (!state.window || state.transition)
2455
2855
  throw new Error("Context window is missing or a checkpoint is already in progress");
2456
2856
  if (role && !await roleSourceMatches(tx, api.conversationId, role))
2457
2857
  throw new Error("The model settings changed. Continue here and request a new role handoff if still needed.");
2458
- if (!await notesAreFresh(tx, api.conversationId))
2858
+ const checkpoint = execution && await sameCellCheckpoint(tx, api.conversationId, api.taskId, execution);
2859
+ const fresh = execution ? checkpoint !== undefined : await notesAreFresh(tx, api.conversationId) && await notesPrecedeRequest(tx, api.conversationId, api.taskId);
2860
+ if (!fresh)
2459
2861
  return {
2460
2862
  status: "checkpoint_required",
2461
2863
  message: "Save the current task checkpoint in your own notes using a relative path, wait for success, then call new_context alone again. Another agent's notes do not save your checkpoint. The current window has not changed."
2462
2864
  };
2463
- const receipt = await tx.doc(ToolWindow, live.run.taskId);
2865
+ const receipt = await tx.doc(ToolWindow, run.taskId);
2866
+ if (receipt.request && receipt.request.tool !== api.taskId)
2867
+ throw new Error("A context rollover is already scheduled for this reply");
2464
2868
  receipt.request ??= {
2465
2869
  tool: api.taskId,
2870
+ ...execution && checkpoint !== undefined ? {
2871
+ nested: {
2872
+ cell: execution.cell,
2873
+ nativeTool: execution.tool,
2874
+ checkpoint
2875
+ }
2876
+ } : {},
2877
+ ...args.resume === false ? { resume: false } : {},
2466
2878
  ...role ? { role } : {},
2467
2879
  window: {
2468
2880
  id: crypto.randomUUID(),
@@ -2471,29 +2883,37 @@ function createToolRollover(host, now, policy) {
2471
2883
  previous: state.window.id
2472
2884
  }
2473
2885
  };
2474
- return { status: "scheduled", window_id: receipt.request.window.id };
2886
+ return {
2887
+ status: "scheduled",
2888
+ window_id: receipt.request.window.id,
2889
+ ...receipt.request.resume === false ? { message: "Finish your reply. No continuation will start." } : {}
2890
+ };
2475
2891
  }, context);
2476
2892
  return { output: [{ type: "text", text: JSON.stringify(result) }] };
2477
2893
  }
2478
2894
  });
2479
2895
  const hooks = [
2480
2896
  hook2(GenerationTask4, {
2481
- async afterTools(_assistant, _results, api, context) {
2897
+ async afterTools(_assistant, results, api, context) {
2482
2898
  const pending = await api.snapshot(ToolWindow, api.taskId, context);
2483
2899
  if (!pending?.request || pending.finished)
2484
2900
  return;
2485
2901
  const conv = await conversation(host(), api.conversationId, context);
2486
- const ready = async (tx) => {
2902
+ const ready = async (tx, arming = false) => {
2487
2903
  const receipt = await tx.doc(ToolWindow, api.taskId);
2488
2904
  if (!receipt.request || receipt.finished)
2489
2905
  return false;
2490
- const live = await tx.doc(LiveDoc4, api.conversationId);
2906
+ const live = await tx.doc(LiveDoc6, api.conversationId);
2491
2907
  const inbox = await tx.doc(InboxDoc2, api.conversationId);
2492
2908
  const state = await tx.doc(WindowState, api.conversationId);
2493
2909
  const slot = live.tools?.[0];
2494
2910
  const generation = await tx.task(api.taskId);
2495
- return live.run?.taskId === api.taskId && !generation?.abortRequested && live.tools?.length === 1 && slot?.taskId === receipt.request.tool && slot.status === "done" && slot.entry !== undefined && inbox.items.length === 0 && !state.transition && state.window?.id === receipt.request.window.previous && await notesAreFresh(tx, api.conversationId) && (!receipt.request.role || await roleSourceMatches(tx, api.conversationId, receipt.request.role)) && (await foreignTasks(tx, api.conversationId)).every((id) => id === api.taskId);
2911
+ return live.run?.taskId === api.taskId && !generation?.abortRequested && live.tools?.length === 1 && slot?.taskId === (receipt.request.nested?.nativeTool ?? receipt.request.tool) && slot.status === "done" && slot.entry !== undefined && slot.entry === results[0] && (await tx.entry(slot.entry))?.model?.some((message) => message.role === "toolResult" && message.toolCallId === slot.callId && !message.isError) === true && (arming || inbox.items.length === 0) && !state.transition && state.window?.id === receipt.request.window.previous && await checkpointSettled(tx, api.conversationId, receipt.request) && (!receipt.request.role || await roleSourceMatches(tx, api.conversationId, receipt.request.role)) && (arming || (await foreignTasks(tx, api.conversationId)).every((id) => id === api.taskId));
2496
2912
  };
2913
+ if (pending.request.resume === false) {
2914
+ await armDeferredWindow(conv, api.taskId, (tx) => ready(tx, true), context);
2915
+ return;
2916
+ }
2497
2917
  const preparation = await prepareRollover(conv, api.taskId, policy.beforeRollover, {
2498
2918
  conversationId: api.conversationId,
2499
2919
  windowId: pending.request.window.previous ?? "",
@@ -2504,25 +2924,10 @@ function createToolRollover(host, now, policy) {
2504
2924
  const receipt = await tx.doc(ToolWindow, api.taskId);
2505
2925
  if (!receipt.request || receipt.finished)
2506
2926
  return;
2507
- const state = await tx.doc(WindowState, api.conversationId);
2508
2927
  const safe = !preparation.error && await ready(tx) && (preparation.head === undefined || preparation.head === await latestContextEntry(tx, api.conversationId));
2509
2928
  receipt.finished = true;
2510
- if (safe) {
2511
- if (receipt.request.role)
2512
- await configure(tx, api.conversationId, {
2513
- model: receipt.request.role.model,
2514
- thinkingLevel: receipt.request.role.thinkingLevel
2515
- });
2516
- const window = { ...receipt.request.window, startedAt: now() };
2517
- const entry = await tx.appendEntry(WindowEntry, api.conversationId, {
2518
- data: window,
2519
- head: "self"
2520
- });
2521
- state.window = window;
2522
- state.entry = entry.id;
2523
- state.reminded = 0;
2524
- delete state.settlement;
2525
- }
2929
+ if (safe)
2930
+ await cut(tx, api.conversationId, receipt.request);
2526
2931
  await tx.appendEntry(api.conversationId, {
2527
2932
  kind: "howaboua.context.continuation",
2528
2933
  model: [
@@ -2532,15 +2937,23 @@ function createToolRollover(host, now, policy) {
2532
2937
 
2533
2938
  Role: ${receipt.request.role.id}` : ""}` : preparation.error ?? "Context rollover was skipped because the conversation changed or foreground work is still running. The window is unchanged. Save fresh notes and retry new_context after that work settles.",
2534
2939
  timestamp: now()
2535
- }
2940
+ },
2941
+ ...safe ? [
2942
+ {
2943
+ role: "user",
2944
+ content: "[Context management request] Resume from your saved checkpoint.",
2945
+ timestamp: now()
2946
+ }
2947
+ ] : []
2536
2948
  ]
2537
2949
  });
2538
2950
  }, context);
2539
- }
2951
+ },
2952
+ ...policy.taskCompletionRollover ? deferredRolloverHooks(host, policy.beforeRollover, cut) : {}
2540
2953
  })
2541
2954
  ];
2542
2955
  return {
2543
- tool: { ...tool, executionHints: { nativeOnly: true } },
2956
+ tool: { ...tool, executionHints: { nestedHidden: true } },
2544
2957
  hooks
2545
2958
  };
2546
2959
  }
@@ -2569,6 +2982,11 @@ function createContextManagement(options) {
2569
2982
  throw new Error("taskBoundaryReminderTokens must be a non-negative safe integer");
2570
2983
  const now = options.now ?? Date.now;
2571
2984
  const newContextRequests = options.newContextRequests ?? "unrestricted";
2985
+ const tailMode = options.rolloverTail ?? "off";
2986
+ if (tailMode !== "off" && tailMode !== "conversation" && tailMode !== "full")
2987
+ throw new Error("rolloverTail must be off, conversation or full");
2988
+ if (options.taskCompletionRollover !== undefined && typeof options.taskCompletionRollover !== "boolean")
2989
+ throw new Error("taskCompletionRollover must be a boolean");
2572
2990
  if (newContextRequests !== "off" && newContextRequests !== "pi-limits" && newContextRequests !== "unrestricted")
2573
2991
  throw new Error("newContextRequests must be off, pi-limits or unrestricted");
2574
2992
  if (newContextRequests === "pi-limits" && options.hasEligibleContextHistory === undefined)
@@ -2577,7 +2995,8 @@ function createContextManagement(options) {
2577
2995
  const conv = await conversation(host(), id, context);
2578
2996
  await conv.commit((tx) => initializeWindow(tx, id, now()), context);
2579
2997
  };
2580
- const rollover = createRollover(host, options.beforeRollover);
2998
+ const taskCompletionRollover = newContextRequests !== "off" && options.taskCompletionRollover === true;
2999
+ const rollover = createRollover(host, options.beforeRollover, tailMode);
2581
3000
  const input = createInput(host, rollover, idleMinutes * 60 * 1000);
2582
3001
  const policy = createContextPolicy({
2583
3002
  models: options.models,
@@ -2586,6 +3005,7 @@ function createContextManagement(options) {
2586
3005
  ensureWindow,
2587
3006
  taskBoundaryReminderTokens,
2588
3007
  newContextRequests,
3008
+ taskCompletionRollover,
2589
3009
  modelRoles: options.modelRoles,
2590
3010
  archiveHistory: options.archiveHistory === true,
2591
3011
  rankedHistory: options.rankedHistory
@@ -2604,6 +3024,7 @@ function createContextManagement(options) {
2604
3024
  });
2605
3025
  const newContext = createToolRollover(host, now, {
2606
3026
  newContextRequests,
3027
+ taskCompletionRollover,
2607
3028
  modelRoles: options.modelRoles,
2608
3029
  beforeRollover: options.beforeRollover,
2609
3030
  ...options.hasEligibleContextHistory === undefined ? {} : { hasEligibleContextHistory: options.hasEligibleContextHistory }
@@ -2611,7 +3032,7 @@ function createContextManagement(options) {
2611
3032
  const extension = defineExtension({
2612
3033
  name: "howaboua.context",
2613
3034
  tools: [
2614
- notes,
3035
+ ...options.localNotes === false ? [] : [notes],
2615
3036
  history,
2616
3037
  policy.remainingTool,
2617
3038
  ...newContextRequests === "off" ? [] : [newContext.tool]
@@ -2812,9 +3233,12 @@ function configuredOptions(request) {
2812
3233
  const config = request.configuration;
2813
3234
  const allowed = new Set([
2814
3235
  "archiveHistory",
3236
+ "localNotes",
2815
3237
  "automaticIdleRollover",
2816
3238
  "idleRolloverMinutes",
2817
3239
  "taskBoundaryReminderTokens",
3240
+ "taskCompletionRollover",
3241
+ "rolloverTail",
2818
3242
  "newContextRequests",
2819
3243
  "rankedHistory",
2820
3244
  "modelRoles"
@@ -2825,7 +3249,12 @@ function configuredOptions(request) {
2825
3249
  const options = {
2826
3250
  models: request.capabilities.get(modelsCapability)
2827
3251
  };
2828
- for (const key of ["archiveHistory", "automaticIdleRollover"]) {
3252
+ for (const key of [
3253
+ "archiveHistory",
3254
+ "localNotes",
3255
+ "automaticIdleRollover",
3256
+ "taskCompletionRollover"
3257
+ ]) {
2829
3258
  const value = config[key];
2830
3259
  if (value !== undefined) {
2831
3260
  if (typeof value !== "boolean")
@@ -2834,6 +3263,12 @@ function configuredOptions(request) {
2834
3263
  }
2835
3264
  }
2836
3265
  const idle = config["idleRolloverMinutes"];
3266
+ const tail = config["rolloverTail"];
3267
+ if (tail !== undefined) {
3268
+ if (!oneOf(tail, ["off", "conversation", "full"]))
3269
+ throw new Error("rolloverTail must be off, conversation or full");
3270
+ options.rolloverTail = tail;
3271
+ }
2837
3272
  if (idle !== undefined) {
2838
3273
  if (!oneOf(idle, [0, 5, 15, 25, 55, 115, 355, 715]))
2839
3274
  throw new Error("Invalid idleRolloverMinutes");