@howaboua/pi-durable-context 0.0.0-stage → 0.10.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.
Files changed (36) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +63 -0
  3. package/README.md +168 -2
  4. package/dist/activation.js +2953 -0
  5. package/dist/history-search-worker.js +85 -0
  6. package/dist/index.js +2703 -0
  7. package/dist/internal/context-visibility.d.ts +6 -0
  8. package/dist/node.js +124 -0
  9. package/dist/packages/context/src/activation.d.ts +20 -0
  10. package/dist/packages/context/src/admission.d.ts +23 -0
  11. package/dist/packages/context/src/history-archive.d.ts +24 -0
  12. package/dist/packages/context/src/history-items.d.ts +17 -0
  13. package/dist/packages/context/src/history-ranker.d.ts +27 -0
  14. package/dist/packages/context/src/history-search-worker.d.ts +15 -0
  15. package/dist/packages/context/src/history.d.ts +80 -0
  16. package/dist/packages/context/src/index.d.ts +76 -0
  17. package/dist/packages/context/src/input-placement.d.ts +6 -0
  18. package/dist/packages/context/src/instruction-run.d.ts +13 -0
  19. package/dist/packages/context/src/lifecycle.d.ts +40 -0
  20. package/dist/packages/context/src/model-roles.d.ts +26 -0
  21. package/dist/packages/context/src/node.d.ts +10 -0
  22. package/dist/packages/context/src/note-path.d.ts +2 -0
  23. package/dist/packages/context/src/note-store.d.ts +53 -0
  24. package/dist/packages/context/src/notes.d.ts +76 -0
  25. package/dist/packages/context/src/policy.d.ts +24 -0
  26. package/dist/packages/context/src/presentation.d.ts +52 -0
  27. package/dist/packages/context/src/query-input.d.ts +3 -0
  28. package/dist/packages/context/src/remote.d.ts +34 -0
  29. package/dist/packages/context/src/rollover-preparation.d.ts +16 -0
  30. package/dist/packages/context/src/rollover.d.ts +32 -0
  31. package/dist/packages/context/src/tool-contract.d.ts +85 -0
  32. package/dist/packages/context/src/tool-rollover.d.ts +41 -0
  33. package/dist/packages/context/src/usage.d.ts +24 -0
  34. package/dist/packages/context/src/window-state.d.ts +37 -0
  35. package/dist/presentation.js +93 -0
  36. package/package.json +70 -5
