@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.
package/dist/index.js CHANGED
@@ -2,7 +2,11 @@
2
2
  import { defineExtension } from "@earendil-works/pi-durable";
3
3
 
4
4
  // packages/context/src/admission.ts
5
- import { ConversationBusy, defineTask as defineTask2 } from "@earendil-works/pi-durable";
5
+ import {
6
+ ConversationBusy,
7
+ defineTask as defineTask2,
8
+ LiveDoc as LiveDoc4
9
+ } from "@earendil-works/pi-durable";
6
10
 
7
11
  // packages/context/src/lifecycle.ts
8
12
  import {
@@ -134,8 +138,12 @@ async function until(watch, predicate, signal) {
134
138
  await new Promise((resolve, reject) => {
135
139
  abort = () => reject(signal.reason);
136
140
  signal.addEventListener("abort", abort, { once: true });
137
- watch.start(async (value) => {
138
- if (value && predicate(value))
141
+ watch.start(async (call) => {
142
+ if (call.kind === "failed") {
143
+ reject(call.error);
144
+ return;
145
+ }
146
+ if (predicate(call.value))
139
147
  resolve();
140
148
  });
141
149
  if (signal.aborted)
@@ -143,8 +151,8 @@ async function until(watch, predicate, signal) {
143
151
  else if (watch.value && predicate(watch.value))
144
152
  resolve();
145
153
  watch.closed.then((end) => {
146
- if (end.reason !== "stopped")
147
- reject(new Error(`Context watch ended: ${end.reason}`));
154
+ if (end.kind !== "stopped")
155
+ reject(end.kind === "failed" || end.kind === "listener_error" ? end.error : new Error(`Context watch ended: ${end.kind}`));
148
156
  });
149
157
  });
150
158
  } finally {
@@ -172,11 +180,67 @@ async function cancelPlacedInput(host, conv, id, context) {
172
180
  // packages/context/src/note-store.ts
173
181
  import {
174
182
  createSession,
175
- defineDoc as defineDoc3,
183
+ defineDoc as defineDoc4,
176
184
  defineDocFamily as defineDocFamily2,
177
185
  GenerationTask,
186
+ ToolTask as ToolTask2
187
+ } from "@earendil-works/pi-durable";
188
+
189
+ // packages/execution/src/tool-origin.ts
190
+ import {
191
+ defineDoc as defineDoc3,
178
192
  ToolTask
179
193
  } from "@earendil-works/pi-durable";
194
+ var ToolOriginDoc = defineDoc3({
195
+ kind: "howaboua.tool-origin",
196
+ version: 1,
197
+ scope: "task",
198
+ checkpointWhen: () => false,
199
+ initial: () => ({})
200
+ });
201
+ async function admittedExecutionCall(tx, conversation, child) {
202
+ const task = await tx.task(child);
203
+ if (task?.conversationId !== conversation || task.kind === ToolTask.definition.name || task.owner === undefined)
204
+ return;
205
+ const owner = await tx.task(task.owner);
206
+ if (owner?.conversationId !== conversation || owner.owner !== undefined)
207
+ return;
208
+ const origin = (await tx.doc(ToolOriginDoc, child)).origin;
209
+ if (origin?.conversationId !== conversation)
210
+ return;
211
+ const root = await tx.task(origin.taskId);
212
+ if (root?.conversationId !== conversation || root.kind !== ToolTask.definition.name)
213
+ return;
214
+ const input = root.input;
215
+ if (input.kind !== "nested" && input.callId === origin.callId)
216
+ return { cell: owner.id, tool: root.id, call: origin.callId };
217
+ }
218
+ async function admittedToolRound(tx, conversation, child) {
219
+ let id = child;
220
+ while (id !== undefined) {
221
+ const task = await tx.task(id);
222
+ if (!task || task.conversationId !== conversation)
223
+ return;
224
+ if (task.kind === ToolTask.definition.name) {
225
+ const input = task.input;
226
+ if (input.kind !== "nested")
227
+ return input.assistant;
228
+ } else if (id !== child) {
229
+ return;
230
+ }
231
+ const origin = (await tx.doc(ToolOriginDoc, id)).origin;
232
+ if (origin) {
233
+ if (origin.conversationId !== conversation)
234
+ return;
235
+ const root = await tx.task(origin.taskId);
236
+ if (root?.conversationId !== conversation || root.kind !== ToolTask.definition.name)
237
+ return;
238
+ const input = root.input;
239
+ return input.kind !== "nested" && input.callId === origin.callId ? input.assistant : undefined;
240
+ }
241
+ id = task.owner;
242
+ }
243
+ }
180
244
 
181
245
  // packages/context/src/query-input.ts
182
246
  var actions = {
@@ -231,13 +295,20 @@ function normalizeQueryInput(namespace, input) {
231
295
  if (!input || typeof input !== "object" || Array.isArray(input))
232
296
  throw new Error("Supply an action object; use {} for help");
233
297
  const params = { ...input };
298
+ if (namespace === "history" && params["action"] === undefined && "query" in params)
299
+ params["action"] = "search";
234
300
  const aliases = actions[namespace];
235
301
  const action = aliases[String(params["action"])] ?? params["action"];
236
302
  if (action !== undefined)
237
303
  params["action"] = action;
238
304
  if (namespace === "notes") {
239
- if (action === "write" || action === "append")
305
+ alias(params, "address", "path");
306
+ if (action === "read")
307
+ alias(params, "end_line", "stop_line");
308
+ if (action === "write" || action === "append") {
240
309
  alias(params, "content", "text");
310
+ alias(params, "body", "text");
311
+ }
241
312
  if (action === "list" || action === "search") {
242
313
  alias(params, "prefix", "path");
243
314
  alias(params, "path_prefix", "path");
@@ -250,6 +321,8 @@ function normalizeQueryInput(namespace, input) {
250
321
  alias(params, "max_results", "limit");
251
322
  }
252
323
  const used = usedPresentation[`${namespace}:${String(action)}`] ?? [];
324
+ if (namespace === "history" && action !== "read")
325
+ delete params["offset_chars"];
253
326
  for (const hint of presentation)
254
327
  if (!used.includes(hint))
255
328
  delete params[hint];
@@ -266,7 +339,7 @@ function isNoteWrite(input) {
266
339
  }
267
340
 
268
341
  // packages/context/src/note-store.ts
269
- var NotesState = defineDoc3({
342
+ var NotesState = defineDoc4({
270
343
  kind: "howaboua.context.notes-state",
271
344
  version: 1,
272
345
  scope: "conversation",
@@ -285,7 +358,7 @@ var NoteFile = defineDocFamily2({
285
358
  fork: "asOf",
286
359
  initial: () => ({ text: "" })
287
360
  });
288
- var WriteReceipt = defineDoc3({
361
+ var WriteReceipt = defineDoc4({
289
362
  kind: "howaboua.context.note-write-receipt",
290
363
  version: 1,
291
364
  scope: "task",
@@ -328,14 +401,30 @@ async function requireNotesWindow(tx, id) {
328
401
  async function readNoteText(tx, id, path) {
329
402
  return (await tx.doc(NoteFile, id, path, null)).text;
330
403
  }
331
- async function notesAreFresh(tx, id) {
404
+ async function freshNote(tx, id) {
332
405
  const userEntry = await latestUserEntry(tx, id);
333
406
  const window = await tx.doc(WindowState, id);
334
407
  const state = await tx.doc(NotesState, id);
335
408
  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;
336
- if (!fresh || !state.lastWrite)
409
+ return fresh ? state.lastWrite : undefined;
410
+ }
411
+ async function successfulTask(tx, id, owner) {
412
+ const task = await tx.task(id);
413
+ if (!task || owner !== undefined && task.owner !== owner || task.abortRequested || task.state.status !== "terminal" || task.state.outcome.status !== "completed")
337
414
  return false;
338
- let owner = state.lastWrite.taskId;
415
+ const result = task.state.outcome.result;
416
+ return !(result && typeof result === "object" && !Array.isArray(result) && result["isError"] === true);
417
+ }
418
+ async function sameCellCheckpoint(tx, id, request, execution) {
419
+ const saved = await freshNote(tx, id);
420
+ 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))
421
+ return saved.taskId;
422
+ }
423
+ async function notesAreFresh(tx, id) {
424
+ const lastWrite = await freshNote(tx, id);
425
+ if (!lastWrite)
426
+ return false;
427
+ let owner = lastWrite.taskId;
339
428
  while (owner !== undefined) {
340
429
  const task = await tx.task(owner);
341
430
  if (!task)
@@ -348,7 +437,7 @@ async function notesAreFresh(tx, id) {
348
437
  if (result && typeof result === "object" && !Array.isArray(result)) {
349
438
  if (result["isError"] === true)
350
439
  return false;
351
- if (task.kind === ToolTask.definition.name && "entryId" in result) {
440
+ if (task.kind === ToolTask2.definition.name && "entryId" in result) {
352
441
  const entryId = result["entryId"];
353
442
  if (typeof entryId === "number") {
354
443
  const entry = await tx.entry(entryId);
@@ -363,11 +452,11 @@ async function notesAreFresh(tx, id) {
363
452
  do {
364
453
  const page = await tx.scanTasks({
365
454
  conversationId: id,
366
- kind: ToolTask.definition.name,
455
+ kind: ToolTask2.definition.name,
367
456
  order: "descending"
368
457
  }, 64, cursor);
369
458
  for (const task of page.items) {
370
- if (task.id <= state.lastWrite.taskId)
459
+ if (task.id <= lastWrite.taskId)
371
460
  return true;
372
461
  const input = task.input;
373
462
  let call = input.kind === "nested" ? input.call : undefined;
@@ -382,6 +471,59 @@ async function notesAreFresh(tx, id) {
382
471
  } while (cursor !== undefined);
383
472
  return true;
384
473
  }
474
+ async function isCurrentCheckpoint(tx, id, checkpoint) {
475
+ return (await freshNote(tx, id))?.taskId === checkpoint;
476
+ }
477
+ async function latestNoteRound(tx, id) {
478
+ const saved = (await tx.doc(NotesState, id)).lastWrite;
479
+ if (!saved)
480
+ return;
481
+ let owner = saved.taskId;
482
+ let savedAssistant = saved.assistantEntry;
483
+ while (owner !== undefined) {
484
+ const task = await tx.task(owner);
485
+ if (!task || task.kind === GenerationTask.definition.name)
486
+ break;
487
+ if (task.kind === ToolTask2.definition.name) {
488
+ const call = task.input;
489
+ if (call.kind !== "nested")
490
+ savedAssistant = call.assistant;
491
+ }
492
+ owner = task.owner;
493
+ }
494
+ return savedAssistant;
495
+ }
496
+ async function notesPrecedeRequest(tx, id, request) {
497
+ const requesting = await tx.task(request);
498
+ if (requesting?.kind !== ToolTask2.definition.name)
499
+ return false;
500
+ const input = requesting.input;
501
+ if (input.kind === "nested")
502
+ return false;
503
+ const savedAssistant = await latestNoteRound(tx, id);
504
+ if (savedAssistant === undefined)
505
+ return false;
506
+ const completed = new Map;
507
+ let cursor;
508
+ do {
509
+ const page = await tx.scanEntries({ conversationId: id, maxEntryId: input.assistant }, 64, cursor);
510
+ for (const entry of page.items) {
511
+ if (entry.id === input.assistant)
512
+ continue;
513
+ for (const message of entry.model ?? []) {
514
+ if (message.role === "toolResult")
515
+ completed.set(message.toolCallId, !message.isError);
516
+ if (message.role !== "assistant")
517
+ continue;
518
+ const calls = message.content.filter((block) => block.type === "toolCall");
519
+ if (calls.length)
520
+ return entry.id === savedAssistant && calls.every((call) => completed.has(call.id) && (call.name !== "notes" || !isNoteWrite(call.arguments) || completed.get(call.id) === true));
521
+ }
522
+ }
523
+ cursor = page.next;
524
+ } while (cursor !== undefined);
525
+ return false;
526
+ }
385
527
  async function beginNoteWrite(tx, id, taskId) {
386
528
  const receipt = await tx.doc(WriteReceipt, taskId);
387
529
  if (receipt.attempted || receipt.file)
@@ -418,9 +560,13 @@ async function mutateNote(tx, input) {
418
560
  nextCatalog.push(metadata);
419
561
  else
420
562
  nextCatalog[index] = metadata;
563
+ const assistantEntry = await admittedToolRound(tx, input.conversationId, input.taskId);
564
+ const execution = await admittedExecutionCall(tx, input.conversationId, input.taskId);
421
565
  const freshness = {
422
566
  windowId,
423
567
  userEntry,
568
+ ...assistantEntry === undefined ? {} : { assistantEntry },
569
+ ...execution === undefined ? {} : { execution },
424
570
  taskId: input.taskId,
425
571
  updatedAt
426
572
  };
@@ -442,7 +588,7 @@ function noteMetadata(file) {
442
588
  async function renderNotesThreadHint(reader, id, context, maxBytes = 4000) {
443
589
  const state = await reader.snapshot(NotesState, id, context);
444
590
  const files = [...state?.files ?? []].sort((left, right) => right.updatedAt - left.updatedAt || left.path.localeCompare(right.path));
445
- const header = "Recent notes (up to 5, most-recent first). More may exist; use notes list or search:";
591
+ const header = "Recent notes in virtual storage (up to 5, most-recent first). More may exist; use notes list or search:";
446
592
  const lines = [];
447
593
  for (const file of files) {
448
594
  if (lines.length >= 5)
@@ -469,13 +615,24 @@ async function startInstruction(tx, id, owner, kind, content, now) {
469
615
  return;
470
616
  await tx.appendEntry(id, {
471
617
  kind,
472
- model: [{ role: "system", content, timestamp: now }]
618
+ model: [
619
+ { role: "system", content, timestamp: now },
620
+ {
621
+ role: "user",
622
+ content: "[Context management request] Carry out the context instructions above.",
623
+ timestamp: now
624
+ }
625
+ ]
473
626
  });
474
627
  const generation = await tx.createTask(GenerationTask2, {}, {
475
628
  ownership: { kind: "task", taskId: owner },
476
629
  conversationId: id
477
630
  });
478
- (await tx.doc(LiveDoc2, id)).run = { taskId: generation, inputs: [] };
631
+ (await tx.doc(LiveDoc2, id)).run = {
632
+ taskId: generation,
633
+ inputs: [],
634
+ turns: 0
635
+ };
479
636
  return generation;
480
637
  }
481
638
  async function waitInstruction(host, id, generation, context) {
@@ -531,9 +688,9 @@ async function instructionAnswer(tx, id) {
531
688
 
532
689
  // packages/context/src/rollover-preparation.ts
533
690
  import {
534
- defineDoc as defineDoc4
691
+ defineDoc as defineDoc5
535
692
  } from "@earendil-works/pi-durable";
536
- var RolloverPreparation = defineDoc4({
693
+ var RolloverPreparation = defineDoc5({
537
694
  kind: "howaboua.context.rollover-preparation",
538
695
  version: 1,
539
696
  scope: "task",
@@ -598,6 +755,95 @@ async function prepareRollover(conversation, taskId, callback, request, ready, c
598
755
  return { head };
599
756
  }
600
757
 
758
+ // packages/context/src/rollover-tail.ts
759
+ function visibleConversation(message) {
760
+ if (message.role === "user")
761
+ return message;
762
+ if (message.role !== "assistant")
763
+ return;
764
+ const content = message.content.filter((part) => part.type === "text");
765
+ if (!content.length)
766
+ return;
767
+ return content.length === message.content.length ? message : { ...message, content, stopReason: "stop" };
768
+ }
769
+ function completeMessages(carriers) {
770
+ const complete = new Set;
771
+ let group;
772
+ const finish = () => {
773
+ if (group && group.calls.size === group.results.size) {
774
+ complete.add(group.assistant);
775
+ for (const result of group.results.values())
776
+ complete.add(result);
777
+ }
778
+ group = undefined;
779
+ };
780
+ for (const carrier of carriers) {
781
+ if (carrier.control)
782
+ continue;
783
+ for (const message of carrier.messages) {
784
+ if (message.role === "assistant") {
785
+ finish();
786
+ const calls = message.content.flatMap((part) => part.type === "toolCall" ? [[part.id, part.name]] : []);
787
+ const byId = new Map(calls);
788
+ if (byId.size !== calls.length)
789
+ continue;
790
+ group = {
791
+ assistant: message,
792
+ calls: byId,
793
+ results: new Map
794
+ };
795
+ } else if (message.role === "user") {
796
+ finish();
797
+ } else if (message.role === "toolResult" && group?.calls.get(message.toolCallId) === message.toolName && !group.results.has(message.toolCallId)) {
798
+ group.results.set(message.toolCallId, message);
799
+ }
800
+ }
801
+ }
802
+ finish();
803
+ return complete;
804
+ }
805
+ async function projectRolloverTail(conv, mode, context) {
806
+ const { head, tip } = await conv.commit(async (tx) => ({
807
+ head: await latestNoteRound(tx, conv.id),
808
+ tip: await latestContextEntry(tx, conv.id)
809
+ }), context);
810
+ if (head === undefined || tip === null || head >= tip)
811
+ return;
812
+ const view = await conv.context(context, { at: tip });
813
+ const start = view.entries.findIndex((entry) => entry.id === head && entry.head === undefined);
814
+ if (start < 0)
815
+ return;
816
+ const carriers = view.entries.slice(start).map((entry, index) => ({
817
+ id: entry.id,
818
+ messages: view.contributions[start + index] ?? [],
819
+ control: entry.kind === "pi.system" || entry.kind.startsWith("howaboua.context.")
820
+ }));
821
+ const complete = completeMessages(carriers);
822
+ const saved = carriers[0]?.messages.find((message) => message.role === "assistant");
823
+ const last = carriers.findLast((carrier) => !carrier.control && carrier.messages.length > 0)?.messages.at(-1);
824
+ if (!saved || !complete.has(saved) || last?.role !== "assistant" || last.stopReason !== "stop" || last.content.some((part) => part.type === "toolCall"))
825
+ return;
826
+ const edits = [];
827
+ for (const carrier of carriers) {
828
+ if (!carrier.messages.length)
829
+ continue;
830
+ const messages = carrier.control ? [] : carrier.messages.flatMap((message) => {
831
+ if (message.role === "system")
832
+ return [];
833
+ const projected = mode === "full" && complete.has(message) ? message : visibleConversation(message);
834
+ return projected ? [projected] : [];
835
+ });
836
+ if (!messages.length)
837
+ edits.push({ target: carrier.id, action: "omit" });
838
+ else if (messages.length !== carrier.messages.length || messages.some((message, index) => message !== carrier.messages[index]))
839
+ edits.push({ target: carrier.id, action: "replace", messages });
840
+ }
841
+ return { head, tip, edits };
842
+ }
843
+ async function rolloverTailMatches(tx, conv, tail) {
844
+ return tail.tip === await latestContextEntry(tx, conv.id) && tail.head === await latestNoteRound(tx, conv.id);
845
+ }
846
+
601
847
  // packages/context/src/rollover.ts
602
848
  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.";
603
849
  var key = (task) => `context:checkpoint:${task}`;
@@ -624,7 +870,7 @@ async function completedFreshNotes(host, id, context) {
624
870
  } while (cursor !== undefined);
625
871
  return done;
626
872
  }
627
- function createRollover(host, beforeRollover) {
873
+ function createRollover(host, beforeRollover, tailMode = "off") {
628
874
  return defineTask({
629
875
  name: ROLLOVER_TASK,
630
876
  version: 1,
@@ -639,7 +885,7 @@ function createRollover(host, beforeRollover) {
639
885
  await Promise.all(tasks.map((id) => runtime.waitForTask(id, context)));
640
886
  }
641
887
  const fresh = await completedFreshNotes(host(), conv.id, context);
642
- if (fresh) {
888
+ if (fresh && (tailMode === "off" || task.input.reason === "idle" || await projectRolloverTail(conv, tailMode, context))) {
643
889
  await runtime.commit(() => ({ status: "running", checkpoint: { phase: "rotate" } }), context);
644
890
  return;
645
891
  }
@@ -740,14 +986,18 @@ function createRollover(host, beforeRollover) {
740
986
  return completed && await nativeIdle(tx, task.conversationId) && (await foreignTasks(tx, task.conversationId)).length === 0 && await notesAreFresh(tx, task.conversationId);
741
987
  };
742
988
  const current = await runtime.snapshot(WindowState, task.conversationId, context);
743
- const preparation = await prepareRollover(conv, task.id, beforeRollover, {
989
+ const keepsTail = tailMode !== "off" && task.input.reason !== "tool";
990
+ const tail = keepsTail ? await projectRolloverTail(conv, tailMode, context) : undefined;
991
+ const preparation = keepsTail && !tail ? {
992
+ error: "No eligible saved checkpoint tail; the current window is unchanged"
993
+ } : await prepareRollover(conv, task.id, beforeRollover, {
744
994
  conversationId: task.conversationId,
745
995
  windowId: current?.window?.id ?? "",
746
996
  nextWindowId: task.input.windowId,
747
997
  reason: task.input.reason
748
- }, ready, context);
998
+ }, async (tx) => await ready(tx) && (!tail || await rolloverTailMatches(tx, conv, tail)), context);
749
999
  await runtime.commit(async (tx) => {
750
- const safe = !preparation.error && await ready(tx) && (preparation.head === undefined || preparation.head === await latestContextEntry(tx, task.conversationId));
1000
+ const safe = !preparation.error && await ready(tx) && (!tail || await rolloverTailMatches(tx, conv, tail)) && (preparation.head === undefined || preparation.head === await latestContextEntry(tx, task.conversationId));
751
1001
  const state = await tx.doc(WindowState, task.conversationId);
752
1002
  if (!safe || !state.window) {
753
1003
  delete state.transition;
@@ -770,7 +1020,7 @@ function createRollover(host, beforeRollover) {
770
1020
  };
771
1021
  const entry = await tx.appendEntry(WindowEntry, task.conversationId, {
772
1022
  data: window,
773
- head: "self"
1023
+ ...tail ? { head: tail.head, edits: tail.edits } : { head: "self" }
774
1024
  });
775
1025
  state.window = window;
776
1026
  state.entry = entry.id;
@@ -1011,7 +1261,8 @@ function createInput(host, rollover, idleMs) {
1011
1261
  const userEntry = await latestUserEntry(tx, task.conversationId);
1012
1262
  const idle = await nativeIdle(tx, task.conversationId);
1013
1263
  const state = await tx.doc(WindowState, task.conversationId);
1014
- if (idle && !state.transition)
1264
+ const answered = !idle && settled.status === "done" && (await tx.doc(LiveDoc4, task.conversationId)).run?.afterRun !== undefined && settled.answer === await latestContextEntry(tx, task.conversationId);
1265
+ if ((idle || answered) && !state.transition)
1015
1266
  state.settlement = {
1016
1267
  observedAt: runtime.now(),
1017
1268
  userEntry,
@@ -1080,9 +1331,9 @@ import {
1080
1331
  import { Type as Type2 } from "typebox";
1081
1332
 
1082
1333
  // internal/context-visibility.ts
1083
- import { createSession as createSession2, defineDoc as defineDoc5 } from "@earendil-works/pi-durable";
1334
+ import { createSession as createSession2, defineDoc as defineDoc6 } from "@earendil-works/pi-durable";
1084
1335
  var SHARED_GROUP = "shared";
1085
- var ContextVisibility = defineDoc5({
1336
+ var ContextVisibility = defineDoc6({
1086
1337
  kind: "howaboua.context.visibility",
1087
1338
  version: 1,
1088
1339
  scope: "conversation",
@@ -1236,21 +1487,6 @@ import {
1236
1487
  // packages/context/src/tool-contract.ts
1237
1488
  import { Type } from "typebox";
1238
1489
  import { Check } from "typebox/value";
1239
- var HISTORY_ACTIONS = [
1240
- "help",
1241
- "list_windows",
1242
- "list",
1243
- "read",
1244
- "search"
1245
- ];
1246
- var NOTES_ACTIONS = [
1247
- "help",
1248
- "list",
1249
- "read",
1250
- "search",
1251
- "append",
1252
- "write"
1253
- ];
1254
1490
  var contextOutputLimits = { maxBytes: Infinity, maxLines: Infinity };
1255
1491
  function contextTextSlice(text, offset, limit) {
1256
1492
  if (offset > 0 && (text.codePointAt(offset - 1) ?? 0) > 65535)
@@ -1275,7 +1511,13 @@ var target = Type.Optional(Type.String({
1275
1511
  description: "Durable conversation ID; defaults to caller"
1276
1512
  }));
1277
1513
  var historyParameters = Type.Object({
1278
- action: Type.Optional(Type.Union(HISTORY_ACTIONS.map((action) => Type.Literal(action)))),
1514
+ action: Type.Optional(Type.Union([
1515
+ Type.Literal("help"),
1516
+ Type.Literal("list_windows"),
1517
+ Type.Literal("list"),
1518
+ Type.Literal("read"),
1519
+ Type.Literal("search")
1520
+ ])),
1279
1521
  target,
1280
1522
  item_id: Type.Optional(Type.String()),
1281
1523
  agent_name: Type.Optional(nullableString),
@@ -1300,7 +1542,14 @@ var historyParameters = Type.Object({
1300
1542
  }))
1301
1543
  }, { additionalProperties: false });
1302
1544
  var notesParameters = Type.Object({
1303
- action: Type.Optional(Type.Union(NOTES_ACTIONS.map((action) => Type.Literal(action)))),
1545
+ action: Type.Optional(Type.Union([
1546
+ Type.Literal("help"),
1547
+ Type.Literal("list"),
1548
+ Type.Literal("read"),
1549
+ Type.Literal("search"),
1550
+ Type.Literal("append"),
1551
+ Type.Literal("write")
1552
+ ])),
1304
1553
  target,
1305
1554
  agent_name: Type.Optional(nullableString),
1306
1555
  file_order: Type.Optional(Type.Union([Type.Literal("ascending"), Type.Literal("descending")])),
@@ -1312,7 +1561,7 @@ var notesParameters = Type.Object({
1312
1561
  limit: Type.Optional(positiveInteger),
1313
1562
  max_matches_per_file: Type.Optional(positiveInteger),
1314
1563
  path: Type.Optional(Type.Union([Type.String(), Type.Null()], {
1315
- description: "File for read/write/append; prefix for list/search"
1564
+ description: "Virtual note path, not a project file; prefix for list/search"
1316
1565
  })),
1317
1566
  query: Type.Optional(Type.String()),
1318
1567
  recent_file_first: Type.Optional(Type.Boolean()),
@@ -1322,11 +1571,23 @@ var notesParameters = Type.Object({
1322
1571
  offset_chars: Type.Optional(Type.Integer({ minimum: 0 })),
1323
1572
  text: Type.Optional(Type.String())
1324
1573
  }, { additionalProperties: false });
1325
- var newContextParameters = Type.Object({ role: Type.Optional(Type.String({ minLength: 1 })) }, { additionalProperties: false });
1326
- function prepareNewContextArguments(input) {
1574
+ function newContextParameters(taskCompletionRollover) {
1575
+ return Type.Object({
1576
+ ...taskCompletionRollover ? {
1577
+ resume: Type.Optional(Type.Boolean({
1578
+ description: "False: finish this reply, then wait in a fresh window"
1579
+ }))
1580
+ } : {},
1581
+ role: Type.Optional(Type.String({
1582
+ minLength: 1,
1583
+ description: "Configured model-role ID, not an agent name or handoff text"
1584
+ }))
1585
+ }, { additionalProperties: false });
1586
+ }
1587
+ function prepareNewContextArguments(input, taskCompletionRollover) {
1327
1588
  const args = input ?? {};
1328
- if (!Check(newContextParameters, args))
1329
- throw new Error('Use {} to keep the current model, or {role: "name"} for a configured role.');
1589
+ if (!Check(newContextParameters(taskCompletionRollover), args))
1590
+ 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.');
1330
1591
  return args;
1331
1592
  }
1332
1593
  function prepareNotesArguments(input) {
@@ -1385,6 +1646,9 @@ function contextToolHelp(namespace, args, rankedHistory = false) {
1385
1646
  throw new Error("Help accepts only action: help");
1386
1647
  const fields = namespace === "notes" ? notesFields : historyFields;
1387
1648
  return {
1649
+ ...namespace === "notes" ? {
1650
+ results: "list: files; search: files[].matches; read: file.content or file=null; write/append: file.path"
1651
+ } : {},
1388
1652
  actions: Object.fromEntries(Object.entries(fields).map(([action, names]) => [
1389
1653
  action,
1390
1654
  names.map((name) => (name === "path" ? ["read", "write", "append"].includes(action) : ["text", "query", "item_id"].includes(name)) || action === "read" && name === "window_id" ? name : `${name}?`).join(" ")
@@ -1392,13 +1656,13 @@ function contextToolHelp(namespace, args, rankedHistory = false) {
1392
1656
  target: "Durable conversation ID; defaults to caller; reads require the same Context visibility group; write own",
1393
1657
  ...namespace === "notes" ? {
1394
1658
  writes: "write replaces; append adds",
1395
- paths: "Paths are relative to /notes; target selects a conversation, read-only unless your own",
1659
+ paths: "Virtual note paths, inaccessible to filesystem tools. Relative to /notes; target selects a conversation, read-only unless your own",
1396
1660
  usage: '{ "action": "read", "path": "checkpoint" }',
1397
1661
  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",
1398
1662
  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",
1399
1663
  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"
1400
1664
  } : {
1401
- usage: "Search earlier conversation, don't browse it. Pass returned IDs unchanged",
1665
+ usage: "With query, action defaults to search. Search past chat, don't browse it. Pass returned IDs unchanged",
1402
1666
  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"
1403
1667
  }
1404
1668
  };
@@ -1628,7 +1892,7 @@ var refreshFailures = new WeakMap;
1628
1892
  function createHistoryTool(options) {
1629
1893
  const tool = defineTool({
1630
1894
  name: "history",
1631
- description: "Search earlier conversation",
1895
+ description: "Search past chat",
1632
1896
  parameters: historyParameters,
1633
1897
  structuredOutputSchema: Type2.Object({}, { additionalProperties: true }),
1634
1898
  prepareArguments: prepareHistoryArguments,
@@ -1895,13 +2159,15 @@ async function waitForInputPlacement(host, id, context) {
1895
2159
  revision++;
1896
2160
  wake?.();
1897
2161
  };
1898
- const unsubscribe = host.harness.subscribeCommits((publication) => {
1899
- if (publication.changes.some((change) => change.type === "task" && change.value.id === id || change.type === "submission" && change.value.requestId === requestId))
2162
+ const observation = host.harness.observeCommits({
2163
+ advance(publication) {
2164
+ if (publication.changes.some((change) => change.type === "task" && change.value.id === id || change.type === "submission" && change.value.requestId === requestId))
2165
+ changed();
2166
+ },
2167
+ end() {
2168
+ closing = true;
1900
2169
  changed();
1901
- });
1902
- const stopClose = host.harness.subscribeClose(() => {
1903
- closing = true;
1904
- changed();
2170
+ }
1905
2171
  });
1906
2172
  try {
1907
2173
  while (true) {
@@ -1948,8 +2214,7 @@ async function waitForInputPlacement(host, id, context) {
1948
2214
  });
1949
2215
  }
1950
2216
  } finally {
1951
- unsubscribe();
1952
- stopClose();
2217
+ observation.detach();
1953
2218
  }
1954
2219
  }
1955
2220
 
@@ -1992,7 +2257,7 @@ function normalize(input, prefix) {
1992
2257
  function createNotesTool(options) {
1993
2258
  const tool = defineTool2({
1994
2259
  name: "notes",
1995
- description: "Persistent notes for handing off task state between context windows",
2260
+ description: "Virtual filesystem task checkpoints",
1996
2261
  parameters: notesParameters,
1997
2262
  structuredOutputSchema: Type3.Object({}, { additionalProperties: true }),
1998
2263
  prepareArguments: prepareNotesArguments,
@@ -2132,15 +2397,21 @@ function lineIndex(value, count, fallback) {
2132
2397
  // packages/context/src/policy.ts
2133
2398
  import {
2134
2399
  CompactionTask,
2135
- defineDoc as defineDoc6,
2400
+ defineDoc as defineDoc8,
2136
2401
  defineTool as defineTool3,
2137
2402
  GenerationTask as GenerationTask3,
2138
2403
  hook,
2139
2404
  section,
2140
- ToolTask as ToolTask2
2405
+ ToolTask as ToolTask3
2141
2406
  } from "@earendil-works/pi-durable";
2142
2407
  import { Type as Type4 } from "typebox";
2143
2408
 
2409
+ // packages/context/src/deferred-rollover.ts
2410
+ import {
2411
+ defineDoc as defineDoc7,
2412
+ LiveDoc as LiveDoc5
2413
+ } from "@earendil-works/pi-durable";
2414
+
2144
2415
  // packages/context/src/model-roles.ts
2145
2416
  import {
2146
2417
  AgentDoc
@@ -2163,7 +2434,7 @@ async function readRoles(catalog, id, context) {
2163
2434
  reasoning
2164
2435
  }));
2165
2436
  }
2166
- async function renderModelRoles(catalog, id, context) {
2437
+ async function renderModelRoles(catalog, id, selected, context) {
2167
2438
  let roles;
2168
2439
  try {
2169
2440
  roles = await readRoles(catalog, id, context);
@@ -2174,7 +2445,8 @@ async function renderModelRoles(catalog, id, context) {
2174
2445
  if (!roles.length)
2175
2446
  return "No model roles are available. Call new_context without role.";
2176
2447
  return [
2177
- '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.',
2448
+ `Current role: ${selected ?? "none"}`,
2449
+ '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.',
2178
2450
  ...roles.map((role) => `- ${role.id}: ${role.description}`)
2179
2451
  ].join(`
2180
2452
  `);
@@ -2206,6 +2478,98 @@ async function roleSourceMatches(tx, id, role) {
2206
2478
  return current.model?.provider === role.source.model?.provider && current.model?.modelId === role.source.model?.modelId && (current.thinkingLevel ?? "off") === role.source.thinkingLevel;
2207
2479
  }
2208
2480
 
2481
+ // packages/context/src/deferred-rollover.ts
2482
+ var ToolWindow = defineDoc7({
2483
+ kind: "howaboua.context.tool-window",
2484
+ version: 1,
2485
+ scope: "task",
2486
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
2487
+ initial: () => ({})
2488
+ });
2489
+ var DeferredWindow = defineDoc7({
2490
+ kind: "howaboua.context.deferred-window",
2491
+ version: 1,
2492
+ scope: "conversation",
2493
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
2494
+ history: "latest",
2495
+ fork: "initial",
2496
+ initial: () => ({})
2497
+ });
2498
+ async function finishesInFreshWindow(api, context) {
2499
+ const deferred = await api.snapshot(DeferredWindow, api.conversationId, context);
2500
+ if (!deferred?.pending)
2501
+ return false;
2502
+ const live = await api.snapshot(LiveDoc5, api.conversationId, context);
2503
+ return live?.run?.taskId === api.taskId && live.run.inputs.includes(deferred.pending.input);
2504
+ }
2505
+ async function armDeferredWindow(conv, generation, ready, context) {
2506
+ await conv.commit(async (tx) => {
2507
+ const receipt = await tx.doc(ToolWindow, generation);
2508
+ const live = await tx.doc(LiveDoc5, conv.id);
2509
+ const input = live.run?.inputs[0];
2510
+ if (live.run?.taskId === generation && input !== undefined && receipt.request?.resume === false && await ready(tx))
2511
+ (await tx.doc(DeferredWindow, conv.id)).pending = {
2512
+ input,
2513
+ request: receipt.request
2514
+ };
2515
+ }, context);
2516
+ }
2517
+ function deferredRolloverHooks(host, beforeRollover, cut) {
2518
+ return {
2519
+ async onYield(_answer, api, context) {
2520
+ if (!await finishesInFreshWindow(api, context))
2521
+ return;
2522
+ const id = api.conversationId;
2523
+ const conv = await conversation(host(), id, context);
2524
+ await conv.commit(async (tx) => {
2525
+ const pending = (await tx.doc(DeferredWindow, id)).pending;
2526
+ const live = await tx.doc(LiveDoc5, id);
2527
+ if (pending && live.run?.taskId === api.taskId && live.run.inputs.includes(pending.input))
2528
+ (await tx.doc(ToolWindow, api.taskId)).request = pending.request;
2529
+ }, context);
2530
+ },
2531
+ async afterRun(run, api, context) {
2532
+ const pending = await api.snapshot(ToolWindow, api.taskId, context);
2533
+ if (run.reason !== "answer" || pending?.request?.resume !== false || pending.finished)
2534
+ return;
2535
+ const id = api.conversationId;
2536
+ const conv = await conversation(host(), id, context);
2537
+ const ready = async (tx) => {
2538
+ const receipt = await tx.doc(ToolWindow, api.taskId);
2539
+ const live = await tx.doc(LiveDoc5, id);
2540
+ const state = await tx.doc(WindowState, id);
2541
+ 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);
2542
+ };
2543
+ const prep = await prepareRollover(conv, api.taskId, beforeRollover, {
2544
+ conversationId: id,
2545
+ windowId: pending.request.window.previous ?? "",
2546
+ nextWindowId: pending.request.window.id,
2547
+ reason: "tool"
2548
+ }, ready, context);
2549
+ await conv.commit(async (tx) => {
2550
+ const receipt = await tx.doc(ToolWindow, api.taskId);
2551
+ if (!receipt.request || receipt.finished)
2552
+ return;
2553
+ const safe = !prep.error && await ready(tx);
2554
+ receipt.finished = true;
2555
+ const deferred = await tx.doc(DeferredWindow, id);
2556
+ if (deferred.pending?.request.tool === receipt.request.tool)
2557
+ delete deferred.pending;
2558
+ if (safe)
2559
+ await cut(tx, id, receipt.request);
2560
+ else
2561
+ await tx.appendEntry(id, {
2562
+ kind: "howaboua.context.rollover-skipped",
2563
+ data: {
2564
+ windowId: receipt.request.window.id,
2565
+ reason: prep.error ?? "Conversation changed before the completed reply could roll over"
2566
+ }
2567
+ });
2568
+ }, context);
2569
+ }
2570
+ };
2571
+ }
2572
+
2209
2573
  // packages/context/src/usage.ts
2210
2574
  import { estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
2211
2575
  async function contextUsage(conversation, models, context, answer) {
@@ -2267,14 +2631,14 @@ function reportedTokens(message) {
2267
2631
  function checkpointGuidance(newContextRequests) {
2268
2632
  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.";
2269
2633
  return [
2270
- "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.",
2271
- `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.`,
2272
- "Previous skill reads don't carry into this window. Read the skills needed for the current task."
2634
+ "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.",
2635
+ `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.`,
2636
+ "Skill reads do not survive rollover. Reread required skills."
2273
2637
  ].join(`
2274
2638
 
2275
2639
  `);
2276
2640
  }
2277
- var YieldAdvisory = defineDoc6({
2641
+ var YieldAdvisory = defineDoc8({
2278
2642
  kind: "howaboua.context.yield-advisory",
2279
2643
  version: 1,
2280
2644
  scope: "task",
@@ -2291,7 +2655,7 @@ function createContextPolicy(options) {
2291
2655
  const sections = [
2292
2656
  section("context", () => checkpointGuidance(options.newContextRequests)),
2293
2657
  ...options.newContextRequests === "off" || !options.modelRoles ? [] : [
2294
- section("context-roles", (input, context) => renderModelRoles(options.modelRoles, input.conversationId, context))
2658
+ section("context-roles", async (input, context) => renderModelRoles(options.modelRoles, input.conversationId, (await input.read.snapshot(WindowState, input.conversationId, context))?.selectedRole, context))
2295
2659
  ],
2296
2660
  section("context-state", async (input, context) => {
2297
2661
  const [state, hints] = await Promise.all([
@@ -2385,16 +2749,20 @@ function createContextPolicy(options) {
2385
2749
  await refreshRankedHistory(await conversation(api.conversationId, context), options.rankedHistory, context);
2386
2750
  },
2387
2751
  async afterTools(_assistant, _results, api, context) {
2752
+ if (options.taskCompletionRollover && await finishesInFreshWindow(api, context))
2753
+ return;
2388
2754
  await remind(api, context);
2389
2755
  },
2390
2756
  async onYield(answer, api, context) {
2391
2757
  if (options.rankedHistory)
2392
2758
  await refreshRankedHistory(await conversation(api.conversationId, context), options.rankedHistory, context);
2759
+ if (options.taskCompletionRollover && await finishesInFreshWindow(api, context))
2760
+ return;
2393
2761
  const text = await remind(api, context, answer);
2394
- return text ? { continue: text } : undefined;
2762
+ return text ? { kind: "continue", continue: text } : undefined;
2395
2763
  }
2396
2764
  }),
2397
- hook(ToolTask2, {
2765
+ hook(ToolTask3, {
2398
2766
  async beforeTool(_call, api, context) {
2399
2767
  await options.ensureWindow(api.conversationId, context);
2400
2768
  },
@@ -2405,7 +2773,7 @@ function createContextPolicy(options) {
2405
2773
  }),
2406
2774
  hook(CompactionTask, {
2407
2775
  async beforeCompact(compaction) {
2408
- return compaction.reason === "overflow" ? undefined : { decline: true };
2776
+ return compaction.reason === "overflow" ? undefined : { kind: "decline" };
2409
2777
  }
2410
2778
  })
2411
2779
  ];
@@ -2415,39 +2783,68 @@ function createContextPolicy(options) {
2415
2783
  // packages/context/src/tool-rollover.ts
2416
2784
  import {
2417
2785
  configure,
2418
- defineDoc as defineDoc7,
2419
2786
  defineTool as defineTool4,
2420
2787
  GenerationTask as GenerationTask4,
2421
2788
  hook as hook2,
2422
2789
  InboxDoc as InboxDoc2,
2423
- LiveDoc as LiveDoc4
2790
+ LiveDoc as LiveDoc6
2424
2791
  } from "@earendil-works/pi-durable";
2425
- var ToolWindow = defineDoc7({
2426
- kind: "howaboua.context.tool-window",
2427
- version: 1,
2428
- scope: "task",
2429
- checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
2430
- initial: () => ({})
2431
- });
2792
+ async function requestAdmission(tx, id, tool) {
2793
+ const live = await tx.doc(LiveDoc6, id);
2794
+ const slot = live.tools?.length === 1 ? live.tools[0] : undefined;
2795
+ if (live.run && slot) {
2796
+ if (slot.taskId === tool)
2797
+ return { run: live.run };
2798
+ const execution = await admittedExecutionCall(tx, id, tool);
2799
+ if (execution && execution.tool === slot.taskId && execution.call === slot.callId)
2800
+ return { run: live.run, execution };
2801
+ }
2802
+ throw new Error("Call new_context alone or after a successful notes write in the same foreground cell");
2803
+ }
2804
+ async function checkpointSettled(tx, id, request) {
2805
+ if (!await notesAreFresh(tx, id))
2806
+ return false;
2807
+ const nested = request.nested;
2808
+ 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);
2809
+ }
2432
2810
  function createToolRollover(host, now, policy) {
2811
+ async function cut(tx, id, request) {
2812
+ const state = await tx.doc(WindowState, id);
2813
+ if (request.role) {
2814
+ state.selectedRole = request.role.id;
2815
+ await configure(tx, id, {
2816
+ model: request.role.model,
2817
+ thinkingLevel: request.role.thinkingLevel
2818
+ });
2819
+ }
2820
+ const window = { ...request.window, startedAt: now() };
2821
+ const entry = await tx.appendEntry(WindowEntry, id, {
2822
+ data: window,
2823
+ head: "self"
2824
+ });
2825
+ state.window = window;
2826
+ state.entry = entry.id;
2827
+ state.reminded = 0;
2828
+ delete state.settlement;
2829
+ }
2433
2830
  const tool = defineTool4({
2434
2831
  name: "new_context",
2435
- description: "Start fresh from saved notes; recover earlier conversation through history. Save notes first and call alone",
2436
- parameters: newContextParameters,
2437
- prepareArguments: prepareNewContextArguments,
2832
+ description: "Start fresh context window. Must save notes first and call alone",
2833
+ parameters: newContextParameters(policy.taskCompletionRollover),
2834
+ prepareArguments: (input) => prepareNewContextArguments(input, policy.taskCompletionRollover),
2438
2835
  replay: "safe",
2439
- callers: ["model"],
2836
+ callers: ["model", "tools"],
2440
2837
  executionMode: "sequential",
2441
2838
  async execute(args, api, context) {
2442
2839
  if (policy.newContextRequests === "pi-limits") {
2443
- const live = await api.snapshot(LiveDoc4, api.conversationId, context);
2444
- if (!live?.run || live.tools?.length !== 1 || live.tools[0]?.taskId !== api.taskId)
2445
- throw new Error("Call new_context alone in its native tool round");
2446
- const prior = live?.run ? await api.snapshot(ToolWindow, live.run.taskId, context) : undefined;
2840
+ const prior = await api.commit(async (tx) => {
2841
+ const { run } = await requestAdmission(tx, api.conversationId, api.taskId);
2842
+ return (await tx.doc(ToolWindow, run.taskId)).request?.tool === api.taskId;
2843
+ }, context);
2447
2844
  const hasEligibleContextHistory = policy.hasEligibleContextHistory;
2448
2845
  if (!hasEligibleContextHistory)
2449
2846
  throw new Error("pi-limits requires hasEligibleContextHistory from the host");
2450
- if (!prior?.request && !await hasEligibleContextHistory(api.conversationId, context))
2847
+ if (!prior && !await hasEligibleContextHistory(api.conversationId, context))
2451
2848
  return {
2452
2849
  output: [
2453
2850
  {
@@ -2460,26 +2857,41 @@ function createToolRollover(host, now, policy) {
2460
2857
  ]
2461
2858
  };
2462
2859
  }
2463
- const live = await api.snapshot(LiveDoc4, api.conversationId, context);
2860
+ const live = await api.snapshot(LiveDoc6, api.conversationId, context);
2464
2861
  const prior = live?.run ? await api.snapshot(ToolWindow, live.run.taskId, context) : undefined;
2465
- 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);
2862
+ 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);
2466
2863
  const result = await api.commit(async (tx) => {
2467
- const live = await tx.doc(LiveDoc4, api.conversationId);
2468
- if (!live.run || live.tools?.length !== 1 || live.tools[0]?.taskId !== api.taskId)
2469
- throw new Error("Call new_context alone in its native tool round");
2864
+ const { run, execution } = await requestAdmission(tx, api.conversationId, api.taskId);
2865
+ const deferred = policy.taskCompletionRollover ? (await tx.doc(DeferredWindow, api.conversationId)).pending : undefined;
2866
+ if (deferred && run.inputs.includes(deferred.input))
2867
+ throw new Error("A context rollover is already scheduled for this reply");
2868
+ if (args.resume === false && run.inputs.length === 0)
2869
+ throw new Error("A deferred rollover needs an active input submission");
2470
2870
  const state = await tx.doc(WindowState, api.conversationId);
2471
2871
  if (!state.window || state.transition)
2472
2872
  throw new Error("Context window is missing or a checkpoint is already in progress");
2473
2873
  if (role && !await roleSourceMatches(tx, api.conversationId, role))
2474
2874
  throw new Error("The model settings changed. Continue here and request a new role handoff if still needed.");
2475
- if (!await notesAreFresh(tx, api.conversationId))
2875
+ const checkpoint = execution && await sameCellCheckpoint(tx, api.conversationId, api.taskId, execution);
2876
+ const fresh = execution ? checkpoint !== undefined : await notesAreFresh(tx, api.conversationId) && await notesPrecedeRequest(tx, api.conversationId, api.taskId);
2877
+ if (!fresh)
2476
2878
  return {
2477
2879
  status: "checkpoint_required",
2478
2880
  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."
2479
2881
  };
2480
- const receipt = await tx.doc(ToolWindow, live.run.taskId);
2882
+ const receipt = await tx.doc(ToolWindow, run.taskId);
2883
+ if (receipt.request && receipt.request.tool !== api.taskId)
2884
+ throw new Error("A context rollover is already scheduled for this reply");
2481
2885
  receipt.request ??= {
2482
2886
  tool: api.taskId,
2887
+ ...execution && checkpoint !== undefined ? {
2888
+ nested: {
2889
+ cell: execution.cell,
2890
+ nativeTool: execution.tool,
2891
+ checkpoint
2892
+ }
2893
+ } : {},
2894
+ ...args.resume === false ? { resume: false } : {},
2483
2895
  ...role ? { role } : {},
2484
2896
  window: {
2485
2897
  id: crypto.randomUUID(),
@@ -2488,29 +2900,37 @@ function createToolRollover(host, now, policy) {
2488
2900
  previous: state.window.id
2489
2901
  }
2490
2902
  };
2491
- return { status: "scheduled", window_id: receipt.request.window.id };
2903
+ return {
2904
+ status: "scheduled",
2905
+ window_id: receipt.request.window.id,
2906
+ ...receipt.request.resume === false ? { message: "Finish your reply. No continuation will start." } : {}
2907
+ };
2492
2908
  }, context);
2493
2909
  return { output: [{ type: "text", text: JSON.stringify(result) }] };
2494
2910
  }
2495
2911
  });
2496
2912
  const hooks = [
2497
2913
  hook2(GenerationTask4, {
2498
- async afterTools(_assistant, _results, api, context) {
2914
+ async afterTools(_assistant, results, api, context) {
2499
2915
  const pending = await api.snapshot(ToolWindow, api.taskId, context);
2500
2916
  if (!pending?.request || pending.finished)
2501
2917
  return;
2502
2918
  const conv = await conversation(host(), api.conversationId, context);
2503
- const ready = async (tx) => {
2919
+ const ready = async (tx, arming = false) => {
2504
2920
  const receipt = await tx.doc(ToolWindow, api.taskId);
2505
2921
  if (!receipt.request || receipt.finished)
2506
2922
  return false;
2507
- const live = await tx.doc(LiveDoc4, api.conversationId);
2923
+ const live = await tx.doc(LiveDoc6, api.conversationId);
2508
2924
  const inbox = await tx.doc(InboxDoc2, api.conversationId);
2509
2925
  const state = await tx.doc(WindowState, api.conversationId);
2510
2926
  const slot = live.tools?.[0];
2511
2927
  const generation = await tx.task(api.taskId);
2512
- 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);
2928
+ 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));
2513
2929
  };
2930
+ if (pending.request.resume === false) {
2931
+ await armDeferredWindow(conv, api.taskId, (tx) => ready(tx, true), context);
2932
+ return;
2933
+ }
2514
2934
  const preparation = await prepareRollover(conv, api.taskId, policy.beforeRollover, {
2515
2935
  conversationId: api.conversationId,
2516
2936
  windowId: pending.request.window.previous ?? "",
@@ -2521,25 +2941,10 @@ function createToolRollover(host, now, policy) {
2521
2941
  const receipt = await tx.doc(ToolWindow, api.taskId);
2522
2942
  if (!receipt.request || receipt.finished)
2523
2943
  return;
2524
- const state = await tx.doc(WindowState, api.conversationId);
2525
2944
  const safe = !preparation.error && await ready(tx) && (preparation.head === undefined || preparation.head === await latestContextEntry(tx, api.conversationId));
2526
2945
  receipt.finished = true;
2527
- if (safe) {
2528
- if (receipt.request.role)
2529
- await configure(tx, api.conversationId, {
2530
- model: receipt.request.role.model,
2531
- thinkingLevel: receipt.request.role.thinkingLevel
2532
- });
2533
- const window = { ...receipt.request.window, startedAt: now() };
2534
- const entry = await tx.appendEntry(WindowEntry, api.conversationId, {
2535
- data: window,
2536
- head: "self"
2537
- });
2538
- state.window = window;
2539
- state.entry = entry.id;
2540
- state.reminded = 0;
2541
- delete state.settlement;
2542
- }
2946
+ if (safe)
2947
+ await cut(tx, api.conversationId, receipt.request);
2543
2948
  await tx.appendEntry(api.conversationId, {
2544
2949
  kind: "howaboua.context.continuation",
2545
2950
  model: [
@@ -2549,15 +2954,23 @@ function createToolRollover(host, now, policy) {
2549
2954
 
2550
2955
  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.",
2551
2956
  timestamp: now()
2552
- }
2957
+ },
2958
+ ...safe ? [
2959
+ {
2960
+ role: "user",
2961
+ content: "[Context management request] Resume from your saved checkpoint.",
2962
+ timestamp: now()
2963
+ }
2964
+ ] : []
2553
2965
  ]
2554
2966
  });
2555
2967
  }, context);
2556
- }
2968
+ },
2969
+ ...policy.taskCompletionRollover ? deferredRolloverHooks(host, policy.beforeRollover, cut) : {}
2557
2970
  })
2558
2971
  ];
2559
2972
  return {
2560
- tool: { ...tool, executionHints: { nativeOnly: true } },
2973
+ tool: { ...tool, executionHints: { nestedHidden: true } },
2561
2974
  hooks
2562
2975
  };
2563
2976
  }
@@ -2586,6 +2999,11 @@ function createContextManagement(options) {
2586
2999
  throw new Error("taskBoundaryReminderTokens must be a non-negative safe integer");
2587
3000
  const now = options.now ?? Date.now;
2588
3001
  const newContextRequests = options.newContextRequests ?? "unrestricted";
3002
+ const tailMode = options.rolloverTail ?? "off";
3003
+ if (tailMode !== "off" && tailMode !== "conversation" && tailMode !== "full")
3004
+ throw new Error("rolloverTail must be off, conversation or full");
3005
+ if (options.taskCompletionRollover !== undefined && typeof options.taskCompletionRollover !== "boolean")
3006
+ throw new Error("taskCompletionRollover must be a boolean");
2589
3007
  if (newContextRequests !== "off" && newContextRequests !== "pi-limits" && newContextRequests !== "unrestricted")
2590
3008
  throw new Error("newContextRequests must be off, pi-limits or unrestricted");
2591
3009
  if (newContextRequests === "pi-limits" && options.hasEligibleContextHistory === undefined)
@@ -2594,7 +3012,8 @@ function createContextManagement(options) {
2594
3012
  const conv = await conversation(host(), id, context);
2595
3013
  await conv.commit((tx) => initializeWindow(tx, id, now()), context);
2596
3014
  };
2597
- const rollover = createRollover(host, options.beforeRollover);
3015
+ const taskCompletionRollover = newContextRequests !== "off" && options.taskCompletionRollover === true;
3016
+ const rollover = createRollover(host, options.beforeRollover, tailMode);
2598
3017
  const input = createInput(host, rollover, idleMinutes * 60 * 1000);
2599
3018
  const policy = createContextPolicy({
2600
3019
  models: options.models,
@@ -2603,6 +3022,7 @@ function createContextManagement(options) {
2603
3022
  ensureWindow,
2604
3023
  taskBoundaryReminderTokens,
2605
3024
  newContextRequests,
3025
+ taskCompletionRollover,
2606
3026
  modelRoles: options.modelRoles,
2607
3027
  archiveHistory: options.archiveHistory === true,
2608
3028
  rankedHistory: options.rankedHistory
@@ -2621,6 +3041,7 @@ function createContextManagement(options) {
2621
3041
  });
2622
3042
  const newContext = createToolRollover(host, now, {
2623
3043
  newContextRequests,
3044
+ taskCompletionRollover,
2624
3045
  modelRoles: options.modelRoles,
2625
3046
  beforeRollover: options.beforeRollover,
2626
3047
  ...options.hasEligibleContextHistory === undefined ? {} : { hasEligibleContextHistory: options.hasEligibleContextHistory }
@@ -2628,7 +3049,7 @@ function createContextManagement(options) {
2628
3049
  const extension = defineExtension({
2629
3050
  name: "howaboua.context",
2630
3051
  tools: [
2631
- notes,
3052
+ ...options.localNotes === false ? [] : [notes],
2632
3053
  history,
2633
3054
  policy.remainingTool,
2634
3055
  ...newContextRequests === "off" ? [] : [newContext.tool]