@howaboua/pi-durable-context 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +4 -0
- package/README.md +8 -4
- package/dist/activation.js +455 -116
- package/dist/index.js +440 -115
- package/dist/internal/context-visibility.d.ts +1 -1
- package/dist/packages/context/src/activation.d.ts +4 -1
- package/dist/packages/context/src/admission.d.ts +2 -0
- package/dist/packages/context/src/deferred-rollover.d.ts +30 -0
- package/dist/packages/context/src/history-archive.d.ts +1 -1
- package/dist/packages/context/src/history.d.ts +18 -2
- package/dist/packages/context/src/index.d.ts +10 -1
- package/dist/packages/context/src/input-placement.d.ts +1 -1
- package/dist/packages/context/src/instruction-run.d.ts +1 -1
- package/dist/packages/context/src/lifecycle.d.ts +1 -1
- package/dist/packages/context/src/model-roles.d.ts +2 -2
- package/dist/packages/context/src/note-store.d.ts +12 -1
- package/dist/packages/context/src/notes.d.ts +18 -1
- package/dist/packages/context/src/policy.d.ts +3 -2
- package/dist/packages/context/src/remote.d.ts +1 -1
- package/dist/packages/context/src/rollover-preparation.d.ts +1 -1
- package/dist/packages/context/src/rollover-tail.d.ts +12 -0
- package/dist/packages/context/src/rollover.d.ts +3 -2
- package/dist/packages/context/src/tool-contract.d.ts +4 -2
- package/dist/packages/context/src/tool-rollover.d.ts +11 -3
- package/dist/packages/context/src/usage.d.ts +1 -1
- package/dist/packages/context/src/window-state.d.ts +1 -0
- package/dist/packages/execution/src/tool-origin.d.ts +19 -0
- package/package.json +7 -7
package/dist/activation.js
CHANGED
|
@@ -12,7 +12,11 @@ import {
|
|
|
12
12
|
import { defineExtension } from "@earendil-works/pi-durable";
|
|
13
13
|
|
|
14
14
|
// packages/context/src/admission.ts
|
|
15
|
-
import {
|
|
15
|
+
import {
|
|
16
|
+
ConversationBusy,
|
|
17
|
+
defineTask as defineTask2,
|
|
18
|
+
LiveDoc as LiveDoc4
|
|
19
|
+
} from "@earendil-works/pi-durable";
|
|
16
20
|
|
|
17
21
|
// packages/context/src/lifecycle.ts
|
|
18
22
|
import {
|
|
@@ -186,11 +190,67 @@ async function cancelPlacedInput(host, conv, id, context) {
|
|
|
186
190
|
// packages/context/src/note-store.ts
|
|
187
191
|
import {
|
|
188
192
|
createSession,
|
|
189
|
-
defineDoc as
|
|
193
|
+
defineDoc as defineDoc4,
|
|
190
194
|
defineDocFamily as defineDocFamily2,
|
|
191
195
|
GenerationTask,
|
|
196
|
+
ToolTask as ToolTask2
|
|
197
|
+
} from "@earendil-works/pi-durable";
|
|
198
|
+
|
|
199
|
+
// packages/execution/src/tool-origin.ts
|
|
200
|
+
import {
|
|
201
|
+
defineDoc as defineDoc3,
|
|
192
202
|
ToolTask
|
|
193
203
|
} from "@earendil-works/pi-durable";
|
|
204
|
+
var ToolOriginDoc = defineDoc3({
|
|
205
|
+
kind: "howaboua.tool-origin",
|
|
206
|
+
version: 1,
|
|
207
|
+
scope: "task",
|
|
208
|
+
checkpointWhen: () => false,
|
|
209
|
+
initial: () => ({})
|
|
210
|
+
});
|
|
211
|
+
async function admittedExecutionCall(tx, conversation, child) {
|
|
212
|
+
const task = await tx.task(child);
|
|
213
|
+
if (task?.conversationId !== conversation || task.kind === ToolTask.definition.name || task.owner === undefined)
|
|
214
|
+
return;
|
|
215
|
+
const owner = await tx.task(task.owner);
|
|
216
|
+
if (owner?.conversationId !== conversation || owner.owner !== undefined)
|
|
217
|
+
return;
|
|
218
|
+
const origin = (await tx.doc(ToolOriginDoc, child)).origin;
|
|
219
|
+
if (origin?.conversationId !== conversation)
|
|
220
|
+
return;
|
|
221
|
+
const root = await tx.task(origin.taskId);
|
|
222
|
+
if (root?.conversationId !== conversation || root.kind !== ToolTask.definition.name)
|
|
223
|
+
return;
|
|
224
|
+
const input = root.input;
|
|
225
|
+
if (input.kind !== "nested" && input.callId === origin.callId)
|
|
226
|
+
return { cell: owner.id, tool: root.id, call: origin.callId };
|
|
227
|
+
}
|
|
228
|
+
async function admittedToolRound(tx, conversation, child) {
|
|
229
|
+
let id = child;
|
|
230
|
+
while (id !== undefined) {
|
|
231
|
+
const task = await tx.task(id);
|
|
232
|
+
if (!task || task.conversationId !== conversation)
|
|
233
|
+
return;
|
|
234
|
+
if (task.kind === ToolTask.definition.name) {
|
|
235
|
+
const input = task.input;
|
|
236
|
+
if (input.kind !== "nested")
|
|
237
|
+
return input.assistant;
|
|
238
|
+
} else if (id !== child) {
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
const origin = (await tx.doc(ToolOriginDoc, id)).origin;
|
|
242
|
+
if (origin) {
|
|
243
|
+
if (origin.conversationId !== conversation)
|
|
244
|
+
return;
|
|
245
|
+
const root = await tx.task(origin.taskId);
|
|
246
|
+
if (root?.conversationId !== conversation || root.kind !== ToolTask.definition.name)
|
|
247
|
+
return;
|
|
248
|
+
const input = root.input;
|
|
249
|
+
return input.kind !== "nested" && input.callId === origin.callId ? input.assistant : undefined;
|
|
250
|
+
}
|
|
251
|
+
id = task.owner;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
194
254
|
|
|
195
255
|
// packages/context/src/query-input.ts
|
|
196
256
|
var actions = {
|
|
@@ -253,6 +313,8 @@ function normalizeQueryInput(namespace, input) {
|
|
|
253
313
|
params["action"] = action;
|
|
254
314
|
if (namespace === "notes") {
|
|
255
315
|
alias(params, "address", "path");
|
|
316
|
+
if (action === "read")
|
|
317
|
+
alias(params, "end_line", "stop_line");
|
|
256
318
|
if (action === "write" || action === "append") {
|
|
257
319
|
alias(params, "content", "text");
|
|
258
320
|
alias(params, "body", "text");
|
|
@@ -287,7 +349,7 @@ function isNoteWrite(input) {
|
|
|
287
349
|
}
|
|
288
350
|
|
|
289
351
|
// packages/context/src/note-store.ts
|
|
290
|
-
var NotesState =
|
|
352
|
+
var NotesState = defineDoc4({
|
|
291
353
|
kind: "howaboua.context.notes-state",
|
|
292
354
|
version: 1,
|
|
293
355
|
scope: "conversation",
|
|
@@ -306,7 +368,7 @@ var NoteFile = defineDocFamily2({
|
|
|
306
368
|
fork: "asOf",
|
|
307
369
|
initial: () => ({ text: "" })
|
|
308
370
|
});
|
|
309
|
-
var WriteReceipt =
|
|
371
|
+
var WriteReceipt = defineDoc4({
|
|
310
372
|
kind: "howaboua.context.note-write-receipt",
|
|
311
373
|
version: 1,
|
|
312
374
|
scope: "task",
|
|
@@ -322,14 +384,30 @@ async function requireNotesWindow(tx, id) {
|
|
|
322
384
|
async function readNoteText(tx, id, path) {
|
|
323
385
|
return (await tx.doc(NoteFile, id, path, null)).text;
|
|
324
386
|
}
|
|
325
|
-
async function
|
|
387
|
+
async function freshNote(tx, id) {
|
|
326
388
|
const userEntry = await latestUserEntry(tx, id);
|
|
327
389
|
const window = await tx.doc(WindowState, id);
|
|
328
390
|
const state = await tx.doc(NotesState, id);
|
|
329
391
|
const fresh = window.window !== undefined && state.lastWrite !== undefined && (state.lastAttempt === undefined || state.lastAttempt === state.lastWrite.taskId) && state.lastWrite.windowId === window.window.id && state.lastWrite.userEntry === userEntry;
|
|
330
|
-
|
|
392
|
+
return fresh ? state.lastWrite : undefined;
|
|
393
|
+
}
|
|
394
|
+
async function successfulTask(tx, id, owner) {
|
|
395
|
+
const task = await tx.task(id);
|
|
396
|
+
if (!task || owner !== undefined && task.owner !== owner || task.abortRequested || task.state.status !== "terminal" || task.state.outcome.status !== "completed")
|
|
397
|
+
return false;
|
|
398
|
+
const result = task.state.outcome.result;
|
|
399
|
+
return !(result && typeof result === "object" && !Array.isArray(result) && result["isError"] === true);
|
|
400
|
+
}
|
|
401
|
+
async function sameCellCheckpoint(tx, id, request, execution) {
|
|
402
|
+
const saved = await freshNote(tx, id);
|
|
403
|
+
if (saved?.execution?.cell === execution.cell && saved.execution.tool === execution.tool && saved.execution.call === execution.call && saved.taskId < request && await successfulTask(tx, saved.taskId, execution.cell))
|
|
404
|
+
return saved.taskId;
|
|
405
|
+
}
|
|
406
|
+
async function notesAreFresh(tx, id) {
|
|
407
|
+
const lastWrite = await freshNote(tx, id);
|
|
408
|
+
if (!lastWrite)
|
|
331
409
|
return false;
|
|
332
|
-
let owner =
|
|
410
|
+
let owner = lastWrite.taskId;
|
|
333
411
|
while (owner !== undefined) {
|
|
334
412
|
const task = await tx.task(owner);
|
|
335
413
|
if (!task)
|
|
@@ -342,7 +420,7 @@ async function notesAreFresh(tx, id) {
|
|
|
342
420
|
if (result && typeof result === "object" && !Array.isArray(result)) {
|
|
343
421
|
if (result["isError"] === true)
|
|
344
422
|
return false;
|
|
345
|
-
if (task.kind ===
|
|
423
|
+
if (task.kind === ToolTask2.definition.name && "entryId" in result) {
|
|
346
424
|
const entryId = result["entryId"];
|
|
347
425
|
if (typeof entryId === "number") {
|
|
348
426
|
const entry = await tx.entry(entryId);
|
|
@@ -357,11 +435,11 @@ async function notesAreFresh(tx, id) {
|
|
|
357
435
|
do {
|
|
358
436
|
const page = await tx.scanTasks({
|
|
359
437
|
conversationId: id,
|
|
360
|
-
kind:
|
|
438
|
+
kind: ToolTask2.definition.name,
|
|
361
439
|
order: "descending"
|
|
362
440
|
}, 64, cursor);
|
|
363
441
|
for (const task of page.items) {
|
|
364
|
-
if (task.id <=
|
|
442
|
+
if (task.id <= lastWrite.taskId)
|
|
365
443
|
return true;
|
|
366
444
|
const input = task.input;
|
|
367
445
|
let call = input.kind === "nested" ? input.call : undefined;
|
|
@@ -376,27 +454,36 @@ async function notesAreFresh(tx, id) {
|
|
|
376
454
|
} while (cursor !== undefined);
|
|
377
455
|
return true;
|
|
378
456
|
}
|
|
379
|
-
async function
|
|
457
|
+
async function isCurrentCheckpoint(tx, id, checkpoint) {
|
|
458
|
+
return (await freshNote(tx, id))?.taskId === checkpoint;
|
|
459
|
+
}
|
|
460
|
+
async function latestNoteRound(tx, id) {
|
|
380
461
|
const saved = (await tx.doc(NotesState, id)).lastWrite;
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
return false;
|
|
384
|
-
const input = requesting.input;
|
|
385
|
-
if (input.kind === "nested")
|
|
386
|
-
return false;
|
|
462
|
+
if (!saved)
|
|
463
|
+
return;
|
|
387
464
|
let owner = saved.taskId;
|
|
388
465
|
let savedAssistant = saved.assistantEntry;
|
|
389
466
|
while (owner !== undefined) {
|
|
390
467
|
const task = await tx.task(owner);
|
|
391
468
|
if (!task || task.kind === GenerationTask.definition.name)
|
|
392
469
|
break;
|
|
393
|
-
if (task.kind ===
|
|
470
|
+
if (task.kind === ToolTask2.definition.name) {
|
|
394
471
|
const call = task.input;
|
|
395
472
|
if (call.kind !== "nested")
|
|
396
473
|
savedAssistant = call.assistant;
|
|
397
474
|
}
|
|
398
475
|
owner = task.owner;
|
|
399
476
|
}
|
|
477
|
+
return savedAssistant;
|
|
478
|
+
}
|
|
479
|
+
async function notesPrecedeRequest(tx, id, request) {
|
|
480
|
+
const requesting = await tx.task(request);
|
|
481
|
+
if (requesting?.kind !== ToolTask2.definition.name)
|
|
482
|
+
return false;
|
|
483
|
+
const input = requesting.input;
|
|
484
|
+
if (input.kind === "nested")
|
|
485
|
+
return false;
|
|
486
|
+
const savedAssistant = await latestNoteRound(tx, id);
|
|
400
487
|
if (savedAssistant === undefined)
|
|
401
488
|
return false;
|
|
402
489
|
const completed = new Map;
|
|
@@ -420,19 +507,6 @@ async function notesPrecedeRequest(tx, id, request) {
|
|
|
420
507
|
} while (cursor !== undefined);
|
|
421
508
|
return false;
|
|
422
509
|
}
|
|
423
|
-
async function currentToolRound(tx, id) {
|
|
424
|
-
let cursor;
|
|
425
|
-
do {
|
|
426
|
-
const page = await tx.scanEntries({ conversationId: id }, 64, cursor);
|
|
427
|
-
for (const entry of page.items) {
|
|
428
|
-
const assistant = entry.model?.findLast((message) => message.role === "assistant");
|
|
429
|
-
if (assistant?.role === "assistant")
|
|
430
|
-
return assistant.content.some((block) => block.type === "toolCall") ? entry.id : undefined;
|
|
431
|
-
}
|
|
432
|
-
cursor = page.next;
|
|
433
|
-
} while (cursor !== undefined);
|
|
434
|
-
return;
|
|
435
|
-
}
|
|
436
510
|
async function beginNoteWrite(tx, id, taskId) {
|
|
437
511
|
const receipt = await tx.doc(WriteReceipt, taskId);
|
|
438
512
|
if (receipt.attempted || receipt.file)
|
|
@@ -469,11 +543,13 @@ async function mutateNote(tx, input) {
|
|
|
469
543
|
nextCatalog.push(metadata);
|
|
470
544
|
else
|
|
471
545
|
nextCatalog[index] = metadata;
|
|
472
|
-
const assistantEntry = await
|
|
546
|
+
const assistantEntry = await admittedToolRound(tx, input.conversationId, input.taskId);
|
|
547
|
+
const execution = await admittedExecutionCall(tx, input.conversationId, input.taskId);
|
|
473
548
|
const freshness = {
|
|
474
549
|
windowId,
|
|
475
550
|
userEntry,
|
|
476
551
|
...assistantEntry === undefined ? {} : { assistantEntry },
|
|
552
|
+
...execution === undefined ? {} : { execution },
|
|
477
553
|
taskId: input.taskId,
|
|
478
554
|
updatedAt
|
|
479
555
|
};
|
|
@@ -595,9 +671,9 @@ async function instructionAnswer(tx, id) {
|
|
|
595
671
|
|
|
596
672
|
// packages/context/src/rollover-preparation.ts
|
|
597
673
|
import {
|
|
598
|
-
defineDoc as
|
|
674
|
+
defineDoc as defineDoc5
|
|
599
675
|
} from "@earendil-works/pi-durable";
|
|
600
|
-
var RolloverPreparation =
|
|
676
|
+
var RolloverPreparation = defineDoc5({
|
|
601
677
|
kind: "howaboua.context.rollover-preparation",
|
|
602
678
|
version: 1,
|
|
603
679
|
scope: "task",
|
|
@@ -662,6 +738,95 @@ async function prepareRollover(conversation, taskId, callback, request, ready, c
|
|
|
662
738
|
return { head };
|
|
663
739
|
}
|
|
664
740
|
|
|
741
|
+
// packages/context/src/rollover-tail.ts
|
|
742
|
+
function visibleConversation(message) {
|
|
743
|
+
if (message.role === "user")
|
|
744
|
+
return message;
|
|
745
|
+
if (message.role !== "assistant")
|
|
746
|
+
return;
|
|
747
|
+
const content = message.content.filter((part) => part.type === "text");
|
|
748
|
+
if (!content.length)
|
|
749
|
+
return;
|
|
750
|
+
return content.length === message.content.length ? message : { ...message, content, stopReason: "stop" };
|
|
751
|
+
}
|
|
752
|
+
function completeMessages(carriers) {
|
|
753
|
+
const complete = new Set;
|
|
754
|
+
let group;
|
|
755
|
+
const finish = () => {
|
|
756
|
+
if (group && group.calls.size === group.results.size) {
|
|
757
|
+
complete.add(group.assistant);
|
|
758
|
+
for (const result of group.results.values())
|
|
759
|
+
complete.add(result);
|
|
760
|
+
}
|
|
761
|
+
group = undefined;
|
|
762
|
+
};
|
|
763
|
+
for (const carrier of carriers) {
|
|
764
|
+
if (carrier.control)
|
|
765
|
+
continue;
|
|
766
|
+
for (const message of carrier.messages) {
|
|
767
|
+
if (message.role === "assistant") {
|
|
768
|
+
finish();
|
|
769
|
+
const calls = message.content.flatMap((part) => part.type === "toolCall" ? [[part.id, part.name]] : []);
|
|
770
|
+
const byId = new Map(calls);
|
|
771
|
+
if (byId.size !== calls.length)
|
|
772
|
+
continue;
|
|
773
|
+
group = {
|
|
774
|
+
assistant: message,
|
|
775
|
+
calls: byId,
|
|
776
|
+
results: new Map
|
|
777
|
+
};
|
|
778
|
+
} else if (message.role === "user") {
|
|
779
|
+
finish();
|
|
780
|
+
} else if (message.role === "toolResult" && group?.calls.get(message.toolCallId) === message.toolName && !group.results.has(message.toolCallId)) {
|
|
781
|
+
group.results.set(message.toolCallId, message);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
finish();
|
|
786
|
+
return complete;
|
|
787
|
+
}
|
|
788
|
+
async function projectRolloverTail(conv, mode, context) {
|
|
789
|
+
const { head, tip } = await conv.commit(async (tx) => ({
|
|
790
|
+
head: await latestNoteRound(tx, conv.id),
|
|
791
|
+
tip: await latestContextEntry(tx, conv.id)
|
|
792
|
+
}), context);
|
|
793
|
+
if (head === undefined || tip === null || head >= tip)
|
|
794
|
+
return;
|
|
795
|
+
const view = await conv.context(context, { at: tip });
|
|
796
|
+
const start = view.entries.findIndex((entry) => entry.id === head && entry.head === undefined);
|
|
797
|
+
if (start < 0)
|
|
798
|
+
return;
|
|
799
|
+
const carriers = view.entries.slice(start).map((entry, index) => ({
|
|
800
|
+
id: entry.id,
|
|
801
|
+
messages: view.contributions[start + index] ?? [],
|
|
802
|
+
control: entry.kind === "pi.system" || entry.kind.startsWith("howaboua.context.")
|
|
803
|
+
}));
|
|
804
|
+
const complete = completeMessages(carriers);
|
|
805
|
+
const saved = carriers[0]?.messages.find((message) => message.role === "assistant");
|
|
806
|
+
const last = carriers.findLast((carrier) => !carrier.control && carrier.messages.length > 0)?.messages.at(-1);
|
|
807
|
+
if (!saved || !complete.has(saved) || last?.role !== "assistant" || last.stopReason !== "stop" || last.content.some((part) => part.type === "toolCall"))
|
|
808
|
+
return;
|
|
809
|
+
const edits = [];
|
|
810
|
+
for (const carrier of carriers) {
|
|
811
|
+
if (!carrier.messages.length)
|
|
812
|
+
continue;
|
|
813
|
+
const messages = carrier.control ? [] : carrier.messages.flatMap((message) => {
|
|
814
|
+
if (message.role === "system")
|
|
815
|
+
return [];
|
|
816
|
+
const projected = mode === "full" && complete.has(message) ? message : visibleConversation(message);
|
|
817
|
+
return projected ? [projected] : [];
|
|
818
|
+
});
|
|
819
|
+
if (!messages.length)
|
|
820
|
+
edits.push({ target: carrier.id, action: "omit" });
|
|
821
|
+
else if (messages.length !== carrier.messages.length || messages.some((message, index) => message !== carrier.messages[index]))
|
|
822
|
+
edits.push({ target: carrier.id, action: "replace", messages });
|
|
823
|
+
}
|
|
824
|
+
return { head, tip, edits };
|
|
825
|
+
}
|
|
826
|
+
async function rolloverTailMatches(tx, conv, tail) {
|
|
827
|
+
return tail.tip === await latestContextEntry(tx, conv.id) && tail.head === await latestNoteRound(tx, conv.id);
|
|
828
|
+
}
|
|
829
|
+
|
|
665
830
|
// packages/context/src/rollover.ts
|
|
666
831
|
var checkpointPrompt = "Save the task state in notes, then finish your reply. A new window opens automatically after your reply; do not call new_context. If saving fails, report the error.";
|
|
667
832
|
var key = (task) => `context:checkpoint:${task}`;
|
|
@@ -688,7 +853,7 @@ async function completedFreshNotes(host, id, context) {
|
|
|
688
853
|
} while (cursor !== undefined);
|
|
689
854
|
return done;
|
|
690
855
|
}
|
|
691
|
-
function createRollover(host, beforeRollover) {
|
|
856
|
+
function createRollover(host, beforeRollover, tailMode = "off") {
|
|
692
857
|
return defineTask({
|
|
693
858
|
name: ROLLOVER_TASK,
|
|
694
859
|
version: 1,
|
|
@@ -703,7 +868,7 @@ function createRollover(host, beforeRollover) {
|
|
|
703
868
|
await Promise.all(tasks.map((id) => runtime.waitForTask(id, context)));
|
|
704
869
|
}
|
|
705
870
|
const fresh = await completedFreshNotes(host(), conv.id, context);
|
|
706
|
-
if (fresh) {
|
|
871
|
+
if (fresh && (tailMode === "off" || task.input.reason === "idle" || await projectRolloverTail(conv, tailMode, context))) {
|
|
707
872
|
await runtime.commit(() => ({ status: "running", checkpoint: { phase: "rotate" } }), context);
|
|
708
873
|
return;
|
|
709
874
|
}
|
|
@@ -804,14 +969,18 @@ function createRollover(host, beforeRollover) {
|
|
|
804
969
|
return completed && await nativeIdle(tx, task.conversationId) && (await foreignTasks(tx, task.conversationId)).length === 0 && await notesAreFresh(tx, task.conversationId);
|
|
805
970
|
};
|
|
806
971
|
const current = await runtime.snapshot(WindowState, task.conversationId, context);
|
|
807
|
-
const
|
|
972
|
+
const keepsTail = tailMode !== "off" && task.input.reason !== "tool";
|
|
973
|
+
const tail = keepsTail ? await projectRolloverTail(conv, tailMode, context) : undefined;
|
|
974
|
+
const preparation = keepsTail && !tail ? {
|
|
975
|
+
error: "No eligible saved checkpoint tail; the current window is unchanged"
|
|
976
|
+
} : await prepareRollover(conv, task.id, beforeRollover, {
|
|
808
977
|
conversationId: task.conversationId,
|
|
809
978
|
windowId: current?.window?.id ?? "",
|
|
810
979
|
nextWindowId: task.input.windowId,
|
|
811
980
|
reason: task.input.reason
|
|
812
|
-
}, ready, context);
|
|
981
|
+
}, async (tx) => await ready(tx) && (!tail || await rolloverTailMatches(tx, conv, tail)), context);
|
|
813
982
|
await runtime.commit(async (tx) => {
|
|
814
|
-
const safe = !preparation.error && await ready(tx) && (preparation.head === undefined || preparation.head === await latestContextEntry(tx, task.conversationId));
|
|
983
|
+
const safe = !preparation.error && await ready(tx) && (!tail || await rolloverTailMatches(tx, conv, tail)) && (preparation.head === undefined || preparation.head === await latestContextEntry(tx, task.conversationId));
|
|
815
984
|
const state = await tx.doc(WindowState, task.conversationId);
|
|
816
985
|
if (!safe || !state.window) {
|
|
817
986
|
delete state.transition;
|
|
@@ -834,7 +1003,7 @@ function createRollover(host, beforeRollover) {
|
|
|
834
1003
|
};
|
|
835
1004
|
const entry = await tx.appendEntry(WindowEntry, task.conversationId, {
|
|
836
1005
|
data: window,
|
|
837
|
-
head: "self"
|
|
1006
|
+
...tail ? { head: tail.head, edits: tail.edits } : { head: "self" }
|
|
838
1007
|
});
|
|
839
1008
|
state.window = window;
|
|
840
1009
|
state.entry = entry.id;
|
|
@@ -1075,7 +1244,8 @@ function createInput(host, rollover, idleMs) {
|
|
|
1075
1244
|
const userEntry = await latestUserEntry(tx, task.conversationId);
|
|
1076
1245
|
const idle = await nativeIdle(tx, task.conversationId);
|
|
1077
1246
|
const state = await tx.doc(WindowState, task.conversationId);
|
|
1078
|
-
|
|
1247
|
+
const answered = !idle && settled.status === "done" && (await tx.doc(LiveDoc4, task.conversationId)).run?.afterRun !== undefined && settled.answer === await latestContextEntry(tx, task.conversationId);
|
|
1248
|
+
if ((idle || answered) && !state.transition)
|
|
1079
1249
|
state.settlement = {
|
|
1080
1250
|
observedAt: runtime.now(),
|
|
1081
1251
|
userEntry,
|
|
@@ -1144,9 +1314,9 @@ import {
|
|
|
1144
1314
|
import { Type as Type2 } from "typebox";
|
|
1145
1315
|
|
|
1146
1316
|
// internal/context-visibility.ts
|
|
1147
|
-
import { createSession as createSession2, defineDoc as
|
|
1317
|
+
import { createSession as createSession2, defineDoc as defineDoc6 } from "@earendil-works/pi-durable";
|
|
1148
1318
|
var SHARED_GROUP = "shared";
|
|
1149
|
-
var ContextVisibility =
|
|
1319
|
+
var ContextVisibility = defineDoc6({
|
|
1150
1320
|
kind: "howaboua.context.visibility",
|
|
1151
1321
|
version: 1,
|
|
1152
1322
|
scope: "conversation",
|
|
@@ -1384,16 +1554,23 @@ var notesParameters = Type.Object({
|
|
|
1384
1554
|
offset_chars: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
1385
1555
|
text: Type.Optional(Type.String())
|
|
1386
1556
|
}, { additionalProperties: false });
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
}
|
|
1393
|
-
|
|
1557
|
+
function newContextParameters(taskCompletionRollover) {
|
|
1558
|
+
return Type.Object({
|
|
1559
|
+
...taskCompletionRollover ? {
|
|
1560
|
+
resume: Type.Optional(Type.Boolean({
|
|
1561
|
+
description: "False: finish this reply, then wait in a fresh window"
|
|
1562
|
+
}))
|
|
1563
|
+
} : {},
|
|
1564
|
+
role: Type.Optional(Type.String({
|
|
1565
|
+
minLength: 1,
|
|
1566
|
+
description: "Configured model-role ID, not an agent name or handoff text"
|
|
1567
|
+
}))
|
|
1568
|
+
}, { additionalProperties: false });
|
|
1569
|
+
}
|
|
1570
|
+
function prepareNewContextArguments(input, taskCompletionRollover) {
|
|
1394
1571
|
const args = input ?? {};
|
|
1395
|
-
if (!Check(newContextParameters, args))
|
|
1396
|
-
throw new Error('Use {} to keep the current role, or {role: "name"} for a configured model-role ID.');
|
|
1572
|
+
if (!Check(newContextParameters(taskCompletionRollover), args))
|
|
1573
|
+
throw new Error(taskCompletionRollover ? 'Use {}, {role: "name"}, or set resume to false after completing the task.' : 'Use {} to keep the current role, or {role: "name"} for a configured model-role ID.');
|
|
1397
1574
|
return args;
|
|
1398
1575
|
}
|
|
1399
1576
|
function prepareNotesArguments(input) {
|
|
@@ -1452,7 +1629,9 @@ function contextToolHelp(namespace, args, rankedHistory = false) {
|
|
|
1452
1629
|
throw new Error("Help accepts only action: help");
|
|
1453
1630
|
const fields = namespace === "notes" ? notesFields : historyFields;
|
|
1454
1631
|
return {
|
|
1455
|
-
...namespace === "notes" ? {
|
|
1632
|
+
...namespace === "notes" ? {
|
|
1633
|
+
results: "list: files; search: files[].matches; read: file.content or file=null; write/append: file.path"
|
|
1634
|
+
} : {},
|
|
1456
1635
|
actions: Object.fromEntries(Object.entries(fields).map(([action, names]) => [
|
|
1457
1636
|
action,
|
|
1458
1637
|
names.map((name) => (name === "path" ? ["read", "write", "append"].includes(action) : ["text", "query", "item_id"].includes(name)) || action === "read" && name === "window_id" ? name : `${name}?`).join(" ")
|
|
@@ -2201,15 +2380,21 @@ function lineIndex(value, count, fallback) {
|
|
|
2201
2380
|
// packages/context/src/policy.ts
|
|
2202
2381
|
import {
|
|
2203
2382
|
CompactionTask,
|
|
2204
|
-
defineDoc as
|
|
2383
|
+
defineDoc as defineDoc8,
|
|
2205
2384
|
defineTool as defineTool3,
|
|
2206
2385
|
GenerationTask as GenerationTask3,
|
|
2207
2386
|
hook,
|
|
2208
2387
|
section,
|
|
2209
|
-
ToolTask as
|
|
2388
|
+
ToolTask as ToolTask3
|
|
2210
2389
|
} from "@earendil-works/pi-durable";
|
|
2211
2390
|
import { Type as Type4 } from "typebox";
|
|
2212
2391
|
|
|
2392
|
+
// packages/context/src/deferred-rollover.ts
|
|
2393
|
+
import {
|
|
2394
|
+
defineDoc as defineDoc7,
|
|
2395
|
+
LiveDoc as LiveDoc5
|
|
2396
|
+
} from "@earendil-works/pi-durable";
|
|
2397
|
+
|
|
2213
2398
|
// packages/context/src/model-roles.ts
|
|
2214
2399
|
import {
|
|
2215
2400
|
AgentDoc
|
|
@@ -2232,7 +2417,7 @@ async function readRoles(catalog, id, context) {
|
|
|
2232
2417
|
reasoning
|
|
2233
2418
|
}));
|
|
2234
2419
|
}
|
|
2235
|
-
async function renderModelRoles(catalog, id,
|
|
2420
|
+
async function renderModelRoles(catalog, id, selected, context) {
|
|
2236
2421
|
let roles;
|
|
2237
2422
|
try {
|
|
2238
2423
|
roles = await readRoles(catalog, id, context);
|
|
@@ -2242,11 +2427,9 @@ async function renderModelRoles(catalog, id, agent, context) {
|
|
|
2242
2427
|
}
|
|
2243
2428
|
if (!roles.length)
|
|
2244
2429
|
return "No model roles are available. Call new_context without role.";
|
|
2245
|
-
const matching = roles.filter((role) => role.provider === agent?.model?.provider && role.model === agent?.model?.modelId && role.reasoning === (agent?.thinkingLevel ?? "off")).map((role) => role.id);
|
|
2246
|
-
const currentRole = matching.length === 0 ? "none (no matching preset)" : matching.length === 1 ? matching.join(", ") : `ambiguous (${matching.join(", ")})`;
|
|
2247
2430
|
return [
|
|
2248
|
-
`Current role: ${
|
|
2249
|
-
'Roles
|
|
2431
|
+
`Current role: ${selected ?? "none"}`,
|
|
2432
|
+
'Roles set focus, not permissions. Switch before a substantial phase that fits another role better. Keep the current role for a brief detour or when no role fits better. Save decisions, evidence paths and the next step in notes immediately before new_context({role: "name"}); omit role to keep the current role.',
|
|
2250
2433
|
...roles.map((role) => `- ${role.id}: ${role.description}`)
|
|
2251
2434
|
].join(`
|
|
2252
2435
|
`);
|
|
@@ -2278,6 +2461,98 @@ async function roleSourceMatches(tx, id, role) {
|
|
|
2278
2461
|
return current.model?.provider === role.source.model?.provider && current.model?.modelId === role.source.model?.modelId && (current.thinkingLevel ?? "off") === role.source.thinkingLevel;
|
|
2279
2462
|
}
|
|
2280
2463
|
|
|
2464
|
+
// packages/context/src/deferred-rollover.ts
|
|
2465
|
+
var ToolWindow = defineDoc7({
|
|
2466
|
+
kind: "howaboua.context.tool-window",
|
|
2467
|
+
version: 1,
|
|
2468
|
+
scope: "task",
|
|
2469
|
+
checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
|
|
2470
|
+
initial: () => ({})
|
|
2471
|
+
});
|
|
2472
|
+
var DeferredWindow = defineDoc7({
|
|
2473
|
+
kind: "howaboua.context.deferred-window",
|
|
2474
|
+
version: 1,
|
|
2475
|
+
scope: "conversation",
|
|
2476
|
+
checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
|
|
2477
|
+
history: "latest",
|
|
2478
|
+
fork: "initial",
|
|
2479
|
+
initial: () => ({})
|
|
2480
|
+
});
|
|
2481
|
+
async function finishesInFreshWindow(api, context) {
|
|
2482
|
+
const deferred = await api.snapshot(DeferredWindow, api.conversationId, context);
|
|
2483
|
+
if (!deferred?.pending)
|
|
2484
|
+
return false;
|
|
2485
|
+
const live = await api.snapshot(LiveDoc5, api.conversationId, context);
|
|
2486
|
+
return live?.run?.taskId === api.taskId && live.run.inputs.includes(deferred.pending.input);
|
|
2487
|
+
}
|
|
2488
|
+
async function armDeferredWindow(conv, generation, ready, context) {
|
|
2489
|
+
await conv.commit(async (tx) => {
|
|
2490
|
+
const receipt = await tx.doc(ToolWindow, generation);
|
|
2491
|
+
const live = await tx.doc(LiveDoc5, conv.id);
|
|
2492
|
+
const input = live.run?.inputs[0];
|
|
2493
|
+
if (live.run?.taskId === generation && input !== undefined && receipt.request?.resume === false && await ready(tx))
|
|
2494
|
+
(await tx.doc(DeferredWindow, conv.id)).pending = {
|
|
2495
|
+
input,
|
|
2496
|
+
request: receipt.request
|
|
2497
|
+
};
|
|
2498
|
+
}, context);
|
|
2499
|
+
}
|
|
2500
|
+
function deferredRolloverHooks(host, beforeRollover, cut) {
|
|
2501
|
+
return {
|
|
2502
|
+
async onYield(_answer, api, context) {
|
|
2503
|
+
if (!await finishesInFreshWindow(api, context))
|
|
2504
|
+
return;
|
|
2505
|
+
const id = api.conversationId;
|
|
2506
|
+
const conv = await conversation(host(), id, context);
|
|
2507
|
+
await conv.commit(async (tx) => {
|
|
2508
|
+
const pending = (await tx.doc(DeferredWindow, id)).pending;
|
|
2509
|
+
const live = await tx.doc(LiveDoc5, id);
|
|
2510
|
+
if (pending && live.run?.taskId === api.taskId && live.run.inputs.includes(pending.input))
|
|
2511
|
+
(await tx.doc(ToolWindow, api.taskId)).request = pending.request;
|
|
2512
|
+
}, context);
|
|
2513
|
+
},
|
|
2514
|
+
async afterRun(run, api, context) {
|
|
2515
|
+
const pending = await api.snapshot(ToolWindow, api.taskId, context);
|
|
2516
|
+
if (run.reason !== "answer" || pending?.request?.resume !== false || pending.finished)
|
|
2517
|
+
return;
|
|
2518
|
+
const id = api.conversationId;
|
|
2519
|
+
const conv = await conversation(host(), id, context);
|
|
2520
|
+
const ready = async (tx) => {
|
|
2521
|
+
const receipt = await tx.doc(ToolWindow, api.taskId);
|
|
2522
|
+
const live = await tx.doc(LiveDoc5, id);
|
|
2523
|
+
const state = await tx.doc(WindowState, id);
|
|
2524
|
+
return !receipt.finished && receipt.request?.resume === false && live.run?.taskId === api.taskId && live.run.afterRun !== undefined && !(await tx.task(api.taskId))?.abortRequested && !state.transition && state.window?.id === receipt.request.window.previous && run.answer === await latestContextEntry(tx, id) && await notesAreFresh(tx, id) && (!receipt.request.role || await roleSourceMatches(tx, id, receipt.request.role)) && (await foreignTasks(tx, id)).every((task) => task === api.taskId);
|
|
2525
|
+
};
|
|
2526
|
+
const prep = await prepareRollover(conv, api.taskId, beforeRollover, {
|
|
2527
|
+
conversationId: id,
|
|
2528
|
+
windowId: pending.request.window.previous ?? "",
|
|
2529
|
+
nextWindowId: pending.request.window.id,
|
|
2530
|
+
reason: "tool"
|
|
2531
|
+
}, ready, context);
|
|
2532
|
+
await conv.commit(async (tx) => {
|
|
2533
|
+
const receipt = await tx.doc(ToolWindow, api.taskId);
|
|
2534
|
+
if (!receipt.request || receipt.finished)
|
|
2535
|
+
return;
|
|
2536
|
+
const safe = !prep.error && await ready(tx);
|
|
2537
|
+
receipt.finished = true;
|
|
2538
|
+
const deferred = await tx.doc(DeferredWindow, id);
|
|
2539
|
+
if (deferred.pending?.request.tool === receipt.request.tool)
|
|
2540
|
+
delete deferred.pending;
|
|
2541
|
+
if (safe)
|
|
2542
|
+
await cut(tx, id, receipt.request);
|
|
2543
|
+
else
|
|
2544
|
+
await tx.appendEntry(id, {
|
|
2545
|
+
kind: "howaboua.context.rollover-skipped",
|
|
2546
|
+
data: {
|
|
2547
|
+
windowId: receipt.request.window.id,
|
|
2548
|
+
reason: prep.error ?? "Conversation changed before the completed reply could roll over"
|
|
2549
|
+
}
|
|
2550
|
+
});
|
|
2551
|
+
}, context);
|
|
2552
|
+
}
|
|
2553
|
+
};
|
|
2554
|
+
}
|
|
2555
|
+
|
|
2281
2556
|
// packages/context/src/usage.ts
|
|
2282
2557
|
import { estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
|
|
2283
2558
|
async function contextUsage(conversation, models, context, answer) {
|
|
@@ -2346,7 +2621,7 @@ function checkpointGuidance(newContextRequests) {
|
|
|
2346
2621
|
|
|
2347
2622
|
`);
|
|
2348
2623
|
}
|
|
2349
|
-
var YieldAdvisory =
|
|
2624
|
+
var YieldAdvisory = defineDoc8({
|
|
2350
2625
|
kind: "howaboua.context.yield-advisory",
|
|
2351
2626
|
version: 1,
|
|
2352
2627
|
scope: "task",
|
|
@@ -2363,7 +2638,7 @@ function createContextPolicy(options) {
|
|
|
2363
2638
|
const sections = [
|
|
2364
2639
|
section("context", () => checkpointGuidance(options.newContextRequests)),
|
|
2365
2640
|
...options.newContextRequests === "off" || !options.modelRoles ? [] : [
|
|
2366
|
-
section("context-roles", async (input, context) => renderModelRoles(options.modelRoles, input.conversationId, input.
|
|
2641
|
+
section("context-roles", async (input, context) => renderModelRoles(options.modelRoles, input.conversationId, (await input.read.snapshot(WindowState, input.conversationId, context))?.selectedRole, context))
|
|
2367
2642
|
],
|
|
2368
2643
|
section("context-state", async (input, context) => {
|
|
2369
2644
|
const [state, hints] = await Promise.all([
|
|
@@ -2457,16 +2732,20 @@ function createContextPolicy(options) {
|
|
|
2457
2732
|
await refreshRankedHistory(await conversation(api.conversationId, context), options.rankedHistory, context);
|
|
2458
2733
|
},
|
|
2459
2734
|
async afterTools(_assistant, _results, api, context) {
|
|
2735
|
+
if (options.taskCompletionRollover && await finishesInFreshWindow(api, context))
|
|
2736
|
+
return;
|
|
2460
2737
|
await remind(api, context);
|
|
2461
2738
|
},
|
|
2462
2739
|
async onYield(answer, api, context) {
|
|
2463
2740
|
if (options.rankedHistory)
|
|
2464
2741
|
await refreshRankedHistory(await conversation(api.conversationId, context), options.rankedHistory, context);
|
|
2742
|
+
if (options.taskCompletionRollover && await finishesInFreshWindow(api, context))
|
|
2743
|
+
return;
|
|
2465
2744
|
const text = await remind(api, context, answer);
|
|
2466
|
-
return text ? { continue: text } : undefined;
|
|
2745
|
+
return text ? { kind: "continue", continue: text } : undefined;
|
|
2467
2746
|
}
|
|
2468
2747
|
}),
|
|
2469
|
-
hook(
|
|
2748
|
+
hook(ToolTask3, {
|
|
2470
2749
|
async beforeTool(_call, api, context) {
|
|
2471
2750
|
await options.ensureWindow(api.conversationId, context);
|
|
2472
2751
|
},
|
|
@@ -2477,7 +2756,7 @@ function createContextPolicy(options) {
|
|
|
2477
2756
|
}),
|
|
2478
2757
|
hook(CompactionTask, {
|
|
2479
2758
|
async beforeCompact(compaction) {
|
|
2480
|
-
return compaction.reason === "overflow" ? undefined : {
|
|
2759
|
+
return compaction.reason === "overflow" ? undefined : { kind: "decline" };
|
|
2481
2760
|
}
|
|
2482
2761
|
})
|
|
2483
2762
|
];
|
|
@@ -2487,39 +2766,68 @@ function createContextPolicy(options) {
|
|
|
2487
2766
|
// packages/context/src/tool-rollover.ts
|
|
2488
2767
|
import {
|
|
2489
2768
|
configure,
|
|
2490
|
-
defineDoc as defineDoc7,
|
|
2491
2769
|
defineTool as defineTool4,
|
|
2492
2770
|
GenerationTask as GenerationTask4,
|
|
2493
2771
|
hook as hook2,
|
|
2494
2772
|
InboxDoc as InboxDoc2,
|
|
2495
|
-
LiveDoc as
|
|
2773
|
+
LiveDoc as LiveDoc6
|
|
2496
2774
|
} from "@earendil-works/pi-durable";
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2775
|
+
async function requestAdmission(tx, id, tool) {
|
|
2776
|
+
const live = await tx.doc(LiveDoc6, id);
|
|
2777
|
+
const slot = live.tools?.length === 1 ? live.tools[0] : undefined;
|
|
2778
|
+
if (live.run && slot) {
|
|
2779
|
+
if (slot.taskId === tool)
|
|
2780
|
+
return { run: live.run };
|
|
2781
|
+
const execution = await admittedExecutionCall(tx, id, tool);
|
|
2782
|
+
if (execution && execution.tool === slot.taskId && execution.call === slot.callId)
|
|
2783
|
+
return { run: live.run, execution };
|
|
2784
|
+
}
|
|
2785
|
+
throw new Error("Call new_context alone or after a successful notes write in the same foreground cell");
|
|
2786
|
+
}
|
|
2787
|
+
async function checkpointSettled(tx, id, request) {
|
|
2788
|
+
if (!await notesAreFresh(tx, id))
|
|
2789
|
+
return false;
|
|
2790
|
+
const nested = request.nested;
|
|
2791
|
+
return nested ? await successfulTask(tx, request.tool, nested.cell) && await successfulTask(tx, nested.cell) && await isCurrentCheckpoint(tx, id, nested.checkpoint) : notesPrecedeRequest(tx, id, request.tool);
|
|
2792
|
+
}
|
|
2504
2793
|
function createToolRollover(host, now, policy) {
|
|
2794
|
+
async function cut(tx, id, request) {
|
|
2795
|
+
const state = await tx.doc(WindowState, id);
|
|
2796
|
+
if (request.role) {
|
|
2797
|
+
state.selectedRole = request.role.id;
|
|
2798
|
+
await configure(tx, id, {
|
|
2799
|
+
model: request.role.model,
|
|
2800
|
+
thinkingLevel: request.role.thinkingLevel
|
|
2801
|
+
});
|
|
2802
|
+
}
|
|
2803
|
+
const window = { ...request.window, startedAt: now() };
|
|
2804
|
+
const entry = await tx.appendEntry(WindowEntry, id, {
|
|
2805
|
+
data: window,
|
|
2806
|
+
head: "self"
|
|
2807
|
+
});
|
|
2808
|
+
state.window = window;
|
|
2809
|
+
state.entry = entry.id;
|
|
2810
|
+
state.reminded = 0;
|
|
2811
|
+
delete state.settlement;
|
|
2812
|
+
}
|
|
2505
2813
|
const tool = defineTool4({
|
|
2506
2814
|
name: "new_context",
|
|
2507
2815
|
description: "Start fresh context window. Must save notes first and call alone",
|
|
2508
|
-
parameters: newContextParameters,
|
|
2509
|
-
prepareArguments: prepareNewContextArguments,
|
|
2816
|
+
parameters: newContextParameters(policy.taskCompletionRollover),
|
|
2817
|
+
prepareArguments: (input) => prepareNewContextArguments(input, policy.taskCompletionRollover),
|
|
2510
2818
|
replay: "safe",
|
|
2511
|
-
callers: ["model"],
|
|
2819
|
+
callers: ["model", "tools"],
|
|
2512
2820
|
executionMode: "sequential",
|
|
2513
2821
|
async execute(args, api, context) {
|
|
2514
2822
|
if (policy.newContextRequests === "pi-limits") {
|
|
2515
|
-
const
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2823
|
+
const prior = await api.commit(async (tx) => {
|
|
2824
|
+
const { run } = await requestAdmission(tx, api.conversationId, api.taskId);
|
|
2825
|
+
return (await tx.doc(ToolWindow, run.taskId)).request?.tool === api.taskId;
|
|
2826
|
+
}, context);
|
|
2519
2827
|
const hasEligibleContextHistory = policy.hasEligibleContextHistory;
|
|
2520
2828
|
if (!hasEligibleContextHistory)
|
|
2521
2829
|
throw new Error("pi-limits requires hasEligibleContextHistory from the host");
|
|
2522
|
-
if (!prior
|
|
2830
|
+
if (!prior && !await hasEligibleContextHistory(api.conversationId, context))
|
|
2523
2831
|
return {
|
|
2524
2832
|
output: [
|
|
2525
2833
|
{
|
|
@@ -2532,26 +2840,41 @@ function createToolRollover(host, now, policy) {
|
|
|
2532
2840
|
]
|
|
2533
2841
|
};
|
|
2534
2842
|
}
|
|
2535
|
-
const live = await api.snapshot(
|
|
2843
|
+
const live = await api.snapshot(LiveDoc6, api.conversationId, context);
|
|
2536
2844
|
const prior = live?.run ? await api.snapshot(ToolWindow, live.run.taskId, context) : undefined;
|
|
2537
|
-
const role = prior?.request ? prior.request.role : args.role === undefined ? undefined : await prepareRole(policy.modelRoles, args.role, api.conversationId, await api.agent(context), api.models, context);
|
|
2845
|
+
const role = prior?.request?.tool === api.taskId ? prior.request.role : args.role === undefined ? undefined : await prepareRole(policy.modelRoles, args.role, api.conversationId, await api.agent(context), api.models, context);
|
|
2538
2846
|
const result = await api.commit(async (tx) => {
|
|
2539
|
-
const
|
|
2540
|
-
|
|
2541
|
-
|
|
2847
|
+
const { run, execution } = await requestAdmission(tx, api.conversationId, api.taskId);
|
|
2848
|
+
const deferred = policy.taskCompletionRollover ? (await tx.doc(DeferredWindow, api.conversationId)).pending : undefined;
|
|
2849
|
+
if (deferred && run.inputs.includes(deferred.input))
|
|
2850
|
+
throw new Error("A context rollover is already scheduled for this reply");
|
|
2851
|
+
if (args.resume === false && run.inputs.length === 0)
|
|
2852
|
+
throw new Error("A deferred rollover needs an active input submission");
|
|
2542
2853
|
const state = await tx.doc(WindowState, api.conversationId);
|
|
2543
2854
|
if (!state.window || state.transition)
|
|
2544
2855
|
throw new Error("Context window is missing or a checkpoint is already in progress");
|
|
2545
2856
|
if (role && !await roleSourceMatches(tx, api.conversationId, role))
|
|
2546
2857
|
throw new Error("The model settings changed. Continue here and request a new role handoff if still needed.");
|
|
2547
|
-
|
|
2858
|
+
const checkpoint = execution && await sameCellCheckpoint(tx, api.conversationId, api.taskId, execution);
|
|
2859
|
+
const fresh = execution ? checkpoint !== undefined : await notesAreFresh(tx, api.conversationId) && await notesPrecedeRequest(tx, api.conversationId, api.taskId);
|
|
2860
|
+
if (!fresh)
|
|
2548
2861
|
return {
|
|
2549
2862
|
status: "checkpoint_required",
|
|
2550
2863
|
message: "Save the current task checkpoint in your own notes using a relative path, wait for success, then call new_context alone again. Another agent's notes do not save your checkpoint. The current window has not changed."
|
|
2551
2864
|
};
|
|
2552
|
-
const receipt = await tx.doc(ToolWindow,
|
|
2865
|
+
const receipt = await tx.doc(ToolWindow, run.taskId);
|
|
2866
|
+
if (receipt.request && receipt.request.tool !== api.taskId)
|
|
2867
|
+
throw new Error("A context rollover is already scheduled for this reply");
|
|
2553
2868
|
receipt.request ??= {
|
|
2554
2869
|
tool: api.taskId,
|
|
2870
|
+
...execution && checkpoint !== undefined ? {
|
|
2871
|
+
nested: {
|
|
2872
|
+
cell: execution.cell,
|
|
2873
|
+
nativeTool: execution.tool,
|
|
2874
|
+
checkpoint
|
|
2875
|
+
}
|
|
2876
|
+
} : {},
|
|
2877
|
+
...args.resume === false ? { resume: false } : {},
|
|
2555
2878
|
...role ? { role } : {},
|
|
2556
2879
|
window: {
|
|
2557
2880
|
id: crypto.randomUUID(),
|
|
@@ -2560,29 +2883,37 @@ function createToolRollover(host, now, policy) {
|
|
|
2560
2883
|
previous: state.window.id
|
|
2561
2884
|
}
|
|
2562
2885
|
};
|
|
2563
|
-
return {
|
|
2886
|
+
return {
|
|
2887
|
+
status: "scheduled",
|
|
2888
|
+
window_id: receipt.request.window.id,
|
|
2889
|
+
...receipt.request.resume === false ? { message: "Finish your reply. No continuation will start." } : {}
|
|
2890
|
+
};
|
|
2564
2891
|
}, context);
|
|
2565
2892
|
return { output: [{ type: "text", text: JSON.stringify(result) }] };
|
|
2566
2893
|
}
|
|
2567
2894
|
});
|
|
2568
2895
|
const hooks = [
|
|
2569
2896
|
hook2(GenerationTask4, {
|
|
2570
|
-
async afterTools(_assistant,
|
|
2897
|
+
async afterTools(_assistant, results, api, context) {
|
|
2571
2898
|
const pending = await api.snapshot(ToolWindow, api.taskId, context);
|
|
2572
2899
|
if (!pending?.request || pending.finished)
|
|
2573
2900
|
return;
|
|
2574
2901
|
const conv = await conversation(host(), api.conversationId, context);
|
|
2575
|
-
const ready = async (tx) => {
|
|
2902
|
+
const ready = async (tx, arming = false) => {
|
|
2576
2903
|
const receipt = await tx.doc(ToolWindow, api.taskId);
|
|
2577
2904
|
if (!receipt.request || receipt.finished)
|
|
2578
2905
|
return false;
|
|
2579
|
-
const live = await tx.doc(
|
|
2906
|
+
const live = await tx.doc(LiveDoc6, api.conversationId);
|
|
2580
2907
|
const inbox = await tx.doc(InboxDoc2, api.conversationId);
|
|
2581
2908
|
const state = await tx.doc(WindowState, api.conversationId);
|
|
2582
2909
|
const slot = live.tools?.[0];
|
|
2583
2910
|
const generation = await tx.task(api.taskId);
|
|
2584
|
-
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
|
|
2911
|
+
return live.run?.taskId === api.taskId && !generation?.abortRequested && live.tools?.length === 1 && slot?.taskId === (receipt.request.nested?.nativeTool ?? receipt.request.tool) && slot.status === "done" && slot.entry !== undefined && slot.entry === results[0] && (await tx.entry(slot.entry))?.model?.some((message) => message.role === "toolResult" && message.toolCallId === slot.callId && !message.isError) === true && (arming || inbox.items.length === 0) && !state.transition && state.window?.id === receipt.request.window.previous && await checkpointSettled(tx, api.conversationId, receipt.request) && (!receipt.request.role || await roleSourceMatches(tx, api.conversationId, receipt.request.role)) && (arming || (await foreignTasks(tx, api.conversationId)).every((id) => id === api.taskId));
|
|
2585
2912
|
};
|
|
2913
|
+
if (pending.request.resume === false) {
|
|
2914
|
+
await armDeferredWindow(conv, api.taskId, (tx) => ready(tx, true), context);
|
|
2915
|
+
return;
|
|
2916
|
+
}
|
|
2586
2917
|
const preparation = await prepareRollover(conv, api.taskId, policy.beforeRollover, {
|
|
2587
2918
|
conversationId: api.conversationId,
|
|
2588
2919
|
windowId: pending.request.window.previous ?? "",
|
|
@@ -2593,25 +2924,10 @@ function createToolRollover(host, now, policy) {
|
|
|
2593
2924
|
const receipt = await tx.doc(ToolWindow, api.taskId);
|
|
2594
2925
|
if (!receipt.request || receipt.finished)
|
|
2595
2926
|
return;
|
|
2596
|
-
const state = await tx.doc(WindowState, api.conversationId);
|
|
2597
2927
|
const safe = !preparation.error && await ready(tx) && (preparation.head === undefined || preparation.head === await latestContextEntry(tx, api.conversationId));
|
|
2598
2928
|
receipt.finished = true;
|
|
2599
|
-
if (safe)
|
|
2600
|
-
|
|
2601
|
-
await configure(tx, api.conversationId, {
|
|
2602
|
-
model: receipt.request.role.model,
|
|
2603
|
-
thinkingLevel: receipt.request.role.thinkingLevel
|
|
2604
|
-
});
|
|
2605
|
-
const window = { ...receipt.request.window, startedAt: now() };
|
|
2606
|
-
const entry = await tx.appendEntry(WindowEntry, api.conversationId, {
|
|
2607
|
-
data: window,
|
|
2608
|
-
head: "self"
|
|
2609
|
-
});
|
|
2610
|
-
state.window = window;
|
|
2611
|
-
state.entry = entry.id;
|
|
2612
|
-
state.reminded = 0;
|
|
2613
|
-
delete state.settlement;
|
|
2614
|
-
}
|
|
2929
|
+
if (safe)
|
|
2930
|
+
await cut(tx, api.conversationId, receipt.request);
|
|
2615
2931
|
await tx.appendEntry(api.conversationId, {
|
|
2616
2932
|
kind: "howaboua.context.continuation",
|
|
2617
2933
|
model: [
|
|
@@ -2632,11 +2948,12 @@ Role: ${receipt.request.role.id}` : ""}` : preparation.error ?? "Context rollove
|
|
|
2632
2948
|
]
|
|
2633
2949
|
});
|
|
2634
2950
|
}, context);
|
|
2635
|
-
}
|
|
2951
|
+
},
|
|
2952
|
+
...policy.taskCompletionRollover ? deferredRolloverHooks(host, policy.beforeRollover, cut) : {}
|
|
2636
2953
|
})
|
|
2637
2954
|
];
|
|
2638
2955
|
return {
|
|
2639
|
-
tool: { ...tool, executionHints: {
|
|
2956
|
+
tool: { ...tool, executionHints: { nestedHidden: true } },
|
|
2640
2957
|
hooks
|
|
2641
2958
|
};
|
|
2642
2959
|
}
|
|
@@ -2665,6 +2982,11 @@ function createContextManagement(options) {
|
|
|
2665
2982
|
throw new Error("taskBoundaryReminderTokens must be a non-negative safe integer");
|
|
2666
2983
|
const now = options.now ?? Date.now;
|
|
2667
2984
|
const newContextRequests = options.newContextRequests ?? "unrestricted";
|
|
2985
|
+
const tailMode = options.rolloverTail ?? "off";
|
|
2986
|
+
if (tailMode !== "off" && tailMode !== "conversation" && tailMode !== "full")
|
|
2987
|
+
throw new Error("rolloverTail must be off, conversation or full");
|
|
2988
|
+
if (options.taskCompletionRollover !== undefined && typeof options.taskCompletionRollover !== "boolean")
|
|
2989
|
+
throw new Error("taskCompletionRollover must be a boolean");
|
|
2668
2990
|
if (newContextRequests !== "off" && newContextRequests !== "pi-limits" && newContextRequests !== "unrestricted")
|
|
2669
2991
|
throw new Error("newContextRequests must be off, pi-limits or unrestricted");
|
|
2670
2992
|
if (newContextRequests === "pi-limits" && options.hasEligibleContextHistory === undefined)
|
|
@@ -2673,7 +2995,8 @@ function createContextManagement(options) {
|
|
|
2673
2995
|
const conv = await conversation(host(), id, context);
|
|
2674
2996
|
await conv.commit((tx) => initializeWindow(tx, id, now()), context);
|
|
2675
2997
|
};
|
|
2676
|
-
const
|
|
2998
|
+
const taskCompletionRollover = newContextRequests !== "off" && options.taskCompletionRollover === true;
|
|
2999
|
+
const rollover = createRollover(host, options.beforeRollover, tailMode);
|
|
2677
3000
|
const input = createInput(host, rollover, idleMinutes * 60 * 1000);
|
|
2678
3001
|
const policy = createContextPolicy({
|
|
2679
3002
|
models: options.models,
|
|
@@ -2682,6 +3005,7 @@ function createContextManagement(options) {
|
|
|
2682
3005
|
ensureWindow,
|
|
2683
3006
|
taskBoundaryReminderTokens,
|
|
2684
3007
|
newContextRequests,
|
|
3008
|
+
taskCompletionRollover,
|
|
2685
3009
|
modelRoles: options.modelRoles,
|
|
2686
3010
|
archiveHistory: options.archiveHistory === true,
|
|
2687
3011
|
rankedHistory: options.rankedHistory
|
|
@@ -2700,6 +3024,7 @@ function createContextManagement(options) {
|
|
|
2700
3024
|
});
|
|
2701
3025
|
const newContext = createToolRollover(host, now, {
|
|
2702
3026
|
newContextRequests,
|
|
3027
|
+
taskCompletionRollover,
|
|
2703
3028
|
modelRoles: options.modelRoles,
|
|
2704
3029
|
beforeRollover: options.beforeRollover,
|
|
2705
3030
|
...options.hasEligibleContextHistory === undefined ? {} : { hasEligibleContextHistory: options.hasEligibleContextHistory }
|
|
@@ -2707,7 +3032,7 @@ function createContextManagement(options) {
|
|
|
2707
3032
|
const extension = defineExtension({
|
|
2708
3033
|
name: "howaboua.context",
|
|
2709
3034
|
tools: [
|
|
2710
|
-
notes,
|
|
3035
|
+
...options.localNotes === false ? [] : [notes],
|
|
2711
3036
|
history,
|
|
2712
3037
|
policy.remainingTool,
|
|
2713
3038
|
...newContextRequests === "off" ? [] : [newContext.tool]
|
|
@@ -2908,9 +3233,12 @@ function configuredOptions(request) {
|
|
|
2908
3233
|
const config = request.configuration;
|
|
2909
3234
|
const allowed = new Set([
|
|
2910
3235
|
"archiveHistory",
|
|
3236
|
+
"localNotes",
|
|
2911
3237
|
"automaticIdleRollover",
|
|
2912
3238
|
"idleRolloverMinutes",
|
|
2913
3239
|
"taskBoundaryReminderTokens",
|
|
3240
|
+
"taskCompletionRollover",
|
|
3241
|
+
"rolloverTail",
|
|
2914
3242
|
"newContextRequests",
|
|
2915
3243
|
"rankedHistory",
|
|
2916
3244
|
"modelRoles"
|
|
@@ -2921,7 +3249,12 @@ function configuredOptions(request) {
|
|
|
2921
3249
|
const options = {
|
|
2922
3250
|
models: request.capabilities.get(modelsCapability)
|
|
2923
3251
|
};
|
|
2924
|
-
for (const key of [
|
|
3252
|
+
for (const key of [
|
|
3253
|
+
"archiveHistory",
|
|
3254
|
+
"localNotes",
|
|
3255
|
+
"automaticIdleRollover",
|
|
3256
|
+
"taskCompletionRollover"
|
|
3257
|
+
]) {
|
|
2925
3258
|
const value = config[key];
|
|
2926
3259
|
if (value !== undefined) {
|
|
2927
3260
|
if (typeof value !== "boolean")
|
|
@@ -2930,6 +3263,12 @@ function configuredOptions(request) {
|
|
|
2930
3263
|
}
|
|
2931
3264
|
}
|
|
2932
3265
|
const idle = config["idleRolloverMinutes"];
|
|
3266
|
+
const tail = config["rolloverTail"];
|
|
3267
|
+
if (tail !== undefined) {
|
|
3268
|
+
if (!oneOf(tail, ["off", "conversation", "full"]))
|
|
3269
|
+
throw new Error("rolloverTail must be off, conversation or full");
|
|
3270
|
+
options.rolloverTail = tail;
|
|
3271
|
+
}
|
|
2933
3272
|
if (idle !== undefined) {
|
|
2934
3273
|
if (!oneOf(idle, [0, 5, 15, 25, 55, 115, 355, 715]))
|
|
2935
3274
|
throw new Error("Invalid idleRolloverMinutes");
|