package/dist/index.js ADDED
@@ -0,0 +1,2703 @@
1
+ // packages/context/src/index.ts
2
+ import { defineExtension } from "@earendil-works/pi-durable";
3
+
4
+ // packages/context/src/admission.ts
5
+ import { ConversationBusy, defineTask as defineTask2 } from "@earendil-works/pi-durable";
6
+
7
+ // packages/context/src/lifecycle.ts
8
+ import {
9
+ defineDoc as defineDoc2,
10
+ defineDocFamily,
11
+ InboxDoc,
12
+ LiveDoc
13
+ } from "@earendil-works/pi-durable";
14
+
15
+ // packages/context/src/window-state.ts
16
+ import { defineDoc, defineEntry } from "@earendil-works/pi-durable";
17
+ var WindowEntry = defineEntry("howaboua.context.window");
18
+ var WindowState = defineDoc({
19
+ kind: "howaboua.context.window-state",
20
+ version: 1,
21
+ scope: "conversation",
22
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
23
+ history: "rewindable",
24
+ fork: "initial",
25
+ initial: () => ({ reminded: 0 })
26
+ });
27
+ async function latestUserEntry(tx, conversationId) {
28
+ let cursor;
29
+ do {
30
+ const page = await tx.scanEntries({ conversationId }, 64, cursor);
31
+ const entry = page.items.find((item) => item.kind === "pi.user");
32
+ if (entry)
33
+ return entry.id;
34
+ cursor = page.next;
35
+ } while (cursor !== undefined);
36
+ return null;
37
+ }
38
+
39
+ // packages/context/src/lifecycle.ts
40
+ var INPUT_TASK = "howaboua.context.input";
41
+ var ROLLOVER_TASK = "howaboua.context.rollover";
42
+ var Admission = defineDoc2({
43
+ kind: "howaboua.context.admission",
44
+ version: 1,
45
+ scope: "conversation",
46
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
47
+ history: "latest",
48
+ fork: "initial",
49
+ initial: () => ({ queue: [], cancelled: [], retry: 0 })
50
+ });
51
+ var InputReceipt = defineDocFamily({
52
+ kind: "howaboua.context.input-receipt",
53
+ version: 1,
54
+ scope: "conversation",
55
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
56
+ family: true,
57
+ history: "latest",
58
+ fork: "initial",
59
+ initial: () => ({})
60
+ });
61
+ var Continuation = defineDocFamily({
62
+ kind: "howaboua.context.continuation",
63
+ version: 1,
64
+ scope: "conversation",
65
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
66
+ family: true,
67
+ history: "latest",
68
+ fork: "initial",
69
+ initial: () => ({})
70
+ });
71
+ async function cancelHeldInputs(tx, id) {
72
+ const gate = await tx.doc(Admission, id);
73
+ gate.cancelled = [...new Set([...gate.cancelled, ...gate.queue])];
74
+ }
75
+ async function releaseAdmission(tx, id, task) {
76
+ const gate = await tx.doc(Admission, id);
77
+ gate.queue = gate.queue.filter((item) => item !== task);
78
+ gate.cancelled = gate.cancelled.filter((item) => item !== task);
79
+ if (gate.blocked?.task === task)
80
+ delete gate.blocked;
81
+ }
82
+ async function conversation(host, id, context) {
83
+ const value = await host.harness.conversation(id, context);
84
+ if (!value)
85
+ throw new Error(`Missing conversation ${id}`);
86
+ return value;
87
+ }
88
+ async function initializeWindow(tx, id, now) {
89
+ const state = await tx.doc(WindowState, id);
90
+ if (state.window)
91
+ return;
92
+ let previous;
93
+ let cursor;
94
+ do {
95
+ const page = await tx.scanEntries({ conversationId: id }, 64, cursor);
96
+ const marker = page.items.find(WindowEntry.is);
97
+ if (marker && WindowEntry.is(marker))
98
+ previous = marker.data;
99
+ cursor = page.next;
100
+ } while (!previous && cursor !== undefined);
101
+ const window = {
102
+ id: crypto.randomUUID(),
103
+ number: (previous?.number ?? 0) + 1,
104
+ startedAt: now,
105
+ ...previous ? { previous: previous.id } : {}
106
+ };
107
+ const entry = await tx.appendEntry(WindowEntry, id, { data: window });
108
+ state.window = window;
109
+ state.entry = entry.id;
110
+ }
111
+ async function foreignTasks(tx, id) {
112
+ const tasks = [];
113
+ let cursor;
114
+ do {
115
+ const page = await tx.scanTasks({ conversationId: id, background: false }, 64, cursor);
116
+ for (const task of page.items) {
117
+ if (task.state.status !== "terminal" && task.kind !== INPUT_TASK && task.kind !== ROLLOVER_TASK)
118
+ tasks.push(task.id);
119
+ }
120
+ cursor = page.next;
121
+ } while (cursor !== undefined);
122
+ return tasks;
123
+ }
124
+ async function nativeIdle(tx, id) {
125
+ const live = await tx.doc(LiveDoc, id);
126
+ const inbox = await tx.doc(InboxDoc, id);
127
+ return !live.run && inbox.items.length === 0;
128
+ }
129
+ async function until(watch, predicate, signal) {
130
+ if (!watch)
131
+ throw new Error("Context admission state is missing");
132
+ let abort = () => {};
133
+ try {
134
+ await new Promise((resolve, reject) => {
135
+ abort = () => reject(signal.reason);
136
+ signal.addEventListener("abort", abort, { once: true });
137
+ watch.start(async (value) => {
138
+ if (value && predicate(value))
139
+ resolve();
140
+ });
141
+ if (signal.aborted)
142
+ abort();
143
+ else if (watch.value && predicate(watch.value))
144
+ resolve();
145
+ watch.closed.then((end) => {
146
+ if (end.reason !== "stopped")
147
+ reject(new Error(`Context watch ended: ${end.reason}`));
148
+ });
149
+ });
150
+ } finally {
151
+ signal.removeEventListener("abort", abort);
152
+ await watch.stop();
153
+ }
154
+ }
155
+ async function cancelInput(host, id, requestId, context) {
156
+ const conv = await conversation(host, id, context);
157
+ const input = await conv.commit((tx) => tx.submissionByRequest(id, requestId), context);
158
+ if (!input || input.status === "done" || input.status === "unanswered")
159
+ return;
160
+ await host.harness.abortSubmission(input.id, context, id);
161
+ await cancelPlacedInput(host, conv, input.id, context);
162
+ }
163
+ async function cancelPlacedInput(host, conv, id, context) {
164
+ const run = await conv.commit(async (tx) => {
165
+ const live = await tx.doc(LiveDoc, conv.id);
166
+ return live.run?.inputs.includes(id) ? live.run.taskId : undefined;
167
+ }, context);
168
+ if (run)
169
+ await host.harness.abortTask(run, context);
170
+ }
171
+
172
+ // packages/context/src/note-store.ts
173
+ import {
174
+ createSession,
175
+ defineDoc as defineDoc3,
176
+ defineDocFamily as defineDocFamily2,
177
+ GenerationTask,
178
+ ToolTask
179
+ } from "@earendil-works/pi-durable";
180
+
181
+ // packages/context/src/query-input.ts
182
+ var actions = {
183
+ notes: {
184
+ list_files_by_prefix: "list",
185
+ read_file: "read",
186
+ search_contents: "search",
187
+ append_to_file: "append",
188
+ write_file: "write"
189
+ },
190
+ history: { list_items: "list", read_item: "read", search_contents: "search" }
191
+ };
192
+ var presentation = [
193
+ "limit",
194
+ "max_results",
195
+ "max_files",
196
+ "max_matches_per_file",
197
+ "file_order",
198
+ "file_order_by",
199
+ "recent_file_first",
200
+ "recent_first",
201
+ "limit_chars",
202
+ "max_chars_per_item"
203
+ ];
204
+ var usedPresentation = {
205
+ "notes:list": ["limit", "file_order", "file_order_by"],
206
+ "notes:search": ["limit", "max_matches_per_file", "recent_file_first"],
207
+ "notes:read": ["start_line", "stop_line", "limit_chars", "offset_chars"],
208
+ "history:list_windows": ["limit", "recent_first"],
209
+ "history:list": ["limit", "recent_first", "max_chars_per_item"],
210
+ "history:search": ["limit", "recent_first"],
211
+ "history:read": ["limit_chars", "offset_chars"]
212
+ };
213
+ function alias(params, from, to) {
214
+ if (!(from in params))
215
+ return;
216
+ if (to in params && params[to] !== params[from])
217
+ throw new Error(`Conflicting ${to} and ${from}; supply only ${to}`);
218
+ params[to] = params[from];
219
+ delete params[from];
220
+ }
221
+ function normalizeQueryInput(namespace, input) {
222
+ if (input === undefined)
223
+ return {};
224
+ if (typeof input === "string") {
225
+ try {
226
+ input = JSON.parse(input);
227
+ } catch {
228
+ throw new Error("Supply an action object or valid JSON object; use {} for help");
229
+ }
230
+ }
231
+ if (!input || typeof input !== "object" || Array.isArray(input))
232
+ throw new Error("Supply an action object; use {} for help");
233
+ const params = { ...input };
234
+ const aliases = actions[namespace];
235
+ const action = aliases[String(params["action"])] ?? params["action"];
236
+ if (action !== undefined)
237
+ params["action"] = action;
238
+ if (namespace === "notes") {
239
+ if (action === "write" || action === "append")
240
+ alias(params, "content", "text");
241
+ if (action === "list" || action === "search") {
242
+ alias(params, "prefix", "path");
243
+ alias(params, "path_prefix", "path");
244
+ alias(params, "max_results", "limit");
245
+ alias(params, "max_files", "limit");
246
+ if (action === "search")
247
+ alias(params, "recent_first", "recent_file_first");
248
+ }
249
+ } else if (["list", "search", "list_windows"].includes(String(action))) {
250
+ alias(params, "max_results", "limit");
251
+ }
252
+ const used = usedPresentation[`${namespace}:${String(action)}`] ?? [];
253
+ for (const hint of presentation)
254
+ if (!used.includes(hint))
255
+ delete params[hint];
256
+ return params;
257
+ }
258
+ function isNoteWrite(input) {
259
+ try {
260
+ if (typeof input === "string")
261
+ input = JSON.parse(input);
262
+ return !!input && typeof input === "object" && "action" in input && ["write", "append", "write_file", "append_to_file"].includes(String(input.action));
263
+ } catch {
264
+ return false;
265
+ }
266
+ }
267
+
268
+ // packages/context/src/note-store.ts
269
+ var NotesState = defineDoc3({
270
+ kind: "howaboua.context.notes-state",
271
+ version: 1,
272
+ scope: "conversation",
273
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
274
+ history: "rewindable",
275
+ fork: "asOf",
276
+ initial: () => ({ files: [], totalBytes: 0 })
277
+ });
278
+ var NoteFile = defineDocFamily2({
279
+ kind: "howaboua.context.note-file",
280
+ version: 1,
281
+ family: true,
282
+ scope: "conversation",
283
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
284
+ history: "rewindable",
285
+ fork: "asOf",
286
+ initial: () => ({ text: "" })
287
+ });
288
+ var WriteReceipt = defineDoc3({
289
+ kind: "howaboua.context.note-write-receipt",
290
+ version: 1,
291
+ scope: "task",
292
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
293
+ initial: () => ({})
294
+ });
295
+ async function readSavedNotes(storage, conversationId, context) {
296
+ const reader = createSession(storage);
297
+ const catalog = await reader.snapshot(NotesState, conversationId, context);
298
+ if (catalog === undefined)
299
+ return [];
300
+ const notes = [];
301
+ const paths = new Set;
302
+ let totalBytes = 0;
303
+ for (const file of catalog.files) {
304
+ context.abortSignal?.throwIfAborted();
305
+ const body = await reader.snapshot(NoteFile, conversationId, file.path, context);
306
+ if (paths.has(file.path) || body === undefined || Buffer.byteLength(body.text, "utf8") !== file.bytes || (body.text === "" ? 0 : body.text.split(`
307
+ `).length) !== file.lines)
308
+ throw new Error(`Saved note catalog/body mismatch: ${file.path}`);
309
+ paths.add(file.path);
310
+ totalBytes += file.bytes;
311
+ notes.push({
312
+ path: file.path,
313
+ text: body.text,
314
+ createdAt: file.createdAt,
315
+ updatedAt: file.updatedAt
316
+ });
317
+ }
318
+ if (totalBytes !== catalog.totalBytes)
319
+ throw new Error("Saved note catalog total bytes mismatch");
320
+ return notes.sort((left, right) => left.path.localeCompare(right.path));
321
+ }
322
+ async function requireNotesWindow(tx, id) {
323
+ const state = await tx.doc(WindowState, id);
324
+ if (!state.window)
325
+ throw new Error("Context window is missing; ask the host to run context.bind or context.submit before using context tools");
326
+ return state.window.id;
327
+ }
328
+ async function readNoteText(tx, id, path) {
329
+ return (await tx.doc(NoteFile, id, path, null)).text;
330
+ }
331
+ async function notesAreFresh(tx, id) {
332
+ const userEntry = await latestUserEntry(tx, id);
333
+ const window = await tx.doc(WindowState, id);
334
+ const state = await tx.doc(NotesState, id);
335
+ 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)
337
+ return false;
338
+ let owner = state.lastWrite.taskId;
339
+ while (owner !== undefined) {
340
+ const task = await tx.task(owner);
341
+ if (!task)
342
+ return false;
343
+ if (task.kind === GenerationTask.definition.name)
344
+ break;
345
+ if (task.abortRequested || task.state.status !== "terminal" || task.state.outcome.status !== "completed")
346
+ return false;
347
+ const result = task.state.outcome.result;
348
+ if (result && typeof result === "object" && !Array.isArray(result)) {
349
+ if (result["isError"] === true)
350
+ return false;
351
+ if (task.kind === ToolTask.definition.name && "entryId" in result) {
352
+ const entryId = result["entryId"];
353
+ if (typeof entryId === "number") {
354
+ const entry = await tx.entry(entryId);
355
+ if (entry?.model?.some((message) => message.role === "toolResult" && message.isError))
356
+ return false;
357
+ }
358
+ }
359
+ }
360
+ owner = task.owner;
361
+ }
362
+ let cursor;
363
+ do {
364
+ const page = await tx.scanTasks({
365
+ conversationId: id,
366
+ kind: ToolTask.definition.name,
367
+ order: "descending"
368
+ }, 64, cursor);
369
+ for (const task of page.items) {
370
+ if (task.id <= state.lastWrite.taskId)
371
+ return true;
372
+ const input = task.input;
373
+ let call = input.kind === "nested" ? input.call : undefined;
374
+ if (input.kind !== "nested") {
375
+ const assistant = (await tx.entry(input.assistant))?.model?.[0];
376
+ call = assistant?.role === "assistant" ? assistant.content.filter((item) => item.type === "toolCall").find((item) => item.id === input.callId) : undefined;
377
+ }
378
+ if (call?.name === "notes" && isNoteWrite(call.arguments))
379
+ return false;
380
+ }
381
+ cursor = page.next;
382
+ } while (cursor !== undefined);
383
+ return true;
384
+ }
385
+ async function beginNoteWrite(tx, id, taskId) {
386
+ const receipt = await tx.doc(WriteReceipt, taskId);
387
+ if (receipt.attempted || receipt.file)
388
+ return;
389
+ receipt.attempted = true;
390
+ (await tx.doc(NotesState, id)).lastAttempt = taskId;
391
+ }
392
+ async function mutateNote(tx, input) {
393
+ const receipt = await tx.doc(WriteReceipt, input.taskId);
394
+ if (receipt.file)
395
+ return { ...receipt.file };
396
+ const userEntry = await latestUserEntry(tx, input.conversationId);
397
+ const windowId = await requireNotesWindow(tx, input.conversationId);
398
+ const catalog = await tx.doc(NotesState, input.conversationId);
399
+ const index = catalog.files.findIndex((file) => file.path === input.path);
400
+ const previous = catalog.files[index];
401
+ const file = await tx.doc(NoteFile, input.conversationId, input.path, null);
402
+ const text = input.append ? file.text + input.text : input.text;
403
+ const bytes = Buffer.byteLength(text, "utf8");
404
+ if (bytes > 1e6)
405
+ throw new Error("Note file exceeds the 1,000,000-byte limit");
406
+ const totalBytes = catalog.totalBytes - (previous?.bytes ?? 0) + bytes;
407
+ const updatedAt = input.now();
408
+ const metadata = {
409
+ path: input.path,
410
+ bytes,
411
+ lines: text === "" ? 0 : text.split(`
412
+ `).length,
413
+ createdAt: previous?.createdAt ?? updatedAt,
414
+ updatedAt
415
+ };
416
+ const nextCatalog = [...catalog.files];
417
+ if (index < 0)
418
+ nextCatalog.push(metadata);
419
+ else
420
+ nextCatalog[index] = metadata;
421
+ const freshness = {
422
+ windowId,
423
+ userEntry,
424
+ taskId: input.taskId,
425
+ updatedAt
426
+ };
427
+ file.text = text;
428
+ catalog.files = nextCatalog;
429
+ catalog.totalBytes = totalBytes;
430
+ catalog.lastWrite = freshness;
431
+ receipt.file = metadata;
432
+ return metadata;
433
+ }
434
+ function noteMetadata(file) {
435
+ return {
436
+ path: file.path,
437
+ bytes: file.bytes,
438
+ created_at: new Date(file.createdAt).toISOString(),
439
+ updated_at: new Date(file.updatedAt).toISOString()
440
+ };
441
+ }
442
+ async function renderNotesThreadHint(reader, id, context, maxBytes = 4000) {
443
+ const state = await reader.snapshot(NotesState, id, context);
444
+ 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:";
446
+ const lines = [];
447
+ for (const file of files) {
448
+ if (lines.length >= 5)
449
+ break;
450
+ const line = `- ${file.path} (${file.lines} ${file.lines === 1 ? "line" : "lines"}, ${file.bytes} UTF-8 bytes)`;
451
+ if (Buffer.byteLength([header, ...lines, line].join(`
452
+ `), "utf8") <= Math.min(maxBytes, 4000))
453
+ lines.push(line);
454
+ }
455
+ return lines.length ? [header, ...lines].join(`
456
+ `) : undefined;
457
+ }
458
+
459
+ // packages/context/src/rollover.ts
460
+ import { defineTask, LiveDoc as LiveDoc3 } from "@earendil-works/pi-durable";
461
+
462
+ // packages/context/src/instruction-run.ts
463
+ import {
464
+ GenerationTask as GenerationTask2,
465
+ LiveDoc as LiveDoc2
466
+ } from "@earendil-works/pi-durable";
467
+ async function startInstruction(tx, id, owner, kind, content, now) {
468
+ if (!await nativeIdle(tx, id))
469
+ return;
470
+ await tx.appendEntry(id, {
471
+ kind,
472
+ model: [{ role: "system", content, timestamp: now }]
473
+ });
474
+ const generation = await tx.createTask(GenerationTask2, {}, {
475
+ ownership: { kind: "task", taskId: owner },
476
+ conversationId: id
477
+ });
478
+ (await tx.doc(LiveDoc2, id)).run = { taskId: generation, inputs: [] };
479
+ return generation;
480
+ }
481
+ async function waitInstruction(host, id, generation, context) {
482
+ for (;; ) {
483
+ await host.harness.waitForTask(generation, context);
484
+ const live = await host.harness.snapshot(LiveDoc2, id, context);
485
+ if (!live?.run)
486
+ return;
487
+ generation = live.run.taskId;
488
+ }
489
+ }
490
+ async function instructionOutcome(tx, id, first) {
491
+ if ((await tx.doc(LiveDoc2, id)).run)
492
+ return;
493
+ let cursor;
494
+ let outcome = "completed";
495
+ let found = false;
496
+ do {
497
+ const page = await tx.scanTasks({
498
+ conversationId: id,
499
+ kind: GenerationTask2.definition.name,
500
+ order: "descending"
501
+ }, 64, cursor);
502
+ for (const task of page.items) {
503
+ if (task.id < first)
504
+ return found ? outcome : undefined;
505
+ found = true;
506
+ if (task.state.status !== "terminal")
507
+ return;
508
+ if (task.state.outcome.status === "aborted")
509
+ outcome = "aborted";
510
+ else if (task.state.outcome.status !== "completed" && outcome !== "aborted")
511
+ outcome = "failed";
512
+ }
513
+ cursor = page.next;
514
+ } while (cursor !== undefined);
515
+ return found ? outcome : undefined;
516
+ }
517
+ async function instructionAnswer(tx, id) {
518
+ let cursor;
519
+ do {
520
+ const page = await tx.scanEntries({ conversationId: id }, 64, cursor);
521
+ for (const entry of page.items) {
522
+ const final = entry.model?.findLast((message) => message.role === "assistant");
523
+ if (final?.role === "assistant")
524
+ return final.stopReason === "stop" || final.stopReason === "length" ? entry.id : undefined;
525
+ if (entry.kind === "howaboua.context.checkpoint" || entry.kind === "howaboua.context.continuation")
526
+ return;
527
+ }
528
+ cursor = page.next;
529
+ } while (cursor !== undefined);
530
+ }
531
+
532
+ // packages/context/src/rollover-preparation.ts
533
+ import {
534
+ defineDoc as defineDoc4
535
+ } from "@earendil-works/pi-durable";
536
+ var RolloverPreparation = defineDoc4({
537
+ kind: "howaboua.context.rollover-preparation",
538
+ version: 1,
539
+ scope: "task",
540
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
541
+ initial: () => ({})
542
+ });
543
+ async function latestContextEntry(tx, id) {
544
+ let cursor;
545
+ do {
546
+ const page = await tx.scanEntries({ conversationId: id }, 64, cursor);
547
+ const entry = page.items.find((item) => item.model?.length || item.head !== undefined || item.edits?.length);
548
+ if (entry)
549
+ return entry.id;
550
+ cursor = page.next;
551
+ } while (cursor !== undefined);
552
+ return null;
553
+ }
554
+ async function prepareRollover(conversation, taskId, callback, request, ready, context) {
555
+ if (!callback)
556
+ return {};
557
+ const admission = await conversation.commit(async (tx) => {
558
+ if (!await ready(tx))
559
+ return {
560
+ error: "Conversation changed before context rollover; save fresh notes and retry after it settles"
561
+ };
562
+ const receipt = await tx.doc(RolloverPreparation, taskId);
563
+ if (receipt.state?.status === "done")
564
+ return { head: receipt.state.head };
565
+ if (receipt.state?.status === "failed")
566
+ return { error: receipt.state.error };
567
+ if (receipt.state?.status === "started")
568
+ return {
569
+ error: "Context rollover preparation was interrupted; its outcome is uncertain. The window is unchanged. Check the connected service before requesting another rollover"
570
+ };
571
+ const head = await latestContextEntry(tx, conversation.id);
572
+ receipt.state = { status: "started", head };
573
+ return { head, execute: true };
574
+ }, context);
575
+ if (!admission.execute || admission.head === undefined)
576
+ return admission;
577
+ const head = admission.head;
578
+ try {
579
+ await callback(request, context);
580
+ context.abortSignal?.throwIfAborted();
581
+ } catch (error) {
582
+ context.abortSignal?.throwIfAborted();
583
+ const reason = `Context rollover preparation failed: ${error instanceof Error ? error.message : String(error)}. The window is unchanged`;
584
+ await conversation.commit(async (tx) => {
585
+ (await tx.doc(RolloverPreparation, taskId)).state = {
586
+ status: "failed",
587
+ error: reason
588
+ };
589
+ }, context);
590
+ return { error: reason };
591
+ }
592
+ await conversation.commit(async (tx) => {
593
+ (await tx.doc(RolloverPreparation, taskId)).state = {
594
+ status: "done",
595
+ head
596
+ };
597
+ }, context);
598
+ return { head };
599
+ }
600
+
601
+ // packages/context/src/rollover.ts
602
+ 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
+ var key = (task) => `context:checkpoint:${task}`;
604
+ async function completedFreshNotes(host, id, context) {
605
+ const conv = await conversation(host, id, context);
606
+ const state = await conv.commit(async (tx) => ({
607
+ fresh: await notesAreFresh(tx, id),
608
+ user: await latestUserEntry(tx, id)
609
+ }), context);
610
+ if (!state.fresh || state.user === null)
611
+ return false;
612
+ let cursor;
613
+ let newest = 0;
614
+ let done = false;
615
+ do {
616
+ const page = await host.storage.scanSubmissions({ conversationId: id }, 64, cursor, context);
617
+ for (const submission of page.items) {
618
+ if (submission.type !== "input" || submission.entry === undefined || submission.entry > state.user || submission.entry <= newest)
619
+ continue;
620
+ newest = submission.entry;
621
+ done = submission.status === "done" && submission.answer > state.user;
622
+ }
623
+ cursor = page.next;
624
+ } while (cursor !== undefined);
625
+ return done;
626
+ }
627
+ function createRollover(host, beforeRollover) {
628
+ return defineTask({
629
+ name: ROLLOVER_TASK,
630
+ version: 1,
631
+ initial: () => ({ phase: "prepare" }),
632
+ phases: {
633
+ prepare: async (task, runtime, context) => {
634
+ const conv = await conversation(host(), task.conversationId, context);
635
+ for (;; ) {
636
+ const tasks = await conv.commit((tx) => foreignTasks(tx, conv.id), context);
637
+ if (!tasks.length)
638
+ break;
639
+ await Promise.all(tasks.map((id) => runtime.waitForTask(id, context)));
640
+ }
641
+ const fresh = await completedFreshNotes(host(), conv.id, context);
642
+ if (fresh) {
643
+ await runtime.commit(() => ({ status: "running", checkpoint: { phase: "rotate" } }), context);
644
+ return;
645
+ }
646
+ if (task.input.reason === "idle") {
647
+ await runtime.commit(async (tx) => {
648
+ const state = await tx.doc(WindowState, conv.id);
649
+ if (state.transition === task.id)
650
+ delete state.transition;
651
+ return {
652
+ status: "terminal",
653
+ outcome: {
654
+ status: "completed",
655
+ result: {
656
+ status: "skipped",
657
+ reason: "Latest completed run has no fresh notes"
658
+ }
659
+ }
660
+ };
661
+ }, context);
662
+ return;
663
+ }
664
+ await runtime.commit(async (tx) => {
665
+ const generation = await startInstruction(tx, conv.id, task.id, "howaboua.context.checkpoint", checkpointPrompt, runtime.now());
666
+ if (!generation)
667
+ return { status: "running", checkpoint: { phase: "prepare" } };
668
+ return {
669
+ status: "running",
670
+ checkpoint: { phase: "instruction", generation }
671
+ };
672
+ }, context);
673
+ },
674
+ checkpoint: async (task, runtime, context) => {
675
+ const submission = await host().harness.submission(task.state.checkpoint.submission, context);
676
+ if (!submission)
677
+ throw new Error("Context checkpoint submission is missing");
678
+ const result = await submission.wait(context);
679
+ await runtime.commit(async (tx) => {
680
+ const fresh = await notesAreFresh(tx, task.conversationId);
681
+ if (result.status === "done" && fresh)
682
+ return { status: "running", checkpoint: { phase: "rotate" } };
683
+ const state = await tx.doc(WindowState, task.conversationId);
684
+ if (result.status === "unanswered" && result.reason === "aborted")
685
+ await cancelHeldInputs(tx, task.conversationId);
686
+ if (state.transition === task.id)
687
+ delete state.transition;
688
+ return {
689
+ status: "terminal",
690
+ outcome: {
691
+ status: "completed",
692
+ result: result.status === "unanswered" && result.reason === "aborted" ? { status: "cancelled" } : {
693
+ status: "failed",
694
+ reason: result.status === "done" ? "Checkpoint finished without saving fresh notes" : `Checkpoint was unanswered: ${result.reason}`
695
+ }
696
+ }
697
+ };
698
+ }, context);
699
+ },
700
+ instruction: async (task, runtime, context) => {
701
+ await waitInstruction(host(), task.conversationId, task.state.checkpoint.generation, context);
702
+ await runtime.commit(async (tx) => {
703
+ const outcome = await instructionOutcome(tx, task.conversationId, task.state.checkpoint.generation);
704
+ if (!outcome)
705
+ return;
706
+ const aborted = outcome === "aborted";
707
+ const fresh = await notesAreFresh(tx, task.conversationId);
708
+ if (outcome === "completed" && fresh && await instructionAnswer(tx, task.conversationId))
709
+ return { status: "running", checkpoint: { phase: "rotate" } };
710
+ const state = await tx.doc(WindowState, task.conversationId);
711
+ if (aborted)
712
+ await cancelHeldInputs(tx, task.conversationId);
713
+ if (state.transition === task.id)
714
+ delete state.transition;
715
+ return {
716
+ status: "terminal",
717
+ outcome: {
718
+ status: "completed",
719
+ result: aborted ? { status: "cancelled" } : {
720
+ status: "failed",
721
+ reason: "Checkpoint finished without saving fresh notes"
722
+ }
723
+ }
724
+ };
725
+ }, context);
726
+ },
727
+ rotate: async (task, runtime, context) => {
728
+ const conv = await conversation(host(), task.conversationId, context);
729
+ for (;; ) {
730
+ const tasks = await conv.commit((tx) => foreignTasks(tx, conv.id), context);
731
+ if (!tasks.length)
732
+ break;
733
+ await Promise.all(tasks.map((id) => runtime.waitForTask(id, context)));
734
+ }
735
+ const ready = async (tx) => {
736
+ const state = await tx.doc(WindowState, task.conversationId);
737
+ const completed = task.input.reason !== "idle" || state.settlement?.completed === true && state.settlement.userEntry === await latestUserEntry(tx, task.conversationId);
738
+ if (!state.window || state.transition !== task.id)
739
+ throw new Error("Context rollover lost its window claim");
740
+ return completed && await nativeIdle(tx, task.conversationId) && (await foreignTasks(tx, task.conversationId)).length === 0 && await notesAreFresh(tx, task.conversationId);
741
+ };
742
+ const current = await runtime.snapshot(WindowState, task.conversationId, context);
743
+ const preparation = await prepareRollover(conv, task.id, beforeRollover, {
744
+ conversationId: task.conversationId,
745
+ windowId: current?.window?.id ?? "",
746
+ nextWindowId: task.input.windowId,
747
+ reason: task.input.reason
748
+ }, ready, context);
749
+ await runtime.commit(async (tx) => {
750
+ const safe = !preparation.error && await ready(tx) && (preparation.head === undefined || preparation.head === await latestContextEntry(tx, task.conversationId));
751
+ const state = await tx.doc(WindowState, task.conversationId);
752
+ if (!safe || !state.window) {
753
+ delete state.transition;
754
+ return {
755
+ status: "terminal",
756
+ outcome: {
757
+ status: "completed",
758
+ result: {
759
+ status: !preparation.error && task.input.reason === "idle" ? "skipped" : "failed",
760
+ reason: preparation.error ?? (task.input.reason === "idle" ? "Conversation changed before automatic context rollover" : "Conversation changed before context rollover; retry after it settles")
761
+ }
762
+ }
763
+ };
764
+ }
765
+ const window = {
766
+ id: task.input.windowId,
767
+ number: state.window.number + 1,
768
+ startedAt: runtime.now(),
769
+ previous: state.window.id
770
+ };
771
+ const entry = await tx.appendEntry(WindowEntry, task.conversationId, {
772
+ data: window,
773
+ head: "self"
774
+ });
775
+ state.window = window;
776
+ state.entry = entry.id;
777
+ state.reminded = 0;
778
+ delete state.settlement;
779
+ if (task.input.continue)
780
+ return {
781
+ status: "running",
782
+ checkpoint: { phase: "continue", window }
783
+ };
784
+ delete state.transition;
785
+ return {
786
+ status: "terminal",
787
+ outcome: {
788
+ status: "completed",
789
+ result: { status: "done", window }
790
+ }
791
+ };
792
+ }, context);
793
+ },
794
+ continue: async (task, runtime, context) => {
795
+ await runtime.commit(async (tx) => {
796
+ const generation = await startInstruction(tx, task.conversationId, task.id, "howaboua.context.continuation", "Read your saved notes with the notes tool and resume the task.", runtime.now());
797
+ if (!generation)
798
+ throw new Error("Conversation changed before legacy continuation");
799
+ return {
800
+ status: "running",
801
+ checkpoint: {
802
+ phase: "continued",
803
+ window: task.state.checkpoint.window,
804
+ generation
805
+ }
806
+ };
807
+ }, context);
808
+ },
809
+ continued: async (task, runtime, context) => {
810
+ await waitInstruction(host(), task.conversationId, task.state.checkpoint.generation, context);
811
+ await runtime.commit(async (tx) => {
812
+ const outcome = await instructionOutcome(tx, task.conversationId, task.state.checkpoint.generation);
813
+ if (!outcome)
814
+ return;
815
+ const state = await tx.doc(WindowState, task.conversationId);
816
+ if (state.transition === task.id)
817
+ delete state.transition;
818
+ const answer = await instructionAnswer(tx, task.conversationId);
819
+ return {
820
+ status: "terminal",
821
+ outcome: {
822
+ status: "completed",
823
+ result: outcome === "completed" && answer !== undefined ? {
824
+ status: "done",
825
+ window: task.state.checkpoint.window,
826
+ answer
827
+ } : {
828
+ status: "failed",
829
+ reason: "Context continuation did not finish successfully"
830
+ }
831
+ }
832
+ };
833
+ }, context);
834
+ }
835
+ },
836
+ abort: async (task, runtime, context) => {
837
+ if (task.state.checkpoint.phase === "instruction" || task.state.checkpoint.phase === "continued") {
838
+ const live = await runtime.snapshot(LiveDoc3, task.conversationId, context);
839
+ if (live?.run && live.run.inputs.length === 0) {
840
+ await host().harness.abortTask(live.run.taskId, context);
841
+ await host().harness.waitForTask(live.run.taskId, context);
842
+ }
843
+ }
844
+ await cancelInput(host(), task.conversationId, key(task.id), context);
845
+ await cancelInput(host(), task.conversationId, `context:continue:${task.id}`, context);
846
+ await runtime.commit(async (tx) => {
847
+ const state = await tx.doc(WindowState, task.conversationId);
848
+ if (state.transition === task.id) {
849
+ await cancelHeldInputs(tx, task.conversationId);
850
+ delete state.transition;
851
+ }
852
+ return { status: "terminal", outcome: { status: "aborted" } };
853
+ }, context);
854
+ }
855
+ });
856
+ }
857
+ async function scheduleRollover(tx, id, task, reason, owner) {
858
+ const state = await tx.doc(WindowState, id);
859
+ if (!state.window)
860
+ throw new Error("Context window has not been initialized");
861
+ if (state.transition)
862
+ return state.transition;
863
+ const next = await tx.createTask(task, { reason, continue: reason === "tool", windowId: crypto.randomUUID() }, {
864
+ ownership: owner === undefined ? { kind: "conversation" } : { kind: "task", taskId: owner },
865
+ conversationId: id
866
+ });
867
+ state.transition = next;
868
+ return next;
869
+ }
870
+ async function transitionResult(host, id, context) {
871
+ const task = await host.harness.waitForTask(id, context);
872
+ return task.state.outcome.status === "completed" ? task.state.outcome.result : task.state.outcome.status === "aborted" ? { status: "cancelled" } : {
873
+ status: "failed",
874
+ reason: `Context rollover ${task.state.outcome.status}`
875
+ };
876
+ }
877
+
878
+ // packages/context/src/admission.ts
879
+ function createInput(host, rollover, idleMs) {
880
+ return defineTask2({
881
+ name: INPUT_TASK,
882
+ version: 1,
883
+ initial: () => ({ phase: "admit" }),
884
+ phases: {
885
+ admit: async (task, runtime, context) => {
886
+ await until(await runtime.watchDoc(Admission, task.conversationId, context), (state) => state.queue[0] === task.id || state.cancelled.includes(task.id), runtime.signal);
887
+ if ((await runtime.snapshot(Admission, task.conversationId, context))?.cancelled.includes(task.id)) {
888
+ await runtime.commit(async (tx) => {
889
+ await releaseAdmission(tx, task.conversationId, task.id);
890
+ return { status: "terminal", outcome: { status: "aborted" } };
891
+ }, context);
892
+ return;
893
+ }
894
+ const conv = await conversation(host(), task.conversationId, context);
895
+ const decision = await conv.commit(async (tx) => {
896
+ const userEntry = await latestUserEntry(tx, conv.id);
897
+ const idle = await nativeIdle(tx, conv.id);
898
+ const tasks = await foreignTasks(tx, conv.id);
899
+ const state = await tx.doc(WindowState, conv.id);
900
+ const gate = await tx.doc(Admission, conv.id);
901
+ const due = idleMs > 0 && idle && tasks.length === 0 && state.settlement !== undefined && state.settlement.completed === true && state.settlement.userEntry === userEntry && runtime.now() - state.settlement.observedAt >= idleMs && await notesAreFresh(tx, conv.id);
902
+ const transition = state.transition ?? (due || task.state.checkpoint.checkpointRequired ? await scheduleRollover(tx, conv.id, rollover, task.state.checkpoint.checkpointRequired ? "manual" : "idle", task.id) : undefined);
903
+ return { transition, retry: gate.retry };
904
+ }, context);
905
+ if (decision.transition) {
906
+ const result = await transitionResult(host(), decision.transition, context);
907
+ if (result.status === "cancelled") {
908
+ await runtime.commit(async (tx) => {
909
+ await cancelHeldInputs(tx, conv.id);
910
+ await releaseAdmission(tx, conv.id, task.id);
911
+ return { status: "terminal", outcome: { status: "aborted" } };
912
+ }, context);
913
+ return;
914
+ }
915
+ if (result.status === "failed") {
916
+ await runtime.commit(async (tx) => {
917
+ const gate = await tx.doc(Admission, conv.id);
918
+ gate.blocked = { task: task.id, reason: result.reason };
919
+ return {
920
+ status: "running",
921
+ checkpoint: {
922
+ phase: "blocked",
923
+ retry: decision.retry,
924
+ reason: result.reason
925
+ }
926
+ };
927
+ }, context);
928
+ return;
929
+ }
930
+ }
931
+ let submission;
932
+ try {
933
+ submission = await conv.submit({ ...task.input, requestId: `context:input:${task.id}` }, context);
934
+ } catch (error) {
935
+ if (!(error instanceof ConversationBusy))
936
+ throw error;
937
+ await runtime.commit(async (tx) => {
938
+ await releaseAdmission(tx, conv.id, task.id);
939
+ return {
940
+ status: "terminal",
941
+ outcome: { status: "failed", error: { message: error.message } }
942
+ };
943
+ }, context);
944
+ return;
945
+ }
946
+ await runtime.commit(async (tx) => {
947
+ await releaseAdmission(tx, conv.id, task.id);
948
+ return {
949
+ status: "running",
950
+ checkpoint: { phase: "observe", submission: submission.id }
951
+ };
952
+ }, context);
953
+ },
954
+ blocked: async (task, runtime, context) => {
955
+ await until(await runtime.watchDoc(Admission, task.conversationId, context), (gate) => gate.retry > task.state.checkpoint.retry || gate.cancelled.includes(task.id), runtime.signal);
956
+ await runtime.commit(async (tx) => {
957
+ const gate = await tx.doc(Admission, task.conversationId);
958
+ if (gate.cancelled.includes(task.id)) {
959
+ await releaseAdmission(tx, task.conversationId, task.id);
960
+ return { status: "terminal", outcome: { status: "aborted" } };
961
+ }
962
+ if (gate.blocked?.task === task.id)
963
+ delete gate.blocked;
964
+ return {
965
+ status: "running",
966
+ checkpoint: { phase: "admit", checkpointRequired: true }
967
+ };
968
+ }, context);
969
+ },
970
+ observe: async (task, runtime, context) => {
971
+ const submission = await host().harness.submission(task.state.checkpoint.submission, context);
972
+ if (!submission)
973
+ throw new Error("Managed input submission is missing");
974
+ const settled = await submission.wait(context);
975
+ if (settled.type !== "input")
976
+ throw new Error("Managed submission is not an input");
977
+ const continuation = await runtime.snapshot(Continuation, task.conversationId, String(submission.id), context);
978
+ if (continuation?.task) {
979
+ const result = await transitionResult(host(), continuation.task, context);
980
+ if (result.status === "done" && result.answer !== undefined) {
981
+ const answer = result.answer;
982
+ await runtime.commit(() => ({
983
+ status: "terminal",
984
+ outcome: {
985
+ status: "completed",
986
+ result: { status: "done", answer, submission: submission.id }
987
+ }
988
+ }), context);
989
+ return;
990
+ }
991
+ if (result.status === "done" && result.continuation !== undefined) {
992
+ const next = result.continuation;
993
+ await runtime.commit(() => ({
994
+ status: "running",
995
+ checkpoint: { phase: "observe", submission: next }
996
+ }), context);
997
+ return;
998
+ }
999
+ await runtime.commit(() => ({
1000
+ status: "terminal",
1001
+ outcome: {
1002
+ status: "failed",
1003
+ error: {
1004
+ message: result.status === "failed" ? result.reason : "Context continuation was cancelled"
1005
+ }
1006
+ }
1007
+ }), context);
1008
+ return;
1009
+ }
1010
+ await runtime.commit(async (tx) => {
1011
+ const userEntry = await latestUserEntry(tx, task.conversationId);
1012
+ const idle = await nativeIdle(tx, task.conversationId);
1013
+ const state = await tx.doc(WindowState, task.conversationId);
1014
+ if (idle && !state.transition)
1015
+ state.settlement = {
1016
+ observedAt: runtime.now(),
1017
+ userEntry,
1018
+ completed: settled.status === "done" && userEntry !== null && settled.answer > userEntry
1019
+ };
1020
+ const result = settled.status === "done" ? {
1021
+ status: "done",
1022
+ answer: settled.answer,
1023
+ submission: submission.id
1024
+ } : {
1025
+ status: "unanswered",
1026
+ reason: settled.reason,
1027
+ submission: submission.id,
1028
+ ...settled.detail === undefined ? {} : { detail: settled.detail }
1029
+ };
1030
+ return {
1031
+ status: "terminal",
1032
+ outcome: { status: "completed", result }
1033
+ };
1034
+ }, context);
1035
+ }
1036
+ },
1037
+ abort: async (task, runtime, context) => {
1038
+ const binding = host();
1039
+ const conv = await conversation(binding, task.conversationId, context);
1040
+ const original = await conv.commit((tx) => tx.submissionByRequest(conv.id, `context:input:${task.id}`), context);
1041
+ const submission = task.state.checkpoint.phase === "observe" ? task.state.checkpoint.submission : original?.id;
1042
+ if (submission !== undefined)
1043
+ await cancelContinuation(binding, conv.id, submission, context);
1044
+ const window = await runtime.snapshot(WindowState, conv.id, context);
1045
+ if (window?.transition) {
1046
+ const transition = await runtime.getTask(window.transition, context);
1047
+ if (transition?.owner === task.id) {
1048
+ await binding.harness.abortTask(transition.id, context);
1049
+ await binding.harness.waitForTask(transition.id, context);
1050
+ }
1051
+ }
1052
+ await runtime.commit(async (tx) => {
1053
+ await releaseAdmission(tx, task.conversationId, task.id);
1054
+ return { status: "terminal", outcome: { status: "aborted" } };
1055
+ }, context);
1056
+ }
1057
+ });
1058
+ }
1059
+ async function cancelContinuation(host, id, first, context) {
1060
+ const conv = await conversation(host, id, context);
1061
+ let current = first;
1062
+ while (current !== undefined) {
1063
+ await host.harness.abortSubmission(current, context, id);
1064
+ await cancelPlacedInput(host, conv, current, context);
1065
+ const link = await host.harness.snapshot(Continuation, id, String(current), context);
1066
+ if (!link?.task)
1067
+ return;
1068
+ await host.harness.abortTask(link.task, context);
1069
+ await host.harness.waitForTask(link.task, context);
1070
+ const next = await conv.commit((tx) => tx.submissionByRequest(id, `context:continue:${link.task}`), context);
1071
+ current = next?.id;
1072
+ }
1073
+ }
1074
+
1075
+ // packages/context/src/history.ts
1076
+ import {
1077
+ CompactionEntry as CompactionEntry2,
1078
+ defineTool
1079
+ } from "@earendil-works/pi-durable";
1080
+ import { Type as Type2 } from "typebox";
1081
+
1082
+ // internal/context-visibility.ts
1083
+ import { createSession as createSession2, defineDoc as defineDoc5 } from "@earendil-works/pi-durable";
1084
+ var SHARED_GROUP = "shared";
1085
+ var ContextVisibility = defineDoc5({
1086
+ kind: "howaboua.context.visibility",
1087
+ version: 1,
1088
+ scope: "conversation",
1089
+ history: "latest",
1090
+ fork: "current",
1091
+ checkpointWhen: () => true,
1092
+ initial: () => ({ group: SHARED_GROUP })
1093
+ });
1094
+ async function canReadContextTarget(storage, caller, target, context) {
1095
+ const reader = createSession2(storage);
1096
+ const [callerState, targetState] = await Promise.all([
1097
+ reader.snapshot(ContextVisibility, caller, context),
1098
+ reader.snapshot(ContextVisibility, target, context)
1099
+ ]);
1100
+ return (callerState?.group ?? SHARED_GROUP) === (targetState?.group ?? SHARED_GROUP);
1101
+ }
1102
+
1103
+ // packages/context/src/history-archive.ts
1104
+ import {
1105
+ CompactionEntry,
1106
+ UserEntry
1107
+ } from "@earendil-works/pi-durable";
1108
+ async function* retainedBranches(storage, caller, target, context, familyTargets) {
1109
+ const ancestry = async (id) => {
1110
+ const chain = [];
1111
+ const seen = new Set;
1112
+ for (;; ) {
1113
+ context.abortSignal?.throwIfAborted();
1114
+ if (seen.has(id))
1115
+ throw new Error("Retained conversation ancestry contains a cycle");
1116
+ seen.add(id);
1117
+ const record = await storage.conversation(id, context);
1118
+ if (!record)
1119
+ throw new Error("Retained conversation ancestry is unavailable");
1120
+ chain.push(record);
1121
+ if (!record.parent)
1122
+ return chain;
1123
+ id = record.parent.conversationId;
1124
+ }
1125
+ };
1126
+ const current = await ancestry(target);
1127
+ const root = current.at(-1)?.id;
1128
+ const inherited = new Map;
1129
+ let cutoff;
1130
+ for (const record of current) {
1131
+ if (cutoff !== undefined)
1132
+ inherited.set(record.id, cutoff);
1133
+ if (record.parent)
1134
+ cutoff = cutoff === undefined || record.parent.at < cutoff ? record.parent.at : cutoff;
1135
+ }
1136
+ let cursor;
1137
+ do {
1138
+ context.abortSignal?.throwIfAborted();
1139
+ const page = await storage.scanConversations({ order: "descending" }, 64, cursor, context);
1140
+ for (const record of page.items) {
1141
+ context.abortSignal?.throwIfAborted();
1142
+ if (record.id === target || familyTargets && !familyTargets.includes(record.id) || (await ancestry(record.id)).at(-1)?.id !== root)
1143
+ continue;
1144
+ if (!await canReadContextTarget(storage, caller, record.id, context) || !await canReadContextTarget(storage, target, record.id, context))
1145
+ continue;
1146
+ const after = inherited.get(record.id);
1147
+ yield { id: record.id, ...after === undefined ? {} : { after } };
1148
+ }
1149
+ cursor = page.next;
1150
+ } while (cursor !== undefined);
1151
+ }
1152
+ async function* historyEntries(options) {
1153
+ const { context, conversation, archive } = options;
1154
+ const branches = archive ? retainedBranches(options.storage, options.caller, conversation.id, context, options.familyTargets) : [];
1155
+ async function* readers() {
1156
+ yield { id: conversation.id };
1157
+ yield* branches;
1158
+ }
1159
+ for await (const branch of readers()) {
1160
+ const extra = branch.id !== conversation.id;
1161
+ if (options.windowId && (extra ? !options.windowId.startsWith(`archive:${branch.id}:`) : options.windowId.startsWith("archive:")))
1162
+ continue;
1163
+ const reader = extra ? await options.reader(branch.id, context) : conversation;
1164
+ if (reader.id !== branch.id)
1165
+ throw new Error("Archive reader is bound to a different conversation");
1166
+ let windowId = extra ? await options.activeWindowFor(branch.id) : options.activeWindow;
1167
+ let cursor;
1168
+ do {
1169
+ context.abortSignal?.throwIfAborted();
1170
+ const page = await reader.entries({}, 64, cursor, context);
1171
+ for (const entry of page.items) {
1172
+ context.abortSignal?.throwIfAborted();
1173
+ const boundary = WindowEntry.is(entry);
1174
+ if (archive && boundary && (!entry.data || typeof entry.data.id !== "string" || !entry.data.id || entry.data.previous !== undefined && (typeof entry.data.previous !== "string" || !entry.data.previous || entry.data.previous === entry.data.id)))
1175
+ throw new Error("Retained window has an invalid archive reference");
1176
+ if (boundary)
1177
+ windowId = entry.data.id;
1178
+ if (!extra || entry.conversationId === branch.id && (!("after" in branch) || branch.after === undefined || entry.id > branch.after)) {
1179
+ const summary = archive && CompactionEntry.is(entry);
1180
+ if (summary) {
1181
+ if (entry.head === undefined || entry.head >= entry.id || !(await reader.entries({ minEntryId: entry.head, maxEntryId: entry.head }, 1, undefined, context)).items.some((item) => item.id === entry.head))
1182
+ throw new Error("Retained summary references an unavailable archive boundary");
1183
+ }
1184
+ yield {
1185
+ windowId: extra ? `archive:${branch.id}:${encodeURIComponent(windowId)}` : windowId,
1186
+ entry,
1187
+ boundary,
1188
+ summary
1189
+ };
1190
+ }
1191
+ if (boundary)
1192
+ windowId = entry.data.previous ?? entry.data.id;
1193
+ }
1194
+ cursor = page.next;
1195
+ } while (cursor !== undefined);
1196
+ }
1197
+ }
1198
+ async function renderArchiveHistoryHint(conversation, activeWindow, context) {
1199
+ const users = [];
1200
+ let summary;
1201
+ let windowId = activeWindow;
1202
+ let cursor;
1203
+ do {
1204
+ context.abortSignal?.throwIfAborted();
1205
+ const page = await conversation.entries({}, 64, cursor, context);
1206
+ for (const entry of page.items) {
1207
+ context.abortSignal?.throwIfAborted();
1208
+ if (WindowEntry.is(entry)) {
1209
+ windowId = entry.data.previous ?? entry.data.id;
1210
+ continue;
1211
+ }
1212
+ const reference = { window_id: windowId, item_id: String(entry.id) };
1213
+ if (!summary && CompactionEntry.is(entry)) {
1214
+ if (entry.head === undefined || entry.head >= entry.id || !(await conversation.entries({ minEntryId: entry.head, maxEntryId: entry.head }, 1, undefined, context)).items.some((item) => item.id === entry.head))
1215
+ throw new Error("Retained summary references an unavailable archive boundary");
1216
+ summary = reference;
1217
+ }
1218
+ if (users.length < 3 && UserEntry.is(entry))
1219
+ users.push(reference);
1220
+ if (summary && users.length === 3)
1221
+ break;
1222
+ }
1223
+ cursor = page.next;
1224
+ } while (cursor !== undefined && !(summary && users.length === 3));
1225
+ if (!summary && users.length === 0)
1226
+ return "";
1227
+ return `History recovery IDs: ${JSON.stringify({ ...summary ? { summary } : {}, recent_user_requests: users })}. Read known items directly or search for missing details; do not enumerate the archive.`;
1228
+ }
1229
+
1230
+ // packages/context/src/history-items.ts
1231
+ import {
1232
+ AssistantEntry,
1233
+ UserEntry as UserEntry2
1234
+ } from "@earendil-works/pi-durable";
1235
+
1236
+ // packages/context/src/tool-contract.ts
1237
+ import { Type } from "typebox";
1238
+ 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
+ var contextOutputLimits = { maxBytes: Infinity, maxLines: Infinity };
1255
+ function contextTextSlice(text, offset, limit) {
1256
+ if (offset > 0 && (text.codePointAt(offset - 1) ?? 0) > 65535)
1257
+ throw new Error("offset_chars splits a Unicode character; reduce it by one");
1258
+ let end = offset + limit;
1259
+ if (limit > 0 && (text.codePointAt(end - 1) ?? 0) > 65535)
1260
+ end++;
1261
+ return text.slice(offset, end);
1262
+ }
1263
+ function contextToolResult(result, details = result) {
1264
+ const text = JSON.stringify(result);
1265
+ return {
1266
+ output: [{ type: "text", text }],
1267
+ structuredOutput: result,
1268
+ details
1269
+ };
1270
+ }
1271
+ var nullableString = Type.Union([Type.String(), Type.Null()]);
1272
+ var positiveInteger = Type.Integer({ minimum: 1 });
1273
+ var target = Type.Optional(Type.String({
1274
+ pattern: "^[1-9][0-9]*$",
1275
+ description: "Durable conversation ID; defaults to caller"
1276
+ }));
1277
+ var historyParameters = Type.Object({
1278
+ action: Type.Optional(Type.Union(HISTORY_ACTIONS.map((action) => Type.Literal(action)))),
1279
+ target,
1280
+ item_id: Type.Optional(Type.String()),
1281
+ agent_name: Type.Optional(nullableString),
1282
+ limit: Type.Optional(positiveInteger),
1283
+ limit_chars: Type.Optional(positiveInteger),
1284
+ max_chars_per_item: Type.Optional(positiveInteger),
1285
+ offset_chars: Type.Optional(Type.Integer({ minimum: 0 })),
1286
+ query: Type.Optional(Type.String()),
1287
+ recent_first: Type.Optional(Type.Boolean()),
1288
+ role: Type.Optional(Type.Union([
1289
+ Type.Literal("user"),
1290
+ Type.Literal("assistant"),
1291
+ Type.Literal("tool"),
1292
+ Type.Literal("system"),
1293
+ Type.Literal("developer"),
1294
+ Type.Null()
1295
+ ])),
1296
+ tool_name: Type.Optional(nullableString),
1297
+ tool_namespace: Type.Optional(nullableString),
1298
+ window_id: Type.Optional(Type.Union([Type.String(), Type.Null()], {
1299
+ description: "Required with item_id for read"
1300
+ }))
1301
+ }, { additionalProperties: false });
1302
+ var notesParameters = Type.Object({
1303
+ action: Type.Optional(Type.Union(NOTES_ACTIONS.map((action) => Type.Literal(action)))),
1304
+ target,
1305
+ agent_name: Type.Optional(nullableString),
1306
+ file_order: Type.Optional(Type.Union([Type.Literal("ascending"), Type.Literal("descending")])),
1307
+ file_order_by: Type.Optional(Type.Union([
1308
+ Type.Literal("name"),
1309
+ Type.Literal("created_at"),
1310
+ Type.Literal("updated_at")
1311
+ ])),
1312
+ limit: Type.Optional(positiveInteger),
1313
+ max_matches_per_file: Type.Optional(positiveInteger),
1314
+ path: Type.Optional(Type.Union([Type.String(), Type.Null()], {
1315
+ description: "File for read/write/append; prefix for list/search"
1316
+ })),
1317
+ query: Type.Optional(Type.String()),
1318
+ recent_file_first: Type.Optional(Type.Boolean()),
1319
+ start_line: Type.Optional(Type.Union([Type.Integer(), Type.Null()])),
1320
+ stop_line: Type.Optional(Type.Union([Type.Integer(), Type.Null()])),
1321
+ limit_chars: Type.Optional(positiveInteger),
1322
+ offset_chars: Type.Optional(Type.Integer({ minimum: 0 })),
1323
+ text: Type.Optional(Type.String())
1324
+ }, { additionalProperties: false });
1325
+ var newContextParameters = Type.Object({ role: Type.Optional(Type.String({ minLength: 1 })) }, { additionalProperties: false });
1326
+ function prepareNewContextArguments(input) {
1327
+ 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.');
1330
+ return args;
1331
+ }
1332
+ function prepareNotesArguments(input) {
1333
+ const args = normalizeQueryInput("notes", input);
1334
+ if (!Check(notesParameters, args))
1335
+ throw new Error("Supply valid notes arguments; omit arguments for help");
1336
+ return args;
1337
+ }
1338
+ function prepareHistoryArguments(input) {
1339
+ const args = normalizeQueryInput("history", input);
1340
+ if (!Check(historyParameters, args))
1341
+ throw new Error("Supply valid history arguments; omit arguments for help");
1342
+ return args;
1343
+ }
1344
+ var notesFields = {
1345
+ help: [],
1346
+ list: ["file_order", "file_order_by", "limit", "path"],
1347
+ read: ["path", "start_line", "stop_line", "limit_chars", "offset_chars"],
1348
+ search: [
1349
+ "limit",
1350
+ "max_matches_per_file",
1351
+ "path",
1352
+ "query",
1353
+ "recent_file_first"
1354
+ ],
1355
+ append: ["path", "text"],
1356
+ write: ["path", "text"]
1357
+ };
1358
+ var historyFields = {
1359
+ help: [],
1360
+ list_windows: ["limit", "recent_first"],
1361
+ list: [
1362
+ "limit",
1363
+ "max_chars_per_item",
1364
+ "recent_first",
1365
+ "role",
1366
+ "tool_name",
1367
+ "tool_namespace",
1368
+ "window_id"
1369
+ ],
1370
+ read: ["item_id", "limit_chars", "offset_chars", "window_id"],
1371
+ search: [
1372
+ "limit",
1373
+ "query",
1374
+ "recent_first",
1375
+ "role",
1376
+ "tool_name",
1377
+ "tool_namespace",
1378
+ "window_id"
1379
+ ]
1380
+ };
1381
+ function contextToolHelp(namespace, args, rankedHistory = false) {
1382
+ if (Object.keys(args).length && args.action !== "help")
1383
+ return;
1384
+ if (Object.keys(args).some((key) => key !== "action"))
1385
+ throw new Error("Help accepts only action: help");
1386
+ const fields = namespace === "notes" ? notesFields : historyFields;
1387
+ return {
1388
+ actions: Object.fromEntries(Object.entries(fields).map(([action, names]) => [
1389
+ action,
1390
+ names.map((name) => (name === "path" ? ["read", "write", "append"].includes(action) : ["text", "query", "item_id"].includes(name)) || action === "read" && name === "window_id" ? name : `${name}?`).join(" ")
1391
+ ])),
1392
+ target: "Durable conversation ID; defaults to caller; reads require the same Context visibility group; write own",
1393
+ ...namespace === "notes" ? {
1394
+ writes: "write replaces; append adds",
1395
+ paths: "Paths are relative to /notes; target selects a conversation, read-only unless your own",
1396
+ usage: '{ "action": "read", "path": "checkpoint" }',
1397
+ 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
+ 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
+ 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
+ } : {
1401
+ usage: "Search earlier conversation, don't browse it. Pass returned IDs unchanged",
1402
+ 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
+ }
1404
+ };
1405
+ }
1406
+ function validateNotesArguments(args) {
1407
+ validateFields("notes", args, args.action === undefined ? [] : notesFields[args.action]);
1408
+ if (args.action === "read" || args.action === "append" || args.action === "write")
1409
+ requiredString(args.path, `notes ${args.action} requires path`);
1410
+ if (args.action === "search")
1411
+ requiredString(args.query, "notes search requires query");
1412
+ if (args.action === "append" || args.action === "write")
1413
+ requiredString(args.text, `notes ${args.action} requires text`, true);
1414
+ }
1415
+ function validateHistoryArguments(args) {
1416
+ validateFields("history", args, args.action === undefined ? [] : historyFields[args.action]);
1417
+ if (args.action === "read") {
1418
+ const hint = " as a string. Copy window_id and item_id from the same search or list result";
1419
+ requiredString(args.window_id, `history read requires window_id${hint}`);
1420
+ requiredString(args.item_id, `history read requires item_id${hint}`);
1421
+ }
1422
+ if (args.action === "search")
1423
+ requiredString(args.query, "history search requires query");
1424
+ }
1425
+ function validateFields(namespace, args, fields) {
1426
+ if (!fields || args.action === undefined)
1427
+ throw new Error(`${namespace} requires a supported action`);
1428
+ const unexpected = Object.keys(args).find((key) => key !== "action" && key !== "target" && key !== "agent_name" && !fields.includes(key));
1429
+ if (unexpected)
1430
+ throw new Error(`${namespace} ${args.action} does not accept ${unexpected}`);
1431
+ }
1432
+ function targetConversationId(value, caller) {
1433
+ if (value === undefined)
1434
+ return caller;
1435
+ if (!/^[1-9][0-9]*$/.test(value) || !Number.isSafeInteger(Number(value)))
1436
+ throw new Error("target must be a positive safe-integer Durable conversation ID");
1437
+ return Number(value);
1438
+ }
1439
+ function requiredString(value, message, allowEmpty = false) {
1440
+ if (typeof value !== "string" || !allowEmpty && value === "")
1441
+ throw new Error(message);
1442
+ return value;
1443
+ }
1444
+ function boundedInteger(value, fallback, maximum, minimum = 1) {
1445
+ return typeof value === "number" && Number.isInteger(value) ? Math.max(minimum, Math.min(value, maximum)) : fallback;
1446
+ }
1447
+
1448
+ // packages/context/src/history-items.ts
1449
+ function historyItem(entry, windowId) {
1450
+ const first = entry.model?.[0];
1451
+ if (!first)
1452
+ return;
1453
+ const tool = toolIdentity(first);
1454
+ return {
1455
+ window_id: windowId,
1456
+ item_id: String(entry.id),
1457
+ role: first.role === "toolResult" ? "tool" : first.role,
1458
+ ...tool,
1459
+ content: (entry.model ?? []).map(renderMessage).join(`
1460
+ `)
1461
+ };
1462
+ }
1463
+ function toolIdentity(message) {
1464
+ if (message.role === "toolResult")
1465
+ return { tool_name: message.toolName };
1466
+ if (message.role !== "assistant")
1467
+ return {};
1468
+ const call = message.content.find((block) => block.type === "toolCall");
1469
+ if (!call || call.type !== "toolCall")
1470
+ return {};
1471
+ return {
1472
+ tool_name: call.name,
1473
+ ...call.namespace ? { tool_namespace: call.namespace } : {}
1474
+ };
1475
+ }
1476
+ function renderMessage(message) {
1477
+ if (message.role === "system")
1478
+ return JSON.stringify(withoutBinary(message));
1479
+ if (typeof message.content === "string")
1480
+ return message.content;
1481
+ return message.content.map((block) => {
1482
+ switch (block.type) {
1483
+ case "text":
1484
+ return block.text;
1485
+ case "thinking":
1486
+ return block.thinking;
1487
+ case "image":
1488
+ return `[image ${block.mimeType || "attachment"}]`;
1489
+ case "toolCall":
1490
+ return JSON.stringify({
1491
+ tool: block.name,
1492
+ arguments: withoutBinary(block.arguments)
1493
+ });
1494
+ }
1495
+ }).join(`
1496
+ `);
1497
+ }
1498
+ function withoutBinary(value) {
1499
+ if (Array.isArray(value))
1500
+ return value.map(withoutBinary);
1501
+ if (!value || typeof value !== "object")
1502
+ return value;
1503
+ const result = {};
1504
+ const fields = Object.entries(value);
1505
+ const image = fields.some(([key, item]) => key === "type" && item === "image" || (key === "mimeType" || key === "mime_type") && typeof item === "string" && item.startsWith("image/"));
1506
+ for (const [key, item] of fields) {
1507
+ if (image && (key === "data" || key === "url") || /^(?:base64|b64_json|image_base64)$/i.test(key)) {
1508
+ result[key] = "[binary omitted]";
1509
+ } else if (typeof item === "string" && /^data:[^,]*;base64,/.test(item)) {
1510
+ result[key] = "[binary omitted]";
1511
+ } else
1512
+ result[key] = withoutBinary(item);
1513
+ }
1514
+ return result;
1515
+ }
1516
+ function matchesHistoryItem(item, args) {
1517
+ return (!args.window_id || item.window_id === args.window_id) && (!args.role || item.role === args.role) && (!args.tool_name || item.tool_name === args.tool_name) && (!args.tool_namespace || item.tool_namespace === args.tool_namespace) && (args.action !== "search" || item.content.includes(args.query ?? ""));
1518
+ }
1519
+ function itemIdentity(item) {
1520
+ return {
1521
+ window_id: item.window_id,
1522
+ item_id: item.item_id,
1523
+ role: item.role,
1524
+ ...item.tool_name ? { tool_name: item.tool_name } : {},
1525
+ ...item.tool_namespace ? { tool_namespace: item.tool_namespace } : {}
1526
+ };
1527
+ }
1528
+ function previewHistoryItem(item, maxChars) {
1529
+ return {
1530
+ ...itemIdentity(item),
1531
+ truncated_content: contextTextSlice(item.content, 0, maxChars),
1532
+ content_chars: item.content.length
1533
+ };
1534
+ }
1535
+ function boundedPreviews(items) {
1536
+ const result = [];
1537
+ let size = 0;
1538
+ for (const preview of items) {
1539
+ const previewSize = JSON.stringify(preview).length;
1540
+ if (result.length > 0 && size + previewSize > 8000)
1541
+ break;
1542
+ result.push(preview);
1543
+ size += previewSize;
1544
+ }
1545
+ return result;
1546
+ }
1547
+ function rankedHistoryText(entry) {
1548
+ if (!UserEntry2.is(entry) && !AssistantEntry.is(entry))
1549
+ return "";
1550
+ return (entry.model ?? []).flatMap((message) => {
1551
+ if (message.role !== "user" && message.role !== "assistant")
1552
+ return [];
1553
+ if (typeof message.content === "string")
1554
+ return [message.content];
1555
+ return message.content.flatMap((block) => block.type === "text" ? [block.text] : []);
1556
+ }).join(`
1557
+ `);
1558
+ }
1559
+
1560
+ // packages/context/src/remote.ts
1561
+ async function resolveContextTarget(remote, args, caller, context) {
1562
+ context.abortSignal?.throwIfAborted();
1563
+ if (!remote) {
1564
+ if (args.agent_name != null)
1565
+ throw new Error("Agent names require a host-configured remote Context catalogue");
1566
+ return { target: targetConversationId(args.target, caller) };
1567
+ }
1568
+ if (args.target !== undefined && args.agent_name != null)
1569
+ throw new Error("Supply target or agent_name, not both");
1570
+ const catalog = await readRemoteCatalog(remote, caller, context);
1571
+ if (args.target !== undefined) {
1572
+ const target = targetConversationId(args.target, caller);
1573
+ if (!catalog.agents.some((agent) => agent.conversationId === target))
1574
+ throw new Error("Target is not in the caller's remote Context family");
1575
+ return {
1576
+ target,
1577
+ familyTargets: catalog.agents.map((agent) => agent.conversationId)
1578
+ };
1579
+ }
1580
+ const target = catalog.agents.find((agent) => agent.agentName === (args.agent_name || catalog.currentAgentName))?.conversationId;
1581
+ if (target === undefined)
1582
+ throw new Error("Agent is not in the caller's remote Context family");
1583
+ return {
1584
+ target,
1585
+ familyTargets: catalog.agents.map((agent) => agent.conversationId)
1586
+ };
1587
+ }
1588
+ async function readRemoteCatalog(remote, caller, context) {
1589
+ const catalog = await remote.catalog(caller, context);
1590
+ context.abortSignal?.throwIfAborted();
1591
+ if (!catalog || typeof catalog.familyId !== "string" || !catalog.familyId || typeof catalog.currentAgentName !== "string" || !catalog.currentAgentName || !Array.isArray(catalog.agents))
1592
+ throw new Error("Remote Context catalogue is invalid");
1593
+ const names = new Map;
1594
+ for (const agent of catalog.agents) {
1595
+ if (!agent || typeof agent.agentName !== "string" || !agent.agentName || !Number.isSafeInteger(agent.conversationId) || agent.conversationId <= 0 || names.has(agent.agentName))
1596
+ throw new Error("Remote Context catalogue contains an invalid or duplicate agent");
1597
+ names.set(agent.agentName, agent.conversationId);
1598
+ }
1599
+ if (names.get(catalog.currentAgentName) !== caller)
1600
+ throw new Error("Remote Context catalogue does not bind the caller identity");
1601
+ return catalog;
1602
+ }
1603
+ async function remoteContextHelp(remote, caller, storage, context) {
1604
+ if (!remote)
1605
+ return {};
1606
+ const catalog = await readRemoteCatalog(remote, caller, context);
1607
+ const agents = [];
1608
+ for (const agent of catalog.agents) {
1609
+ context.abortSignal?.throwIfAborted();
1610
+ if (agent.conversationId === caller || await canReadContextTarget(storage, caller, agent.conversationId, context))
1611
+ agents.push({
1612
+ agent_name: agent.agentName,
1613
+ target: String(agent.conversationId)
1614
+ });
1615
+ }
1616
+ return {
1617
+ remote: {
1618
+ family_id: catalog.familyId,
1619
+ current_agent_name: catalog.currentAgentName,
1620
+ agents
1621
+ },
1622
+ agent_name: "Select an authorised agent from remote.agents; defaults to current_agent_name; write own"
1623
+ };
1624
+ }
1625
+
1626
+ // packages/context/src/history.ts
1627
+ var refreshFailures = new WeakMap;
1628
+ function createHistoryTool(options) {
1629
+ const tool = defineTool({
1630
+ name: "history",
1631
+ description: "Search earlier conversation",
1632
+ parameters: historyParameters,
1633
+ structuredOutputSchema: Type2.Object({}, { additionalProperties: true }),
1634
+ prepareArguments: prepareHistoryArguments,
1635
+ replay: "safe",
1636
+ outputLimits: contextOutputLimits,
1637
+ async execute(args = {}, api, context) {
1638
+ const rankedEnabled = options.rankedHistory !== undefined && (options.rankedHistory.enabled?.(api.conversationId) ?? true);
1639
+ let help = contextToolHelp("history", args, rankedEnabled);
1640
+ if (help)
1641
+ help = {
1642
+ ...help,
1643
+ ...await remoteContextHelp(options.remote, api.conversationId, options.storage(), context)
1644
+ };
1645
+ if (help) {
1646
+ return contextToolResult(help);
1647
+ }
1648
+ validateHistoryArguments(args);
1649
+ context.abortSignal?.throwIfAborted();
1650
+ const { target, familyTargets } = await resolveContextTarget(options.remote, args, api.conversationId, context);
1651
+ if (target !== api.conversationId && !await canReadContextTarget(options.storage(), api.conversationId, target, context))
1652
+ throw new Error("This conversation's context is not visible here");
1653
+ const conversation = await options.conversation(target, context);
1654
+ if (conversation.id !== target)
1655
+ throw new Error("History reader is bound to a different conversation");
1656
+ const activeWindowFor = async (id) => {
1657
+ const state = await api.snapshot(WindowState, id, context);
1658
+ if (state?.window)
1659
+ return state.window.id;
1660
+ if (options.archiveHistory) {
1661
+ const reader = id === target ? conversation : await options.conversation(id, context);
1662
+ let cursor;
1663
+ do {
1664
+ context.abortSignal?.throwIfAborted();
1665
+ const page = await reader.entries({}, 64, cursor, context);
1666
+ const boundary = page.items.find((entry) => WindowEntry.is(entry));
1667
+ if (boundary && WindowEntry.is(boundary))
1668
+ return boundary.data.id;
1669
+ cursor = page.next;
1670
+ } while (cursor !== undefined);
1671
+ }
1672
+ return `conversation:${id}`;
1673
+ };
1674
+ const activeWindow = await activeWindowFor(target);
1675
+ const activeIds = rankedEnabled ? new Set((await conversation.context(context)).entries.map((entry) => entry.id)) : new Set;
1676
+ const result = await readHistory(() => historyEntries({
1677
+ conversation,
1678
+ activeWindow,
1679
+ caller: api.conversationId,
1680
+ storage: options.storage(),
1681
+ reader: options.conversation,
1682
+ activeWindowFor,
1683
+ familyTargets,
1684
+ windowId: args.window_id,
1685
+ archive: options.archiveHistory === true,
1686
+ context
1687
+ }), activeWindow, args, options.archiveHistory === true, rankedEnabled && target === api.conversationId && !args.agent_name ? options.rankedHistory : undefined, context.abortSignal, activeIds, String(target));
1688
+ return contextToolResult(result);
1689
+ }
1690
+ });
1691
+ return { ...tool, executionHints: { discovery: "help" } };
1692
+ }
1693
+ async function readHistory(entries, activeWindow, args, archive, ranked, signal, activeIds = new Set, scope = "") {
1694
+ if (args.action === "list_windows") {
1695
+ const limit = boundedInteger(args.limit, 20, 100, 0);
1696
+ if (limit === 0)
1697
+ return { windows: [], truncated: true };
1698
+ const counts = new Map([[activeWindow, 0]]);
1699
+ const newest = new Map;
1700
+ for await (const { entry, windowId, boundary } of entries()) {
1701
+ if (archive && (!newest.has(windowId) || entry.id > (newest.get(windowId) ?? 0)))
1702
+ newest.set(windowId, entry.id);
1703
+ if (!counts.has(windowId)) {
1704
+ counts.set(windowId, 0);
1705
+ if (!archive && counts.size > limit && args.recent_first)
1706
+ break;
1707
+ if (!archive && counts.size > limit + 1) {
1708
+ const newest = counts.keys().next().value;
1709
+ if (newest !== undefined)
1710
+ counts.delete(newest);
1711
+ }
1712
+ }
1713
+ if (!boundary && entry.model?.length)
1714
+ counts.set(windowId, (counts.get(windowId) ?? 0) + 1);
1715
+ }
1716
+ const windows = [...counts].map(([window_id, item_count]) => ({
1717
+ window_id,
1718
+ item_count
1719
+ }));
1720
+ if (archive)
1721
+ windows.sort((left, right) => ((newest.get(left.window_id) ?? 0) - (newest.get(right.window_id) ?? 0)) * (args.recent_first ? -1 : 1));
1722
+ else if (!args.recent_first)
1723
+ windows.reverse();
1724
+ return {
1725
+ windows: windows.slice(0, limit),
1726
+ truncated: windows.length > limit
1727
+ };
1728
+ }
1729
+ if (args.action === "read")
1730
+ return readItem(entries, args);
1731
+ if (args.action === "search" && ranked && (!args.role || args.role === "user" || args.role === "assistant") && !args.tool_name && !args.tool_namespace && args.window_id !== activeWindow && !args.window_id?.startsWith("archive:")) {
1732
+ return readRankedHistory(entries, args, ranked, activeIds, scope, signal);
1733
+ }
1734
+ const limit = boundedInteger(args.limit, 10, 25, 0);
1735
+ const maxChars = boundedInteger(args.max_chars_per_item, 1000, 1000, 0);
1736
+ const items = [];
1737
+ const summaries = [];
1738
+ let matched = 0;
1739
+ for await (const { entry, windowId, boundary, summary } of entries()) {
1740
+ if (boundary || args.window_id && windowId !== args.window_id)
1741
+ continue;
1742
+ const item = historyItem(entry, windowId);
1743
+ if (item && summary)
1744
+ item.role = "assistant";
1745
+ if (!item || !matchesHistoryItem(item, args))
1746
+ continue;
1747
+ matched++;
1748
+ const selected = archive && args.action === "search" && summary ? summaries : items;
1749
+ selected.push({
1750
+ id: entry.id,
1751
+ preview: previewHistoryItem(item, maxChars)
1752
+ });
1753
+ selected.sort((left, right) => (left.id - right.id) * (args.recent_first ? -1 : 1));
1754
+ if (items.length > limit && args.recent_first && !archive)
1755
+ break;
1756
+ if (selected.length > limit)
1757
+ selected.pop();
1758
+ }
1759
+ const previews = boundedPreviews([...summaries, ...items].slice(0, limit).map((item) => item.preview));
1760
+ return {
1761
+ truncated: matched > previews.length,
1762
+ ...args.action === "search" ? { search_mode: "literal" } : {},
1763
+ items: previews
1764
+ };
1765
+ }
1766
+ async function readItem(entries, args) {
1767
+ let candidate;
1768
+ let candidateSummary = false;
1769
+ for await (const { entry, windowId, boundary, summary } of entries()) {
1770
+ if (boundary || windowId !== args.window_id)
1771
+ continue;
1772
+ const id = String(entry.id);
1773
+ if (id !== args.item_id)
1774
+ continue;
1775
+ if (entry.model?.length) {
1776
+ candidate = entry;
1777
+ candidateSummary = summary;
1778
+ }
1779
+ }
1780
+ const item = candidate ? historyItem(candidate, args.window_id ?? "") : undefined;
1781
+ if (!item)
1782
+ return { item: null };
1783
+ if (candidateSummary)
1784
+ item.role = "assistant";
1785
+ const offset = boundedInteger(args.offset_chars, 0, item.content.length, 0);
1786
+ const limit = boundedInteger(args.limit_chars, 8000, 8000, 0);
1787
+ const content = contextTextSlice(item.content, offset, limit);
1788
+ const nextOffset = offset + content.length;
1789
+ return {
1790
+ item: {
1791
+ ...itemIdentity(item),
1792
+ content,
1793
+ total_chars: item.content.length,
1794
+ ...nextOffset < item.content.length ? { next_offset_chars: nextOffset } : {}
1795
+ }
1796
+ };
1797
+ }
1798
+ async function readRankedHistory(entries, args, ranked, activeIds, scope, signal) {
1799
+ signal?.throwIfAborted();
1800
+ const previousFailure = refreshFailures.get(ranked.ranker)?.get(scope);
1801
+ if (previousFailure) {
1802
+ refreshFailures.get(ranked.ranker)?.delete(scope);
1803
+ throw new Error("Earlier history indexing failed. Retry this search or disable ranked history; list and read remain available.", { cause: previousFailure });
1804
+ }
1805
+ async function* index() {
1806
+ for await (const { entry, windowId, boundary, summary } of entries()) {
1807
+ if (boundary || summary || args.window_id && windowId !== args.window_id || activeIds.has(entry.id) || windowId.startsWith("archive:"))
1808
+ continue;
1809
+ if (args.role && entry.model?.[0]?.role !== args.role)
1810
+ continue;
1811
+ const content = rankedHistoryText(entry);
1812
+ if (content)
1813
+ yield { id: String(entry.id), content };
1814
+ }
1815
+ }
1816
+ const limit = boundedInteger(args.limit, 10, 25, 0);
1817
+ const ids = await ranked.ranker.search({
1818
+ scope,
1819
+ items: index(),
1820
+ query: args.query ?? "",
1821
+ limit: limit + 1,
1822
+ recentFirst: args.recent_first === true,
1823
+ signal
1824
+ });
1825
+ const wanted = new Set(ids.slice(0, limit));
1826
+ const canonical = new Map;
1827
+ if (wanted.size)
1828
+ for await (const { entry, windowId, boundary, summary } of entries()) {
1829
+ if (!wanted.has(String(entry.id)) || boundary || summary || activeIds.has(entry.id) || windowId.startsWith("archive:") || args.window_id && windowId !== args.window_id)
1830
+ continue;
1831
+ const item = historyItem(entry, windowId);
1832
+ if (!item || args.role && item.role !== args.role || !rankedHistoryText(entry))
1833
+ continue;
1834
+ canonical.set(item.item_id, item);
1835
+ if (canonical.size === wanted.size)
1836
+ break;
1837
+ }
1838
+ const maxChars = boundedInteger(args.max_chars_per_item, 1000, 1000, 0);
1839
+ const previews = boundedPreviews(ids.slice(0, limit).map((id) => {
1840
+ const item = canonical.get(id);
1841
+ if (!item)
1842
+ throw new Error("History ranker returned an out-of-scope item");
1843
+ return previewHistoryItem(item, maxChars);
1844
+ }));
1845
+ return {
1846
+ items: previews,
1847
+ truncated: ids.length > previews.length,
1848
+ search_mode: "ranked_earlier_context"
1849
+ };
1850
+ }
1851
+ async function refreshRankedHistory(conversation, ranked, context) {
1852
+ if (!(ranked.enabled?.(conversation.id) ?? true))
1853
+ return;
1854
+ try {
1855
+ const active = new Set((await conversation.context(context)).entries.map((entry) => entry.id));
1856
+ async function* items() {
1857
+ let cursor;
1858
+ do {
1859
+ context.abortSignal?.throwIfAborted();
1860
+ const page = await conversation.entries({}, 64, cursor, context);
1861
+ for (const entry of page.items) {
1862
+ context.abortSignal?.throwIfAborted();
1863
+ if (active.has(entry.id) || CompactionEntry2.is(entry))
1864
+ continue;
1865
+ const content = rankedHistoryText(entry);
1866
+ if (content)
1867
+ yield { id: String(entry.id), content };
1868
+ }
1869
+ cursor = page.next;
1870
+ } while (cursor !== undefined);
1871
+ }
1872
+ await ranked.ranker.refresh({
1873
+ scope: String(conversation.id),
1874
+ items: items(),
1875
+ signal: context.abortSignal
1876
+ });
1877
+ } catch (error) {
1878
+ context.abortSignal?.throwIfAborted();
1879
+ let failures = refreshFailures.get(ranked.ranker);
1880
+ if (!failures) {
1881
+ failures = new Map;
1882
+ refreshFailures.set(ranked.ranker, failures);
1883
+ }
1884
+ failures.set(String(conversation.id), error instanceof Error ? error : new Error("History indexing failed", { cause: error }));
1885
+ }
1886
+ }
1887
+
1888
+ // packages/context/src/input-placement.ts
1889
+ async function waitForInputPlacement(host, id, context) {
1890
+ const requestId = `context:input:${id}`;
1891
+ let revision = 0;
1892
+ let closing = false;
1893
+ let wake;
1894
+ const changed = () => {
1895
+ revision++;
1896
+ wake?.();
1897
+ };
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))
1900
+ changed();
1901
+ });
1902
+ const stopClose = host.harness.subscribeClose(() => {
1903
+ closing = true;
1904
+ changed();
1905
+ });
1906
+ try {
1907
+ while (true) {
1908
+ context.abortSignal?.throwIfAborted();
1909
+ if (closing)
1910
+ throw new Error("Context host closed before input placement was observed");
1911
+ const before = revision;
1912
+ const task = await host.harness.getTask(id, context);
1913
+ if (!task || task.kind !== INPUT_TASK)
1914
+ throw new Error("Input task does not belong to Context management");
1915
+ const submission = await host.harness.commit((tx) => tx.submissionByRequest(task.conversationId, requestId), context);
1916
+ if (submission)
1917
+ return { status: "submitted", submissionId: submission.id };
1918
+ if (task.state.status === "terminal" || task.state.status === "completing") {
1919
+ const outcome = task.state.outcome;
1920
+ if (outcome.status === "aborted")
1921
+ return {
1922
+ status: "aborted",
1923
+ ...outcome.reason ? { reason: outcome.reason } : {}
1924
+ };
1925
+ return {
1926
+ status: "failed",
1927
+ message: outcome.status === "failed" || outcome.status === "faulted" ? outcome.error.message : outcome.status === "orphaned" ? outcome.reason : "Managed input completed without a native submission receipt"
1928
+ };
1929
+ }
1930
+ if (revision !== before)
1931
+ continue;
1932
+ await new Promise((resolve, reject) => {
1933
+ const signal = context.abortSignal;
1934
+ const abort = () => {
1935
+ wake = undefined;
1936
+ reject(signal?.reason);
1937
+ };
1938
+ wake = () => {
1939
+ signal?.removeEventListener("abort", abort);
1940
+ wake = undefined;
1941
+ resolve();
1942
+ };
1943
+ signal?.addEventListener("abort", abort, { once: true });
1944
+ if (signal?.aborted)
1945
+ abort();
1946
+ else if (revision !== before || closing)
1947
+ wake();
1948
+ });
1949
+ }
1950
+ } finally {
1951
+ unsubscribe();
1952
+ stopClose();
1953
+ }
1954
+ }
1955
+
1956
+ // packages/context/src/notes.ts
1957
+ import {
1958
+ defineTool as defineTool2
1959
+ } from "@earendil-works/pi-durable";
1960
+ import { Type as Type3 } from "typebox";
1961
+
1962
+ // packages/context/src/note-path.ts
1963
+ var NOTES_ROOT = "/notes";
1964
+ function normalizeFilePath(value) {
1965
+ const input = requiredString(value, "Note file path is required");
1966
+ const path = normalize(input, false);
1967
+ if (!path.startsWith(`${NOTES_ROOT}/`))
1968
+ throw new Error("Absolute note paths must use /notes/<path>");
1969
+ return path;
1970
+ }
1971
+ function normalizePrefix(value) {
1972
+ if (value === undefined || value === null || value === "")
1973
+ return `${NOTES_ROOT}/`;
1974
+ if (typeof value !== "string")
1975
+ throw new Error("Note prefix must be a string");
1976
+ const path = normalize(value, true);
1977
+ if (path === NOTES_ROOT)
1978
+ return `${path}/`;
1979
+ if (!path.startsWith(`${NOTES_ROOT}/`))
1980
+ throw new Error("Absolute note prefixes must use /notes[/path]");
1981
+ return path;
1982
+ }
1983
+ function normalize(input, prefix) {
1984
+ const path = input.startsWith("/") ? input : `${NOTES_ROOT}/${input}`;
1985
+ const components = path.slice(1).split("/");
1986
+ if (components.some((part) => !part || part === "." || part === ".."))
1987
+ throw new Error(`Note ${prefix ? "prefixes" : "paths"} cannot contain empty, . or .. components`);
1988
+ return `/${components.join("/")}`;
1989
+ }
1990
+
1991
+ // packages/context/src/notes.ts
1992
+ function createNotesTool(options) {
1993
+ const tool = defineTool2({
1994
+ name: "notes",
1995
+ description: "Persistent notes for handing off task state between context windows",
1996
+ parameters: notesParameters,
1997
+ structuredOutputSchema: Type3.Object({}, { additionalProperties: true }),
1998
+ prepareArguments: prepareNotesArguments,
1999
+ replay: "safe",
2000
+ outputLimits: contextOutputLimits,
2001
+ async execute(args = {}, api, context) {
2002
+ const writing = args.action === "append" || args.action === "write";
2003
+ if (writing)
2004
+ await api.commit((tx) => beginNoteWrite(tx, api.conversationId, api.taskId), context);
2005
+ let help = contextToolHelp("notes", args);
2006
+ if (help)
2007
+ help = {
2008
+ ...help,
2009
+ ...await remoteContextHelp(options.remote, api.conversationId, options.storage(), context)
2010
+ };
2011
+ if (help) {
2012
+ return contextToolResult(help);
2013
+ }
2014
+ validateNotesArguments(args);
2015
+ context.abortSignal?.throwIfAborted();
2016
+ const { target } = await resolveContextTarget(options.remote, args, api.conversationId, context);
2017
+ if (writing && target !== api.conversationId)
2018
+ throw new Error("Notes writes may only target the caller conversation");
2019
+ if (!writing && target !== api.conversationId && !await canReadContextTarget(options.storage(), api.conversationId, target, context))
2020
+ throw new Error("This conversation's context is not visible here");
2021
+ const hasCatalog = writing || await api.snapshot(NotesState, target, context) !== undefined;
2022
+ const result = await api.commit(async (tx) => {
2023
+ if (!await tx.conversation(target))
2024
+ throw new Error(`Conversation ${target} does not exist`);
2025
+ if (writing) {
2026
+ const file = await mutateNote(tx, {
2027
+ conversationId: api.conversationId,
2028
+ taskId: api.taskId,
2029
+ path: normalizeFilePath(args.path),
2030
+ text: requiredString(args.text, `notes ${args.action} requires text`, true),
2031
+ append: args.action === "append",
2032
+ now: options.now
2033
+ });
2034
+ return contextToolResult({ file: { path: file.path } });
2035
+ }
2036
+ return readNotes(tx, target, args, hasCatalog);
2037
+ }, context).catch((error) => {
2038
+ if (writing && options.remote && context.abortSignal?.aborted)
2039
+ throw new Error("Notes write was interrupted after dispatch; its outcome is uncertain. Read the note before another write", { cause: error });
2040
+ throw error;
2041
+ });
2042
+ return result;
2043
+ }
2044
+ });
2045
+ return { ...tool, executionHints: { discovery: "help" } };
2046
+ }
2047
+ async function readNotes(tx, id, args, hasCatalog) {
2048
+ const state = hasCatalog ? await tx.doc(NotesState, id) : { files: [] };
2049
+ if (args.action === "read") {
2050
+ const path = normalizeFilePath(args.path);
2051
+ const file = state.files.find((file) => file.path === path);
2052
+ if (!file)
2053
+ return contextToolResult({ file: null });
2054
+ const lines = (await readNoteText(tx, id, path)).split(`
2055
+ `);
2056
+ const start = lineIndex(args.start_line, lines.length, 0);
2057
+ const stop = lineIndex(args.stop_line, lines.length, lines.length - 1);
2058
+ const selected = start <= stop ? lines.slice(start, stop + 1).join(`
2059
+ `) : "";
2060
+ const offset = boundedInteger(args.offset_chars, 0, selected.length, 0);
2061
+ const limit = boundedInteger(args.limit_chars, selected.length, selected.length, 0);
2062
+ const content = contextTextSlice(selected, offset, limit);
2063
+ const nextOffset = offset + content.length;
2064
+ const detail = {
2065
+ path: file.path,
2066
+ content,
2067
+ total_chars: selected.length,
2068
+ ...nextOffset < selected.length ? { next_offset_chars: nextOffset } : {},
2069
+ start_line: start + 1,
2070
+ stop_line: Math.max(start, stop) + 1,
2071
+ total_lines: lines.length
2072
+ };
2073
+ return contextToolResult({ file: detail }, { file: { ...noteMetadata(file), ...detail } });
2074
+ }
2075
+ if (args.action === "list") {
2076
+ const prefix = normalizePrefix(args.path);
2077
+ const direction = args.file_order === "descending" ? -1 : 1;
2078
+ const files = state.files.filter((file) => file.path.startsWith(prefix)).sort((left, right) => {
2079
+ const compared = args.file_order_by === "created_at" ? left.createdAt - right.createdAt : args.file_order_by === "updated_at" ? left.updatedAt - right.updatedAt : left.path.localeCompare(right.path);
2080
+ return compared * direction;
2081
+ });
2082
+ const limit = boundedInteger(args.limit, 20, 100);
2083
+ const selected = files.slice(0, limit);
2084
+ const truncated = files.length > limit ? { truncated: true } : {};
2085
+ return contextToolResult({
2086
+ files: selected.map((file) => ({
2087
+ path: file.path,
2088
+ updated_at: new Date(file.updatedAt).toISOString(),
2089
+ ...args.file_order_by === "created_at" ? { created_at: new Date(file.createdAt).toISOString() } : {}
2090
+ })),
2091
+ ...truncated
2092
+ }, { files: selected.map(noteMetadata), ...truncated });
2093
+ }
2094
+ const query = requiredString(args.query, "notes search requires query");
2095
+ const prefix = normalizePrefix(args.path);
2096
+ const fileLimit = boundedInteger(args.limit, 20, 100);
2097
+ const matchLimit = boundedInteger(args.max_matches_per_file, 20, 100);
2098
+ const candidates = state.files.filter((file) => file.path.startsWith(prefix)).sort((left, right) => args.recent_file_first === true ? right.createdAt - left.createdAt : left.path.localeCompare(right.path));
2099
+ const files = [];
2100
+ for (const file of candidates) {
2101
+ const matches = [];
2102
+ const lines = (await readNoteText(tx, id, file.path)).split(`
2103
+ `);
2104
+ for (const [index, line] of lines.entries()) {
2105
+ if (line.includes(query))
2106
+ matches.push({
2107
+ line_number: index + 1,
2108
+ line
2109
+ });
2110
+ if (matches.length > matchLimit)
2111
+ break;
2112
+ }
2113
+ if (!matches.length)
2114
+ continue;
2115
+ if (files.length === fileLimit)
2116
+ return contextToolResult({ files, truncated: true });
2117
+ files.push({
2118
+ path: file.path,
2119
+ matches: matches.slice(0, matchLimit),
2120
+ ...matches.length > matchLimit ? { truncated: true } : {}
2121
+ });
2122
+ }
2123
+ return contextToolResult({ files });
2124
+ }
2125
+ function lineIndex(value, count, fallback) {
2126
+ if (typeof value !== "number" || !Number.isInteger(value) || value === 0)
2127
+ return fallback;
2128
+ const index = value > 0 ? value - 1 : count + value;
2129
+ return Math.max(0, Math.min(index, Math.max(0, count - 1)));
2130
+ }
2131
+
2132
+ // packages/context/src/policy.ts
2133
+ import {
2134
+ CompactionTask,
2135
+ defineDoc as defineDoc6,
2136
+ defineTool as defineTool3,
2137
+ GenerationTask as GenerationTask3,
2138
+ hook,
2139
+ section,
2140
+ ToolTask as ToolTask2
2141
+ } from "@earendil-works/pi-durable";
2142
+ import { Type as Type4 } from "typebox";
2143
+
2144
+ // packages/context/src/model-roles.ts
2145
+ import {
2146
+ AgentDoc
2147
+ } from "@earendil-works/pi-durable";
2148
+ async function readRoles(catalog, id, context) {
2149
+ const roles = catalog ? await catalog(id, context) : [];
2150
+ const ids = new Set;
2151
+ if (!Array.isArray(roles))
2152
+ throw new Error("Model roles configuration must contain a roles array");
2153
+ for (const role of roles) {
2154
+ if (!role || typeof role.id !== "string" || !/^[a-z][a-z0-9-]*$/.test(role.id) || typeof role.description !== "string" || !role.description.trim() || typeof role.provider !== "string" || !role.provider.trim() || typeof role.model !== "string" || !role.model.trim() || !["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(role.reasoning) || ids.has(role.id))
2155
+ throw new Error("Invalid or duplicate model role; ask the user to check model role configuration");
2156
+ ids.add(role.id);
2157
+ }
2158
+ return roles.map(({ id, description, provider, model, reasoning }) => ({
2159
+ id,
2160
+ description,
2161
+ provider,
2162
+ model,
2163
+ reasoning
2164
+ }));
2165
+ }
2166
+ async function renderModelRoles(catalog, id, context) {
2167
+ let roles;
2168
+ try {
2169
+ roles = await readRoles(catalog, id, context);
2170
+ } catch {
2171
+ context.abortSignal?.throwIfAborted();
2172
+ return "Model roles are unavailable. Ask the user to check their configuration. Call new_context without role to keep the current model.";
2173
+ }
2174
+ if (!roles.length)
2175
+ return "No model roles are available. Call new_context without role.";
2176
+ 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.',
2178
+ ...roles.map((role) => `- ${role.id}: ${role.description}`)
2179
+ ].join(`
2180
+ `);
2181
+ }
2182
+ async function prepareRole(catalog, id, conversationId, source, models, context) {
2183
+ const role = (await readRoles(catalog, conversationId, context)).find((candidate) => candidate.id === id);
2184
+ if (!role)
2185
+ throw new Error(`Unknown role ${JSON.stringify(id)}. Use a configured role or omit role to keep the current model.`);
2186
+ const model = models.getModel(role.provider, role.model);
2187
+ if (!model)
2188
+ throw new Error(`Role ${id} is unavailable. Continue here and ask the user to check its model configuration.`);
2189
+ if (!await models.getAuth(model, {
2190
+ ...context.abortSignal ? { signal: context.abortSignal } : {}
2191
+ }))
2192
+ throw new Error(`Role ${id} has no usable provider access. Continue here and ask the user to check its login or API configuration.`);
2193
+ context.abortSignal?.throwIfAborted();
2194
+ return {
2195
+ id,
2196
+ model: { provider: role.provider, modelId: role.model },
2197
+ thinkingLevel: role.reasoning,
2198
+ source: {
2199
+ model: source.model ?? null,
2200
+ thinkingLevel: source.thinkingLevel
2201
+ }
2202
+ };
2203
+ }
2204
+ async function roleSourceMatches(tx, id, role) {
2205
+ const current = await tx.doc(AgentDoc, id);
2206
+ return current.model?.provider === role.source.model?.provider && current.model?.modelId === role.source.model?.modelId && (current.thinkingLevel ?? "off") === role.source.thinkingLevel;
2207
+ }
2208
+
2209
+ // packages/context/src/usage.ts
2210
+ import { estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
2211
+ async function contextUsage(conversation, models, context, answer) {
2212
+ const [agent, view] = await Promise.all([
2213
+ conversation.agent(context),
2214
+ conversation.context(context)
2215
+ ]);
2216
+ const ref = agent.model;
2217
+ const model = ref && models.getModel(ref.provider, ref.modelId);
2218
+ const contextWindow = model && Number.isFinite(model.contextWindow) && model.contextWindow > 0 ? model.contextWindow : null;
2219
+ const messages = answer ? [...view.messages, answer] : view.messages;
2220
+ let baseline;
2221
+ for (const [index, entry] of view.entries.entries()) {
2222
+ if (view.head && entry.id <= view.head.id)
2223
+ continue;
2224
+ for (const message of view.contributions[index] ?? []) {
2225
+ if (message.role === "assistant" && reportedTokens(message) !== null)
2226
+ baseline = message;
2227
+ }
2228
+ }
2229
+ if (answer && reportedTokens(answer) !== null)
2230
+ baseline = answer;
2231
+ const baselineIndex = baseline ? messages.lastIndexOf(baseline) : -1;
2232
+ const usageTokens = baseline && baselineIndex >= 0 ? reportedTokens(baseline) : null;
2233
+ const trailingTokens = usageTokens === null ? null : messages.slice(baselineIndex + 1).reduce((tokens, message) => tokens + estimateMessageTokens(message), 0);
2234
+ const usedTokens = usageTokens !== null && trailingTokens !== null ? usageTokens + trailingTokens : null;
2235
+ const known = contextWindow !== null && usedTokens !== null;
2236
+ return {
2237
+ known,
2238
+ reason: known ? null : contextWindow === null ? "The active model has no known context window" : "No applicable assistant usage in the active context",
2239
+ model: ref ? { provider: ref.provider, id: ref.modelId } : null,
2240
+ usageModel: baseline?.role === "assistant" ? { provider: baseline.provider, id: baseline.model } : null,
2241
+ contextWindow,
2242
+ usageTokens,
2243
+ trailingTokens,
2244
+ usedTokens,
2245
+ remainingTokens: known ? Math.max(0, contextWindow - usedTokens) : null,
2246
+ percentage: known ? usedTokens / contextWindow * 100 : null,
2247
+ estimated: trailingTokens !== null && trailingTokens > 0,
2248
+ uncertainty: usageTokens !== null ? "Provider usage plus an estimated unsent tail; not an exact remaining-token budget" : "Usage is unknown; no character-only estimate is presented as measured usage"
2249
+ };
2250
+ }
2251
+ function reportedTokens(message) {
2252
+ if (["error", "aborted", "deferred", "pending"].includes(message.stopReason))
2253
+ return null;
2254
+ const counts = [
2255
+ message.usage.input,
2256
+ message.usage.output,
2257
+ message.usage.cacheRead,
2258
+ message.usage.cacheWrite
2259
+ ];
2260
+ if (!counts.every((count) => Number.isFinite(count) && count >= 0))
2261
+ return null;
2262
+ const tokens = counts.reduce((sum, count) => sum + count, 0);
2263
+ return tokens > 0 ? tokens : null;
2264
+ }
2265
+
2266
+ // packages/context/src/policy.ts
2267
+ function checkpointGuidance(newContextRequests) {
2268
+ 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
+ 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."
2273
+ ].join(`
2274
+
2275
+ `);
2276
+ }
2277
+ var YieldAdvisory = defineDoc6({
2278
+ kind: "howaboua.context.yield-advisory",
2279
+ version: 1,
2280
+ scope: "task",
2281
+ checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
2282
+ initial: () => ({})
2283
+ });
2284
+ function createContextPolicy(options) {
2285
+ async function conversation(id, context) {
2286
+ const result = await options.host().harness.conversation(id, context);
2287
+ if (!result)
2288
+ throw new Error(`Context conversation ${id} is missing`);
2289
+ return result;
2290
+ }
2291
+ const sections = [
2292
+ section("context", () => checkpointGuidance(options.newContextRequests)),
2293
+ ...options.newContextRequests === "off" || !options.modelRoles ? [] : [
2294
+ section("context-roles", (input, context) => renderModelRoles(options.modelRoles, input.conversationId, context))
2295
+ ],
2296
+ section("context-state", async (input, context) => {
2297
+ const [state, hints] = await Promise.all([
2298
+ input.read.snapshot(WindowState, input.conversationId, context),
2299
+ renderNotesThreadHint(input.read, input.conversationId, context)
2300
+ ]);
2301
+ const window = state?.window;
2302
+ return [
2303
+ `Current conversation ID: ${input.conversationId}. notes and history accept target with another conversation ID in this storage only when its Context visibility group matches yours. Write only your own notes.`,
2304
+ window && `Current context window UUID: ${window.id}`,
2305
+ window?.previous && `Previous context window UUID: ${window.previous}`,
2306
+ options.archiveHistory && window && await renderArchiveHistoryHint(await conversation(input.conversationId, context), window.id, context),
2307
+ hints
2308
+ ].filter(Boolean).join(`
2309
+ `);
2310
+ })
2311
+ ];
2312
+ const remainingTool = defineTool3({
2313
+ name: "get_context_remaining",
2314
+ description: "Active model context budget from assistant usage, with tail uncertainty",
2315
+ parameters: Type4.Object({}, { additionalProperties: false }),
2316
+ replay: "safe",
2317
+ async execute(_args, api, context) {
2318
+ await options.ensureWindow(api.conversationId, context);
2319
+ const current = await conversation(api.conversationId, context);
2320
+ const usage = await contextUsage(current, options.models, context);
2321
+ const state = await api.snapshot(WindowState, api.conversationId, context);
2322
+ const result = { ...usage, windowId: state?.window?.id ?? null };
2323
+ return {
2324
+ output: [{ type: "text", text: JSON.stringify(result) }],
2325
+ details: result
2326
+ };
2327
+ }
2328
+ });
2329
+ async function remind(api, context, answer) {
2330
+ if (options.newContextRequests === "off")
2331
+ return;
2332
+ if (answer) {
2333
+ const receipt = await api.snapshot(YieldAdvisory, api.taskId, context);
2334
+ if (receipt?.text)
2335
+ return receipt.text;
2336
+ }
2337
+ const current = await conversation(api.conversationId, context);
2338
+ const usage = await contextUsage(current, options.models, context, answer);
2339
+ const level = usage.percentage === null || usage.percentage < 85 ? 0 : usage.percentage >= 90 ? 90 : 85;
2340
+ const boundary = options.taskBoundaryReminderTokens > 0 && usage.contextWindow !== null && usage.contextWindow > 272000 && usage.usedTokens !== null && usage.usedTokens >= options.taskBoundaryReminderTokens;
2341
+ if (level === 0 && !boundary)
2342
+ return;
2343
+ const remaining = Math.max(0, 100 - Math.round(usage.percentage ?? 0));
2344
+ const boundaryText = `Suggested context budget reached; ${remaining}% remains. For a sequence of tasks, finish the current task, save notes and call new_context before the next. Otherwise, continue here.`;
2345
+ const text = `${level === 90 ? "Urgent: " : ""}${remaining}% context remaining${usage.estimated ? " (estimated tail included)" : " (last reported usage)"}. Save the task state in notes, then call new_context ${level === 90 ? "now, before other work" : "before continuing work"}.`;
2346
+ return current.commit(async (tx) => {
2347
+ const receipt = answer ? await tx.doc(YieldAdvisory, api.taskId) : undefined;
2348
+ if (receipt?.text)
2349
+ return receipt.text;
2350
+ const fresh = await notesAreFresh(tx, api.conversationId);
2351
+ const state = await tx.doc(WindowState, api.conversationId);
2352
+ if (!state.window)
2353
+ return;
2354
+ const threshold = level > 0 && !fresh && state.reminded < level;
2355
+ if (!threshold && (!boundary || state.taskBoundaryReminded === state.window.id))
2356
+ return;
2357
+ const advisory = threshold ? text : boundaryText;
2358
+ await tx.appendEntry(api.conversationId, {
2359
+ kind: "howaboua.context.advisory",
2360
+ ...answer ? {} : {
2361
+ model: [
2362
+ {
2363
+ role: "user",
2364
+ content: advisory,
2365
+ timestamp: options.now()
2366
+ }
2367
+ ]
2368
+ },
2369
+ data: { windowId: state.window.id, level, observedAt: options.now() }
2370
+ });
2371
+ if (threshold)
2372
+ state.reminded = level;
2373
+ else
2374
+ state.taskBoundaryReminded = state.window.id;
2375
+ if (receipt)
2376
+ receipt.text = advisory;
2377
+ return advisory;
2378
+ }, context);
2379
+ }
2380
+ const hooks = [
2381
+ hook(GenerationTask3, {
2382
+ async beforeRequest(_request, api, context) {
2383
+ await options.ensureWindow(api.conversationId, context);
2384
+ if (options.rankedHistory)
2385
+ await refreshRankedHistory(await conversation(api.conversationId, context), options.rankedHistory, context);
2386
+ },
2387
+ async afterTools(_assistant, _results, api, context) {
2388
+ await remind(api, context);
2389
+ },
2390
+ async onYield(answer, api, context) {
2391
+ if (options.rankedHistory)
2392
+ await refreshRankedHistory(await conversation(api.conversationId, context), options.rankedHistory, context);
2393
+ const text = await remind(api, context, answer);
2394
+ return text ? { continue: text } : undefined;
2395
+ }
2396
+ }),
2397
+ hook(ToolTask2, {
2398
+ async beforeTool(_call, api, context) {
2399
+ await options.ensureWindow(api.conversationId, context);
2400
+ },
2401
+ async afterTool(call, result, api, context) {
2402
+ if (call.name === "notes" && result.isError && isNoteWrite(call.arguments))
2403
+ await (await conversation(api.conversationId, context)).commit((tx) => beginNoteWrite(tx, api.conversationId, api.taskId), context);
2404
+ }
2405
+ }),
2406
+ hook(CompactionTask, {
2407
+ async beforeCompact(compaction) {
2408
+ return compaction.reason === "overflow" ? undefined : { decline: true };
2409
+ }
2410
+ })
2411
+ ];
2412
+ return { sections, hooks, remainingTool };
2413
+ }
2414
+
2415
+ // packages/context/src/tool-rollover.ts
2416
+ import {
2417
+ configure,
2418
+ defineDoc as defineDoc7,
2419
+ defineTool as defineTool4,
2420
+ GenerationTask as GenerationTask4,
2421
+ hook as hook2,
2422
+ InboxDoc as InboxDoc2,
2423
+ LiveDoc as LiveDoc4
2424
+ } 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
+ });
2432
+ function createToolRollover(host, now, policy) {
2433
+ const tool = defineTool4({
2434
+ 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,
2438
+ replay: "safe",
2439
+ callers: ["model"],
2440
+ executionMode: "sequential",
2441
+ async execute(args, api, context) {
2442
+ 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;
2447
+ const hasEligibleContextHistory = policy.hasEligibleContextHistory;
2448
+ if (!hasEligibleContextHistory)
2449
+ throw new Error("pi-limits requires hasEligibleContextHistory from the host");
2450
+ if (!prior?.request && !await hasEligibleContextHistory(api.conversationId, context))
2451
+ return {
2452
+ output: [
2453
+ {
2454
+ type: "text",
2455
+ text: JSON.stringify({
2456
+ status: "limit_not_reached",
2457
+ message: "The host reports no eligible history for a new context window. The window is unchanged."
2458
+ })
2459
+ }
2460
+ ]
2461
+ };
2462
+ }
2463
+ const live = await api.snapshot(LiveDoc4, api.conversationId, context);
2464
+ 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);
2466
+ 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");
2470
+ const state = await tx.doc(WindowState, api.conversationId);
2471
+ if (!state.window || state.transition)
2472
+ throw new Error("Context window is missing or a checkpoint is already in progress");
2473
+ if (role && !await roleSourceMatches(tx, api.conversationId, role))
2474
+ 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))
2476
+ return {
2477
+ status: "checkpoint_required",
2478
+ 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
+ };
2480
+ const receipt = await tx.doc(ToolWindow, live.run.taskId);
2481
+ receipt.request ??= {
2482
+ tool: api.taskId,
2483
+ ...role ? { role } : {},
2484
+ window: {
2485
+ id: crypto.randomUUID(),
2486
+ number: state.window.number + 1,
2487
+ startedAt: now(),
2488
+ previous: state.window.id
2489
+ }
2490
+ };
2491
+ return { status: "scheduled", window_id: receipt.request.window.id };
2492
+ }, context);
2493
+ return { output: [{ type: "text", text: JSON.stringify(result) }] };
2494
+ }
2495
+ });
2496
+ const hooks = [
2497
+ hook2(GenerationTask4, {
2498
+ async afterTools(_assistant, _results, api, context) {
2499
+ const pending = await api.snapshot(ToolWindow, api.taskId, context);
2500
+ if (!pending?.request || pending.finished)
2501
+ return;
2502
+ const conv = await conversation(host(), api.conversationId, context);
2503
+ const ready = async (tx) => {
2504
+ const receipt = await tx.doc(ToolWindow, api.taskId);
2505
+ if (!receipt.request || receipt.finished)
2506
+ return false;
2507
+ const live = await tx.doc(LiveDoc4, api.conversationId);
2508
+ const inbox = await tx.doc(InboxDoc2, api.conversationId);
2509
+ const state = await tx.doc(WindowState, api.conversationId);
2510
+ const slot = live.tools?.[0];
2511
+ 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);
2513
+ };
2514
+ const preparation = await prepareRollover(conv, api.taskId, policy.beforeRollover, {
2515
+ conversationId: api.conversationId,
2516
+ windowId: pending.request.window.previous ?? "",
2517
+ nextWindowId: pending.request.window.id,
2518
+ reason: "tool"
2519
+ }, ready, context);
2520
+ await conv.commit(async (tx) => {
2521
+ const receipt = await tx.doc(ToolWindow, api.taskId);
2522
+ if (!receipt.request || receipt.finished)
2523
+ return;
2524
+ const state = await tx.doc(WindowState, api.conversationId);
2525
+ const safe = !preparation.error && await ready(tx) && (preparation.head === undefined || preparation.head === await latestContextEntry(tx, api.conversationId));
2526
+ 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
+ }
2543
+ await tx.appendEntry(api.conversationId, {
2544
+ kind: "howaboua.context.continuation",
2545
+ model: [
2546
+ {
2547
+ role: "system",
2548
+ content: safe ? `Read your saved notes with the notes tool and resume the task.${receipt.request.role ? `
2549
+
2550
+ 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
+ timestamp: now()
2552
+ }
2553
+ ]
2554
+ });
2555
+ }, context);
2556
+ }
2557
+ })
2558
+ ];
2559
+ return {
2560
+ tool: { ...tool, executionHints: { nativeOnly: true } },
2561
+ hooks
2562
+ };
2563
+ }
2564
+
2565
+ // packages/context/src/index.ts
2566
+ function createContextManagement(options) {
2567
+ let binding;
2568
+ if (options.modelRoles !== undefined && typeof options.modelRoles !== "function")
2569
+ throw new Error("modelRoles requires a host-configured catalogue callback");
2570
+ if (options.remote !== undefined && typeof options.remote?.catalog !== "function")
2571
+ throw new Error("Remote Context requires a host-configured catalogue");
2572
+ if (options.archiveHistory !== undefined && typeof options.archiveHistory !== "boolean")
2573
+ throw new Error("archiveHistory must be a boolean");
2574
+ const host = () => {
2575
+ if (!binding)
2576
+ throw new Error("Call context.bind(harness, storage) before using context management");
2577
+ return binding;
2578
+ };
2579
+ if (options.automaticIdleRollover !== undefined && typeof options.automaticIdleRollover !== "boolean")
2580
+ throw new Error("automaticIdleRollover must be a boolean");
2581
+ const idleMinutes = options.idleRolloverMinutes !== undefined ? options.idleRolloverMinutes : options.automaticIdleRollover ? 25 : 0;
2582
+ if (![0, 5, 15, 25, 55, 115, 355, 715].includes(idleMinutes))
2583
+ throw new Error("idleRolloverMinutes must be 0, 5, 15, 25, 55, 115, 355 or 715");
2584
+ const taskBoundaryReminderTokens = options.taskBoundaryReminderTokens === undefined ? 0 : options.taskBoundaryReminderTokens;
2585
+ if (!Number.isSafeInteger(taskBoundaryReminderTokens) || taskBoundaryReminderTokens < 0)
2586
+ throw new Error("taskBoundaryReminderTokens must be a non-negative safe integer");
2587
+ const now = options.now ?? Date.now;
2588
+ const newContextRequests = options.newContextRequests ?? "unrestricted";
2589
+ if (newContextRequests !== "off" && newContextRequests !== "pi-limits" && newContextRequests !== "unrestricted")
2590
+ throw new Error("newContextRequests must be off, pi-limits or unrestricted");
2591
+ if (newContextRequests === "pi-limits" && options.hasEligibleContextHistory === undefined)
2592
+ throw new Error("pi-limits requires hasEligibleContextHistory from the host");
2593
+ const ensureWindow = async (id, context) => {
2594
+ const conv = await conversation(host(), id, context);
2595
+ await conv.commit((tx) => initializeWindow(tx, id, now()), context);
2596
+ };
2597
+ const rollover = createRollover(host, options.beforeRollover);
2598
+ const input = createInput(host, rollover, idleMinutes * 60 * 1000);
2599
+ const policy = createContextPolicy({
2600
+ models: options.models,
2601
+ host,
2602
+ now,
2603
+ ensureWindow,
2604
+ taskBoundaryReminderTokens,
2605
+ newContextRequests,
2606
+ modelRoles: options.modelRoles,
2607
+ archiveHistory: options.archiveHistory === true,
2608
+ rankedHistory: options.rankedHistory
2609
+ });
2610
+ const notes = createNotesTool({
2611
+ now,
2612
+ storage: () => host().storage,
2613
+ remote: options.remote
2614
+ });
2615
+ const history = createHistoryTool({
2616
+ conversation: (id, context) => conversation(host(), id, context),
2617
+ storage: () => host().storage,
2618
+ remote: options.remote,
2619
+ archiveHistory: options.archiveHistory === true,
2620
+ rankedHistory: options.rankedHistory
2621
+ });
2622
+ const newContext = createToolRollover(host, now, {
2623
+ newContextRequests,
2624
+ modelRoles: options.modelRoles,
2625
+ beforeRollover: options.beforeRollover,
2626
+ ...options.hasEligibleContextHistory === undefined ? {} : { hasEligibleContextHistory: options.hasEligibleContextHistory }
2627
+ });
2628
+ const extension = defineExtension({
2629
+ name: "howaboua.context",
2630
+ tools: [
2631
+ notes,
2632
+ history,
2633
+ policy.remainingTool,
2634
+ ...newContextRequests === "off" ? [] : [newContext.tool]
2635
+ ],
2636
+ tasks: [input, rollover],
2637
+ sections: policy.sections,
2638
+ hooks: [...newContext.hooks, ...policy.hooks]
2639
+ });
2640
+ return {
2641
+ extension,
2642
+ bind(harness, storage) {
2643
+ if (binding && (binding.harness !== harness || binding.storage !== storage))
2644
+ throw new Error("Create a separate context component for each Harness");
2645
+ binding = { harness, storage };
2646
+ },
2647
+ unbind(harness) {
2648
+ if (binding?.harness === harness)
2649
+ binding = undefined;
2650
+ },
2651
+ async rejoin(id, requestId, context) {
2652
+ const receipt = await host().harness.snapshot(InputReceipt, id, requestId, context);
2653
+ return receipt?.task;
2654
+ },
2655
+ async submit(id, draft, context) {
2656
+ await ensureWindow(id, context);
2657
+ const conv = await conversation(host(), id, context);
2658
+ const task = await conv.commit(async (tx) => {
2659
+ const receipt = draft.requestId === undefined ? undefined : await tx.doc(InputReceipt, id, draft.requestId, null);
2660
+ if (receipt?.task)
2661
+ return receipt.task;
2662
+ const gate = await tx.doc(Admission, id);
2663
+ const created = await tx.createTask(input, draft, {
2664
+ ownership: { kind: "conversation" }
2665
+ });
2666
+ gate.queue.push(created);
2667
+ gate.retry++;
2668
+ if (receipt)
2669
+ receipt.task = created;
2670
+ return created;
2671
+ }, context);
2672
+ host().harness.resume();
2673
+ return task;
2674
+ },
2675
+ async newContext(id, context) {
2676
+ await ensureWindow(id, context);
2677
+ const conv = await conversation(host(), id, context);
2678
+ const task = await conv.commit((tx) => scheduleRollover(tx, id, rollover, "manual"), context);
2679
+ host().harness.resume();
2680
+ return task;
2681
+ },
2682
+ waitForSubmission(task, context) {
2683
+ return waitForInputPlacement(host(), task, context);
2684
+ },
2685
+ async retry(id, context) {
2686
+ const conv = await conversation(host(), id, context);
2687
+ await conv.commit(async (tx) => {
2688
+ (await tx.doc(Admission, id)).retry++;
2689
+ }, context);
2690
+ host().harness.resume();
2691
+ },
2692
+ async status(id, context) {
2693
+ return {
2694
+ window: await host().harness.snapshot(WindowState, id, context),
2695
+ admission: await host().harness.snapshot(Admission, id, context)
2696
+ };
2697
+ }
2698
+ };
2699
+ }
2700
+ export {
2701
+ createContextManagement,
2702
+ readSavedNotes
2703
+ };