@howaboua/pi-durable-context 0.11.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 {
@@ -176,11 +180,67 @@ async function cancelPlacedInput(host, conv, id, context) {
176
180
  // packages/context/src/note-store.ts
177
181
  import {
178
182
  createSession,
179
- defineDoc as defineDoc3,
183
+ defineDoc as defineDoc4,
180
184
  defineDocFamily as defineDocFamily2,
181
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,
182
192
  ToolTask
183
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
+ }
184
244
 
185
245
  // packages/context/src/query-input.ts
186
246
  var actions = {
@@ -243,6 +303,8 @@ function normalizeQueryInput(namespace, input) {
243
303
  params["action"] = action;
244
304
  if (namespace === "notes") {
245
305
  alias(params, "address", "path");
306
+ if (action === "read")
307
+ alias(params, "end_line", "stop_line");
246
308
  if (action === "write" || action === "append") {
247
309
  alias(params, "content", "text");
248
310
  alias(params, "body", "text");
@@ -277,7 +339,7 @@ function isNoteWrite(input) {
277
339
  }
278
340
 
279
341
  // packages/context/src/note-store.ts
280
- var NotesState = defineDoc3({
342
+ var NotesState = defineDoc4({
281
343
  kind: "howaboua.context.notes-state",
282
344
  version: 1,
283
345
  scope: "conversation",
@@ -296,7 +358,7 @@ var NoteFile = defineDocFamily2({
296
358
  fork: "asOf",
297
359
  initial: () => ({ text: "" })
298
360
  });
299
- var WriteReceipt = defineDoc3({
361
+ var WriteReceipt = defineDoc4({
300
362
  kind: "howaboua.context.note-write-receipt",
301
363
  version: 1,
302
364
  scope: "task",
@@ -339,14 +401,30 @@ async function requireNotesWindow(tx, id) {
339
401
  async function readNoteText(tx, id, path) {
340
402
  return (await tx.doc(NoteFile, id, path, null)).text;
341
403
  }
342
- async function notesAreFresh(tx, id) {
404
+ async function freshNote(tx, id) {
343
405
  const userEntry = await latestUserEntry(tx, id);
344
406
  const window = await tx.doc(WindowState, id);
345
407
  const state = await tx.doc(NotesState, id);
346
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;
347
- 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")
348
414
  return false;
349
- 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;
350
428
  while (owner !== undefined) {
351
429
  const task = await tx.task(owner);
352
430
  if (!task)
@@ -359,7 +437,7 @@ async function notesAreFresh(tx, id) {
359
437
  if (result && typeof result === "object" && !Array.isArray(result)) {
360
438
  if (result["isError"] === true)
361
439
  return false;
362
- if (task.kind === ToolTask.definition.name && "entryId" in result) {
440
+ if (task.kind === ToolTask2.definition.name && "entryId" in result) {
363
441
  const entryId = result["entryId"];
364
442
  if (typeof entryId === "number") {
365
443
  const entry = await tx.entry(entryId);
@@ -374,11 +452,11 @@ async function notesAreFresh(tx, id) {
374
452
  do {
375
453
  const page = await tx.scanTasks({
376
454
  conversationId: id,
377
- kind: ToolTask.definition.name,
455
+ kind: ToolTask2.definition.name,
378
456
  order: "descending"
379
457
  }, 64, cursor);
380
458
  for (const task of page.items) {
381
- if (task.id <= state.lastWrite.taskId)
459
+ if (task.id <= lastWrite.taskId)
382
460
  return true;
383
461
  const input = task.input;
384
462
  let call = input.kind === "nested" ? input.call : undefined;
@@ -393,27 +471,36 @@ async function notesAreFresh(tx, id) {
393
471
  } while (cursor !== undefined);
394
472
  return true;
395
473
  }
396
- async function notesPrecedeRequest(tx, id, request) {
474
+ async function isCurrentCheckpoint(tx, id, checkpoint) {
475
+ return (await freshNote(tx, id))?.taskId === checkpoint;
476
+ }
477
+ async function latestNoteRound(tx, id) {
397
478
  const saved = (await tx.doc(NotesState, id)).lastWrite;
398
- const requesting = await tx.task(request);
399
- if (!saved || requesting?.kind !== ToolTask.definition.name)
400
- return false;
401
- const input = requesting.input;
402
- if (input.kind === "nested")
403
- return false;
479
+ if (!saved)
480
+ return;
404
481
  let owner = saved.taskId;
405
482
  let savedAssistant = saved.assistantEntry;
406
483
  while (owner !== undefined) {
407
484
  const task = await tx.task(owner);
408
485
  if (!task || task.kind === GenerationTask.definition.name)
409
486
  break;
410
- if (task.kind === ToolTask.definition.name) {
487
+ if (task.kind === ToolTask2.definition.name) {
411
488
  const call = task.input;
412
489
  if (call.kind !== "nested")
413
490
  savedAssistant = call.assistant;
414
491
  }
415
492
  owner = task.owner;
416
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);
417
504
  if (savedAssistant === undefined)
418
505
  return false;
419
506
  const completed = new Map;
@@ -437,19 +524,6 @@ async function notesPrecedeRequest(tx, id, request) {
437
524
  } while (cursor !== undefined);
438
525
  return false;
439
526
  }
440
- async function currentToolRound(tx, id) {
441
- let cursor;
442
- do {
443
- const page = await tx.scanEntries({ conversationId: id }, 64, cursor);
444
- for (const entry of page.items) {
445
- const assistant = entry.model?.findLast((message) => message.role === "assistant");
446
- if (assistant?.role === "assistant")
447
- return assistant.content.some((block) => block.type === "toolCall") ? entry.id : undefined;
448
- }
449
- cursor = page.next;
450
- } while (cursor !== undefined);
451
- return;
452
- }
453
527
  async function beginNoteWrite(tx, id, taskId) {
454
528
  const receipt = await tx.doc(WriteReceipt, taskId);
455
529
  if (receipt.attempted || receipt.file)
@@ -486,11 +560,13 @@ async function mutateNote(tx, input) {
486
560
  nextCatalog.push(metadata);
487
561
  else
488
562
  nextCatalog[index] = metadata;
489
- const assistantEntry = await currentToolRound(tx, input.conversationId);
563
+ const assistantEntry = await admittedToolRound(tx, input.conversationId, input.taskId);
564
+ const execution = await admittedExecutionCall(tx, input.conversationId, input.taskId);
490
565
  const freshness = {
491
566
  windowId,
492
567
  userEntry,
493
568
  ...assistantEntry === undefined ? {} : { assistantEntry },
569
+ ...execution === undefined ? {} : { execution },
494
570
  taskId: input.taskId,
495
571
  updatedAt
496
572
  };
@@ -612,9 +688,9 @@ async function instructionAnswer(tx, id) {
612
688
 
613
689
  // packages/context/src/rollover-preparation.ts
614
690
  import {
615
- defineDoc as defineDoc4
691
+ defineDoc as defineDoc5
616
692
  } from "@earendil-works/pi-durable";
617
- var RolloverPreparation = defineDoc4({
693
+ var RolloverPreparation = defineDoc5({
618
694
  kind: "howaboua.context.rollover-preparation",
619
695
  version: 1,
620
696
  scope: "task",
@@ -679,6 +755,95 @@ async function prepareRollover(conversation, taskId, callback, request, ready, c
679
755
  return { head };
680
756
  }
681
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
+
682
847
  // packages/context/src/rollover.ts
683
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.";
684
849
  var key = (task) => `context:checkpoint:${task}`;
@@ -705,7 +870,7 @@ async function completedFreshNotes(host, id, context) {
705
870
  } while (cursor !== undefined);
706
871
  return done;
707
872
  }
708
- function createRollover(host, beforeRollover) {
873
+ function createRollover(host, beforeRollover, tailMode = "off") {
709
874
  return defineTask({
710
875
  name: ROLLOVER_TASK,
711
876
  version: 1,
@@ -720,7 +885,7 @@ function createRollover(host, beforeRollover) {
720
885
  await Promise.all(tasks.map((id) => runtime.waitForTask(id, context)));
721
886
  }
722
887
  const fresh = await completedFreshNotes(host(), conv.id, context);
723
- if (fresh) {
888
+ if (fresh && (tailMode === "off" || task.input.reason === "idle" || await projectRolloverTail(conv, tailMode, context))) {
724
889
  await runtime.commit(() => ({ status: "running", checkpoint: { phase: "rotate" } }), context);
725
890
  return;
726
891
  }
@@ -821,14 +986,18 @@ function createRollover(host, beforeRollover) {
821
986
  return completed && await nativeIdle(tx, task.conversationId) && (await foreignTasks(tx, task.conversationId)).length === 0 && await notesAreFresh(tx, task.conversationId);
822
987
  };
823
988
  const current = await runtime.snapshot(WindowState, task.conversationId, context);
824
- 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, {
825
994
  conversationId: task.conversationId,
826
995
  windowId: current?.window?.id ?? "",
827
996
  nextWindowId: task.input.windowId,
828
997
  reason: task.input.reason
829
- }, ready, context);
998
+ }, async (tx) => await ready(tx) && (!tail || await rolloverTailMatches(tx, conv, tail)), context);
830
999
  await runtime.commit(async (tx) => {
831
- 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));
832
1001
  const state = await tx.doc(WindowState, task.conversationId);
833
1002
  if (!safe || !state.window) {
834
1003
  delete state.transition;
@@ -851,7 +1020,7 @@ function createRollover(host, beforeRollover) {
851
1020
  };
852
1021
  const entry = await tx.appendEntry(WindowEntry, task.conversationId, {
853
1022
  data: window,
854
- head: "self"
1023
+ ...tail ? { head: tail.head, edits: tail.edits } : { head: "self" }
855
1024
  });
856
1025
  state.window = window;
857
1026
  state.entry = entry.id;
@@ -1092,7 +1261,8 @@ function createInput(host, rollover, idleMs) {
1092
1261
  const userEntry = await latestUserEntry(tx, task.conversationId);
1093
1262
  const idle = await nativeIdle(tx, task.conversationId);
1094
1263
  const state = await tx.doc(WindowState, task.conversationId);
1095
- 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)
1096
1266
  state.settlement = {
1097
1267
  observedAt: runtime.now(),
1098
1268
  userEntry,
@@ -1161,9 +1331,9 @@ import {
1161
1331
  import { Type as Type2 } from "typebox";
1162
1332
 
1163
1333
  // internal/context-visibility.ts
1164
- 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";
1165
1335
  var SHARED_GROUP = "shared";
1166
- var ContextVisibility = defineDoc5({
1336
+ var ContextVisibility = defineDoc6({
1167
1337
  kind: "howaboua.context.visibility",
1168
1338
  version: 1,
1169
1339
  scope: "conversation",
@@ -1401,16 +1571,23 @@ var notesParameters = Type.Object({
1401
1571
  offset_chars: Type.Optional(Type.Integer({ minimum: 0 })),
1402
1572
  text: Type.Optional(Type.String())
1403
1573
  }, { additionalProperties: false });
1404
- var newContextParameters = Type.Object({
1405
- role: Type.Optional(Type.String({
1406
- minLength: 1,
1407
- description: "Configured model-role ID, not an agent name or handoff text"
1408
- }))
1409
- }, { additionalProperties: false });
1410
- 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) {
1411
1588
  const args = input ?? {};
1412
- if (!Check(newContextParameters, args))
1413
- throw new Error('Use {} to keep the current role, or {role: "name"} for a configured model-role ID.');
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.');
1414
1591
  return args;
1415
1592
  }
1416
1593
  function prepareNotesArguments(input) {
@@ -1469,7 +1646,9 @@ function contextToolHelp(namespace, args, rankedHistory = false) {
1469
1646
  throw new Error("Help accepts only action: help");
1470
1647
  const fields = namespace === "notes" ? notesFields : historyFields;
1471
1648
  return {
1472
- ...namespace === "notes" ? { results: "read: file.content; write/append: file.path" } : {},
1649
+ ...namespace === "notes" ? {
1650
+ results: "list: files; search: files[].matches; read: file.content or file=null; write/append: file.path"
1651
+ } : {},
1473
1652
  actions: Object.fromEntries(Object.entries(fields).map(([action, names]) => [
1474
1653
  action,
1475
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(" ")
@@ -2218,15 +2397,21 @@ function lineIndex(value, count, fallback) {
2218
2397
  // packages/context/src/policy.ts
2219
2398
  import {
2220
2399
  CompactionTask,
2221
- defineDoc as defineDoc6,
2400
+ defineDoc as defineDoc8,
2222
2401
  defineTool as defineTool3,
2223
2402
  GenerationTask as GenerationTask3,
2224
2403
  hook,
2225
2404
  section,
2226
- ToolTask as ToolTask2
2405
+ ToolTask as ToolTask3
2227
2406
  } from "@earendil-works/pi-durable";
2228
2407
  import { Type as Type4 } from "typebox";
2229
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
+
2230
2415
  // packages/context/src/model-roles.ts
2231
2416
  import {
2232
2417
  AgentDoc
@@ -2249,7 +2434,7 @@ async function readRoles(catalog, id, context) {
2249
2434
  reasoning
2250
2435
  }));
2251
2436
  }
2252
- async function renderModelRoles(catalog, id, agent, context) {
2437
+ async function renderModelRoles(catalog, id, selected, context) {
2253
2438
  let roles;
2254
2439
  try {
2255
2440
  roles = await readRoles(catalog, id, context);
@@ -2259,11 +2444,9 @@ async function renderModelRoles(catalog, id, agent, context) {
2259
2444
  }
2260
2445
  if (!roles.length)
2261
2446
  return "No model roles are available. Call new_context without role.";
2262
- const matching = roles.filter((role) => role.provider === agent?.model?.provider && role.model === agent?.model?.modelId && role.reasoning === (agent?.thinkingLevel ?? "off")).map((role) => role.id);
2263
- const currentRole = matching.length === 0 ? "none (no matching preset)" : matching.length === 1 ? matching.join(", ") : `ambiguous (${matching.join(", ")})`;
2264
2447
  return [
2265
- `Current role: ${currentRole}`,
2266
- 'Roles are user preferences, not capability limits. Switch for a clear, sustained change of task or scope, not a single specialised prompt. Any role 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 role.',
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.',
2267
2450
  ...roles.map((role) => `- ${role.id}: ${role.description}`)
2268
2451
  ].join(`
2269
2452
  `);
@@ -2295,6 +2478,98 @@ async function roleSourceMatches(tx, id, role) {
2295
2478
  return current.model?.provider === role.source.model?.provider && current.model?.modelId === role.source.model?.modelId && (current.thinkingLevel ?? "off") === role.source.thinkingLevel;
2296
2479
  }
2297
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
+
2298
2573
  // packages/context/src/usage.ts
2299
2574
  import { estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
2300
2575
  async function contextUsage(conversation, models, context, answer) {
@@ -2363,7 +2638,7 @@ function checkpointGuidance(newContextRequests) {
2363
2638
 
2364
2639
  `);
2365
2640
  }
2366
- var YieldAdvisory = defineDoc6({
2641
+ var YieldAdvisory = defineDoc8({
2367
2642
  kind: "howaboua.context.yield-advisory",
2368
2643
  version: 1,
2369
2644
  scope: "task",
@@ -2380,7 +2655,7 @@ function createContextPolicy(options) {
2380
2655
  const sections = [
2381
2656
  section("context", () => checkpointGuidance(options.newContextRequests)),
2382
2657
  ...options.newContextRequests === "off" || !options.modelRoles ? [] : [
2383
- section("context-roles", async (input, context) => renderModelRoles(options.modelRoles, input.conversationId, input.agent, context))
2658
+ section("context-roles", async (input, context) => renderModelRoles(options.modelRoles, input.conversationId, (await input.read.snapshot(WindowState, input.conversationId, context))?.selectedRole, context))
2384
2659
  ],
2385
2660
  section("context-state", async (input, context) => {
2386
2661
  const [state, hints] = await Promise.all([
@@ -2474,16 +2749,20 @@ function createContextPolicy(options) {
2474
2749
  await refreshRankedHistory(await conversation(api.conversationId, context), options.rankedHistory, context);
2475
2750
  },
2476
2751
  async afterTools(_assistant, _results, api, context) {
2752
+ if (options.taskCompletionRollover && await finishesInFreshWindow(api, context))
2753
+ return;
2477
2754
  await remind(api, context);
2478
2755
  },
2479
2756
  async onYield(answer, api, context) {
2480
2757
  if (options.rankedHistory)
2481
2758
  await refreshRankedHistory(await conversation(api.conversationId, context), options.rankedHistory, context);
2759
+ if (options.taskCompletionRollover && await finishesInFreshWindow(api, context))
2760
+ return;
2482
2761
  const text = await remind(api, context, answer);
2483
- return text ? { continue: text } : undefined;
2762
+ return text ? { kind: "continue", continue: text } : undefined;
2484
2763
  }
2485
2764
  }),
2486
- hook(ToolTask2, {
2765
+ hook(ToolTask3, {
2487
2766
  async beforeTool(_call, api, context) {
2488
2767
  await options.ensureWindow(api.conversationId, context);
2489
2768
  },
@@ -2494,7 +2773,7 @@ function createContextPolicy(options) {
2494
2773
  }),
2495
2774
  hook(CompactionTask, {
2496
2775
  async beforeCompact(compaction) {
2497
- return compaction.reason === "overflow" ? undefined : { decline: true };
2776
+ return compaction.reason === "overflow" ? undefined : { kind: "decline" };
2498
2777
  }
2499
2778
  })
2500
2779
  ];
@@ -2504,39 +2783,68 @@ function createContextPolicy(options) {
2504
2783
  // packages/context/src/tool-rollover.ts
2505
2784
  import {
2506
2785
  configure,
2507
- defineDoc as defineDoc7,
2508
2786
  defineTool as defineTool4,
2509
2787
  GenerationTask as GenerationTask4,
2510
2788
  hook as hook2,
2511
2789
  InboxDoc as InboxDoc2,
2512
- LiveDoc as LiveDoc4
2790
+ LiveDoc as LiveDoc6
2513
2791
  } from "@earendil-works/pi-durable";
2514
- var ToolWindow = defineDoc7({
2515
- kind: "howaboua.context.tool-window",
2516
- version: 1,
2517
- scope: "task",
2518
- checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
2519
- initial: () => ({})
2520
- });
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
+ }
2521
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
+ }
2522
2830
  const tool = defineTool4({
2523
2831
  name: "new_context",
2524
2832
  description: "Start fresh context window. Must save notes first and call alone",
2525
- parameters: newContextParameters,
2526
- prepareArguments: prepareNewContextArguments,
2833
+ parameters: newContextParameters(policy.taskCompletionRollover),
2834
+ prepareArguments: (input) => prepareNewContextArguments(input, policy.taskCompletionRollover),
2527
2835
  replay: "safe",
2528
- callers: ["model"],
2836
+ callers: ["model", "tools"],
2529
2837
  executionMode: "sequential",
2530
2838
  async execute(args, api, context) {
2531
2839
  if (policy.newContextRequests === "pi-limits") {
2532
- const live = await api.snapshot(LiveDoc4, api.conversationId, context);
2533
- if (!live?.run || live.tools?.length !== 1 || live.tools[0]?.taskId !== api.taskId)
2534
- throw new Error("Call new_context alone in its native tool round");
2535
- 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);
2536
2844
  const hasEligibleContextHistory = policy.hasEligibleContextHistory;
2537
2845
  if (!hasEligibleContextHistory)
2538
2846
  throw new Error("pi-limits requires hasEligibleContextHistory from the host");
2539
- if (!prior?.request && !await hasEligibleContextHistory(api.conversationId, context))
2847
+ if (!prior && !await hasEligibleContextHistory(api.conversationId, context))
2540
2848
  return {
2541
2849
  output: [
2542
2850
  {
@@ -2549,26 +2857,41 @@ function createToolRollover(host, now, policy) {
2549
2857
  ]
2550
2858
  };
2551
2859
  }
2552
- const live = await api.snapshot(LiveDoc4, api.conversationId, context);
2860
+ const live = await api.snapshot(LiveDoc6, api.conversationId, context);
2553
2861
  const prior = live?.run ? await api.snapshot(ToolWindow, live.run.taskId, context) : undefined;
2554
- 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);
2555
2863
  const result = await api.commit(async (tx) => {
2556
- const live = await tx.doc(LiveDoc4, api.conversationId);
2557
- if (!live.run || live.tools?.length !== 1 || live.tools[0]?.taskId !== api.taskId)
2558
- 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");
2559
2870
  const state = await tx.doc(WindowState, api.conversationId);
2560
2871
  if (!state.window || state.transition)
2561
2872
  throw new Error("Context window is missing or a checkpoint is already in progress");
2562
2873
  if (role && !await roleSourceMatches(tx, api.conversationId, role))
2563
2874
  throw new Error("The model settings changed. Continue here and request a new role handoff if still needed.");
2564
- if (!await notesAreFresh(tx, api.conversationId) || !await notesPrecedeRequest(tx, api.conversationId, api.taskId))
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)
2565
2878
  return {
2566
2879
  status: "checkpoint_required",
2567
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."
2568
2881
  };
2569
- 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");
2570
2885
  receipt.request ??= {
2571
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 } : {},
2572
2895
  ...role ? { role } : {},
2573
2896
  window: {
2574
2897
  id: crypto.randomUUID(),
@@ -2577,29 +2900,37 @@ function createToolRollover(host, now, policy) {
2577
2900
  previous: state.window.id
2578
2901
  }
2579
2902
  };
2580
- 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
+ };
2581
2908
  }, context);
2582
2909
  return { output: [{ type: "text", text: JSON.stringify(result) }] };
2583
2910
  }
2584
2911
  });
2585
2912
  const hooks = [
2586
2913
  hook2(GenerationTask4, {
2587
- async afterTools(_assistant, _results, api, context) {
2914
+ async afterTools(_assistant, results, api, context) {
2588
2915
  const pending = await api.snapshot(ToolWindow, api.taskId, context);
2589
2916
  if (!pending?.request || pending.finished)
2590
2917
  return;
2591
2918
  const conv = await conversation(host(), api.conversationId, context);
2592
- const ready = async (tx) => {
2919
+ const ready = async (tx, arming = false) => {
2593
2920
  const receipt = await tx.doc(ToolWindow, api.taskId);
2594
2921
  if (!receipt.request || receipt.finished)
2595
2922
  return false;
2596
- const live = await tx.doc(LiveDoc4, api.conversationId);
2923
+ const live = await tx.doc(LiveDoc6, api.conversationId);
2597
2924
  const inbox = await tx.doc(InboxDoc2, api.conversationId);
2598
2925
  const state = await tx.doc(WindowState, api.conversationId);
2599
2926
  const slot = live.tools?.[0];
2600
2927
  const generation = await tx.task(api.taskId);
2601
- 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) && await notesPrecedeRequest(tx, api.conversationId, receipt.request.tool) && (!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));
2602
2929
  };
2930
+ if (pending.request.resume === false) {
2931
+ await armDeferredWindow(conv, api.taskId, (tx) => ready(tx, true), context);
2932
+ return;
2933
+ }
2603
2934
  const preparation = await prepareRollover(conv, api.taskId, policy.beforeRollover, {
2604
2935
  conversationId: api.conversationId,
2605
2936
  windowId: pending.request.window.previous ?? "",
@@ -2610,25 +2941,10 @@ function createToolRollover(host, now, policy) {
2610
2941
  const receipt = await tx.doc(ToolWindow, api.taskId);
2611
2942
  if (!receipt.request || receipt.finished)
2612
2943
  return;
2613
- const state = await tx.doc(WindowState, api.conversationId);
2614
2944
  const safe = !preparation.error && await ready(tx) && (preparation.head === undefined || preparation.head === await latestContextEntry(tx, api.conversationId));
2615
2945
  receipt.finished = true;
2616
- if (safe) {
2617
- if (receipt.request.role)
2618
- await configure(tx, api.conversationId, {
2619
- model: receipt.request.role.model,
2620
- thinkingLevel: receipt.request.role.thinkingLevel
2621
- });
2622
- const window = { ...receipt.request.window, startedAt: now() };
2623
- const entry = await tx.appendEntry(WindowEntry, api.conversationId, {
2624
- data: window,
2625
- head: "self"
2626
- });
2627
- state.window = window;
2628
- state.entry = entry.id;
2629
- state.reminded = 0;
2630
- delete state.settlement;
2631
- }
2946
+ if (safe)
2947
+ await cut(tx, api.conversationId, receipt.request);
2632
2948
  await tx.appendEntry(api.conversationId, {
2633
2949
  kind: "howaboua.context.continuation",
2634
2950
  model: [
@@ -2649,11 +2965,12 @@ Role: ${receipt.request.role.id}` : ""}` : preparation.error ?? "Context rollove
2649
2965
  ]
2650
2966
  });
2651
2967
  }, context);
2652
- }
2968
+ },
2969
+ ...policy.taskCompletionRollover ? deferredRolloverHooks(host, policy.beforeRollover, cut) : {}
2653
2970
  })
2654
2971
  ];
2655
2972
  return {
2656
- tool: { ...tool, executionHints: { nativeOnly: true } },
2973
+ tool: { ...tool, executionHints: { nestedHidden: true } },
2657
2974
  hooks
2658
2975
  };
2659
2976
  }
@@ -2682,6 +2999,11 @@ function createContextManagement(options) {
2682
2999
  throw new Error("taskBoundaryReminderTokens must be a non-negative safe integer");
2683
3000
  const now = options.now ?? Date.now;
2684
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");
2685
3007
  if (newContextRequests !== "off" && newContextRequests !== "pi-limits" && newContextRequests !== "unrestricted")
2686
3008
  throw new Error("newContextRequests must be off, pi-limits or unrestricted");
2687
3009
  if (newContextRequests === "pi-limits" && options.hasEligibleContextHistory === undefined)
@@ -2690,7 +3012,8 @@ function createContextManagement(options) {
2690
3012
  const conv = await conversation(host(), id, context);
2691
3013
  await conv.commit((tx) => initializeWindow(tx, id, now()), context);
2692
3014
  };
2693
- const rollover = createRollover(host, options.beforeRollover);
3015
+ const taskCompletionRollover = newContextRequests !== "off" && options.taskCompletionRollover === true;
3016
+ const rollover = createRollover(host, options.beforeRollover, tailMode);
2694
3017
  const input = createInput(host, rollover, idleMinutes * 60 * 1000);
2695
3018
  const policy = createContextPolicy({
2696
3019
  models: options.models,
@@ -2699,6 +3022,7 @@ function createContextManagement(options) {
2699
3022
  ensureWindow,
2700
3023
  taskBoundaryReminderTokens,
2701
3024
  newContextRequests,
3025
+ taskCompletionRollover,
2702
3026
  modelRoles: options.modelRoles,
2703
3027
  archiveHistory: options.archiveHistory === true,
2704
3028
  rankedHistory: options.rankedHistory
@@ -2717,6 +3041,7 @@ function createContextManagement(options) {
2717
3041
  });
2718
3042
  const newContext = createToolRollover(host, now, {
2719
3043
  newContextRequests,
3044
+ taskCompletionRollover,
2720
3045
  modelRoles: options.modelRoles,
2721
3046
  beforeRollover: options.beforeRollover,
2722
3047
  ...options.hasEligibleContextHistory === undefined ? {} : { hasEligibleContextHistory: options.hasEligibleContextHistory }
@@ -2724,7 +3049,7 @@ function createContextManagement(options) {
2724
3049
  const extension = defineExtension({
2725
3050
  name: "howaboua.context",
2726
3051
  tools: [
2727
- notes,
3052
+ ...options.localNotes === false ? [] : [notes],
2728
3053
  history,
2729
3054
  policy.remainingTool,
2730
3055
  ...newContextRequests === "off" ? [] : [newContext.tool]