@howaboua/pi-durable-context 0.9.1 → 0.11.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/README.md +2 -2
- package/dist/activation.js +3049 -0
- package/dist/index.js +213 -42
- package/dist/packages/context/src/activation.d.ts +20 -0
- package/dist/packages/context/src/admission.d.ts +1 -0
- package/dist/packages/context/src/history.d.ts +4 -4
- package/dist/packages/context/src/index.d.ts +4 -0
- package/dist/packages/context/src/input-placement.d.ts +6 -0
- package/dist/packages/context/src/model-roles.d.ts +1 -1
- package/dist/packages/context/src/note-store.d.ts +3 -0
- package/dist/packages/context/src/notes.d.ts +4 -4
- package/dist/packages/context/src/tool-contract.d.ts +4 -2
- package/dist/packages/context/src/tool-rollover.d.ts +1 -1
- package/package.json +26 -6
package/dist/index.js
CHANGED
|
@@ -134,8 +134,12 @@ async function until(watch, predicate, signal) {
|
|
|
134
134
|
await new Promise((resolve, reject) => {
|
|
135
135
|
abort = () => reject(signal.reason);
|
|
136
136
|
signal.addEventListener("abort", abort, { once: true });
|
|
137
|
-
watch.start(async (
|
|
138
|
-
if (
|
|
137
|
+
watch.start(async (call) => {
|
|
138
|
+
if (call.kind === "failed") {
|
|
139
|
+
reject(call.error);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (predicate(call.value))
|
|
139
143
|
resolve();
|
|
140
144
|
});
|
|
141
145
|
if (signal.aborted)
|
|
@@ -143,8 +147,8 @@ async function until(watch, predicate, signal) {
|
|
|
143
147
|
else if (watch.value && predicate(watch.value))
|
|
144
148
|
resolve();
|
|
145
149
|
watch.closed.then((end) => {
|
|
146
|
-
if (end.
|
|
147
|
-
reject(new Error(`Context watch ended: ${end.
|
|
150
|
+
if (end.kind !== "stopped")
|
|
151
|
+
reject(end.kind === "failed" || end.kind === "listener_error" ? end.error : new Error(`Context watch ended: ${end.kind}`));
|
|
148
152
|
});
|
|
149
153
|
});
|
|
150
154
|
} finally {
|
|
@@ -231,13 +235,18 @@ function normalizeQueryInput(namespace, input) {
|
|
|
231
235
|
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
232
236
|
throw new Error("Supply an action object; use {} for help");
|
|
233
237
|
const params = { ...input };
|
|
238
|
+
if (namespace === "history" && params["action"] === undefined && "query" in params)
|
|
239
|
+
params["action"] = "search";
|
|
234
240
|
const aliases = actions[namespace];
|
|
235
241
|
const action = aliases[String(params["action"])] ?? params["action"];
|
|
236
242
|
if (action !== undefined)
|
|
237
243
|
params["action"] = action;
|
|
238
244
|
if (namespace === "notes") {
|
|
239
|
-
|
|
245
|
+
alias(params, "address", "path");
|
|
246
|
+
if (action === "write" || action === "append") {
|
|
240
247
|
alias(params, "content", "text");
|
|
248
|
+
alias(params, "body", "text");
|
|
249
|
+
}
|
|
241
250
|
if (action === "list" || action === "search") {
|
|
242
251
|
alias(params, "prefix", "path");
|
|
243
252
|
alias(params, "path_prefix", "path");
|
|
@@ -250,6 +259,8 @@ function normalizeQueryInput(namespace, input) {
|
|
|
250
259
|
alias(params, "max_results", "limit");
|
|
251
260
|
}
|
|
252
261
|
const used = usedPresentation[`${namespace}:${String(action)}`] ?? [];
|
|
262
|
+
if (namespace === "history" && action !== "read")
|
|
263
|
+
delete params["offset_chars"];
|
|
253
264
|
for (const hint of presentation)
|
|
254
265
|
if (!used.includes(hint))
|
|
255
266
|
delete params[hint];
|
|
@@ -382,6 +393,63 @@ async function notesAreFresh(tx, id) {
|
|
|
382
393
|
} while (cursor !== undefined);
|
|
383
394
|
return true;
|
|
384
395
|
}
|
|
396
|
+
async function notesPrecedeRequest(tx, id, request) {
|
|
397
|
+
const saved = (await tx.doc(NotesState, id)).lastWrite;
|
|
398
|
+
const requesting = await tx.task(request);
|
|
399
|
+
if (!saved || requesting?.kind !== ToolTask.definition.name)
|
|
400
|
+
return false;
|
|
401
|
+
const input = requesting.input;
|
|
402
|
+
if (input.kind === "nested")
|
|
403
|
+
return false;
|
|
404
|
+
let owner = saved.taskId;
|
|
405
|
+
let savedAssistant = saved.assistantEntry;
|
|
406
|
+
while (owner !== undefined) {
|
|
407
|
+
const task = await tx.task(owner);
|
|
408
|
+
if (!task || task.kind === GenerationTask.definition.name)
|
|
409
|
+
break;
|
|
410
|
+
if (task.kind === ToolTask.definition.name) {
|
|
411
|
+
const call = task.input;
|
|
412
|
+
if (call.kind !== "nested")
|
|
413
|
+
savedAssistant = call.assistant;
|
|
414
|
+
}
|
|
415
|
+
owner = task.owner;
|
|
416
|
+
}
|
|
417
|
+
if (savedAssistant === undefined)
|
|
418
|
+
return false;
|
|
419
|
+
const completed = new Map;
|
|
420
|
+
let cursor;
|
|
421
|
+
do {
|
|
422
|
+
const page = await tx.scanEntries({ conversationId: id, maxEntryId: input.assistant }, 64, cursor);
|
|
423
|
+
for (const entry of page.items) {
|
|
424
|
+
if (entry.id === input.assistant)
|
|
425
|
+
continue;
|
|
426
|
+
for (const message of entry.model ?? []) {
|
|
427
|
+
if (message.role === "toolResult")
|
|
428
|
+
completed.set(message.toolCallId, !message.isError);
|
|
429
|
+
if (message.role !== "assistant")
|
|
430
|
+
continue;
|
|
431
|
+
const calls = message.content.filter((block) => block.type === "toolCall");
|
|
432
|
+
if (calls.length)
|
|
433
|
+
return entry.id === savedAssistant && calls.every((call) => completed.has(call.id) && (call.name !== "notes" || !isNoteWrite(call.arguments) || completed.get(call.id) === true));
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
cursor = page.next;
|
|
437
|
+
} while (cursor !== undefined);
|
|
438
|
+
return false;
|
|
439
|
+
}
|
|
440
|
+
async function currentToolRound(tx, id) {
|
|
441
|
+
let cursor;
|
|
442
|
+
do {
|
|
443
|
+
const page = await tx.scanEntries({ conversationId: id }, 64, cursor);
|
|
444
|
+
for (const entry of page.items) {
|
|
445
|
+
const assistant = entry.model?.findLast((message) => message.role === "assistant");
|
|
446
|
+
if (assistant?.role === "assistant")
|
|
447
|
+
return assistant.content.some((block) => block.type === "toolCall") ? entry.id : undefined;
|
|
448
|
+
}
|
|
449
|
+
cursor = page.next;
|
|
450
|
+
} while (cursor !== undefined);
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
385
453
|
async function beginNoteWrite(tx, id, taskId) {
|
|
386
454
|
const receipt = await tx.doc(WriteReceipt, taskId);
|
|
387
455
|
if (receipt.attempted || receipt.file)
|
|
@@ -418,9 +486,11 @@ async function mutateNote(tx, input) {
|
|
|
418
486
|
nextCatalog.push(metadata);
|
|
419
487
|
else
|
|
420
488
|
nextCatalog[index] = metadata;
|
|
489
|
+
const assistantEntry = await currentToolRound(tx, input.conversationId);
|
|
421
490
|
const freshness = {
|
|
422
491
|
windowId,
|
|
423
492
|
userEntry,
|
|
493
|
+
...assistantEntry === undefined ? {} : { assistantEntry },
|
|
424
494
|
taskId: input.taskId,
|
|
425
495
|
updatedAt
|
|
426
496
|
};
|
|
@@ -442,7 +512,7 @@ function noteMetadata(file) {
|
|
|
442
512
|
async function renderNotesThreadHint(reader, id, context, maxBytes = 4000) {
|
|
443
513
|
const state = await reader.snapshot(NotesState, id, context);
|
|
444
514
|
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:";
|
|
515
|
+
const header = "Recent notes in virtual storage (up to 5, most-recent first). More may exist; use notes list or search:";
|
|
446
516
|
const lines = [];
|
|
447
517
|
for (const file of files) {
|
|
448
518
|
if (lines.length >= 5)
|
|
@@ -469,13 +539,24 @@ async function startInstruction(tx, id, owner, kind, content, now) {
|
|
|
469
539
|
return;
|
|
470
540
|
await tx.appendEntry(id, {
|
|
471
541
|
kind,
|
|
472
|
-
model: [
|
|
542
|
+
model: [
|
|
543
|
+
{ role: "system", content, timestamp: now },
|
|
544
|
+
{
|
|
545
|
+
role: "user",
|
|
546
|
+
content: "[Context management request] Carry out the context instructions above.",
|
|
547
|
+
timestamp: now
|
|
548
|
+
}
|
|
549
|
+
]
|
|
473
550
|
});
|
|
474
551
|
const generation = await tx.createTask(GenerationTask2, {}, {
|
|
475
552
|
ownership: { kind: "task", taskId: owner },
|
|
476
553
|
conversationId: id
|
|
477
554
|
});
|
|
478
|
-
(await tx.doc(LiveDoc2, id)).run = {
|
|
555
|
+
(await tx.doc(LiveDoc2, id)).run = {
|
|
556
|
+
taskId: generation,
|
|
557
|
+
inputs: [],
|
|
558
|
+
turns: 0
|
|
559
|
+
};
|
|
479
560
|
return generation;
|
|
480
561
|
}
|
|
481
562
|
async function waitInstruction(host, id, generation, context) {
|
|
@@ -1236,21 +1317,6 @@ import {
|
|
|
1236
1317
|
// packages/context/src/tool-contract.ts
|
|
1237
1318
|
import { Type } from "typebox";
|
|
1238
1319
|
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
1320
|
var contextOutputLimits = { maxBytes: Infinity, maxLines: Infinity };
|
|
1255
1321
|
function contextTextSlice(text, offset, limit) {
|
|
1256
1322
|
if (offset > 0 && (text.codePointAt(offset - 1) ?? 0) > 65535)
|
|
@@ -1275,7 +1341,13 @@ var target = Type.Optional(Type.String({
|
|
|
1275
1341
|
description: "Durable conversation ID; defaults to caller"
|
|
1276
1342
|
}));
|
|
1277
1343
|
var historyParameters = Type.Object({
|
|
1278
|
-
action: Type.Optional(Type.Union(
|
|
1344
|
+
action: Type.Optional(Type.Union([
|
|
1345
|
+
Type.Literal("help"),
|
|
1346
|
+
Type.Literal("list_windows"),
|
|
1347
|
+
Type.Literal("list"),
|
|
1348
|
+
Type.Literal("read"),
|
|
1349
|
+
Type.Literal("search")
|
|
1350
|
+
])),
|
|
1279
1351
|
target,
|
|
1280
1352
|
item_id: Type.Optional(Type.String()),
|
|
1281
1353
|
agent_name: Type.Optional(nullableString),
|
|
@@ -1300,7 +1372,14 @@ var historyParameters = Type.Object({
|
|
|
1300
1372
|
}))
|
|
1301
1373
|
}, { additionalProperties: false });
|
|
1302
1374
|
var notesParameters = Type.Object({
|
|
1303
|
-
action: Type.Optional(Type.Union(
|
|
1375
|
+
action: Type.Optional(Type.Union([
|
|
1376
|
+
Type.Literal("help"),
|
|
1377
|
+
Type.Literal("list"),
|
|
1378
|
+
Type.Literal("read"),
|
|
1379
|
+
Type.Literal("search"),
|
|
1380
|
+
Type.Literal("append"),
|
|
1381
|
+
Type.Literal("write")
|
|
1382
|
+
])),
|
|
1304
1383
|
target,
|
|
1305
1384
|
agent_name: Type.Optional(nullableString),
|
|
1306
1385
|
file_order: Type.Optional(Type.Union([Type.Literal("ascending"), Type.Literal("descending")])),
|
|
@@ -1312,7 +1391,7 @@ var notesParameters = Type.Object({
|
|
|
1312
1391
|
limit: Type.Optional(positiveInteger),
|
|
1313
1392
|
max_matches_per_file: Type.Optional(positiveInteger),
|
|
1314
1393
|
path: Type.Optional(Type.Union([Type.String(), Type.Null()], {
|
|
1315
|
-
description: "
|
|
1394
|
+
description: "Virtual note path, not a project file; prefix for list/search"
|
|
1316
1395
|
})),
|
|
1317
1396
|
query: Type.Optional(Type.String()),
|
|
1318
1397
|
recent_file_first: Type.Optional(Type.Boolean()),
|
|
@@ -1322,11 +1401,16 @@ var notesParameters = Type.Object({
|
|
|
1322
1401
|
offset_chars: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
1323
1402
|
text: Type.Optional(Type.String())
|
|
1324
1403
|
}, { additionalProperties: false });
|
|
1325
|
-
var newContextParameters = Type.Object({
|
|
1404
|
+
var newContextParameters = Type.Object({
|
|
1405
|
+
role: Type.Optional(Type.String({
|
|
1406
|
+
minLength: 1,
|
|
1407
|
+
description: "Configured model-role ID, not an agent name or handoff text"
|
|
1408
|
+
}))
|
|
1409
|
+
}, { additionalProperties: false });
|
|
1326
1410
|
function prepareNewContextArguments(input) {
|
|
1327
1411
|
const args = input ?? {};
|
|
1328
1412
|
if (!Check(newContextParameters, args))
|
|
1329
|
-
throw new Error('Use {} to keep the current
|
|
1413
|
+
throw new Error('Use {} to keep the current role, or {role: "name"} for a configured model-role ID.');
|
|
1330
1414
|
return args;
|
|
1331
1415
|
}
|
|
1332
1416
|
function prepareNotesArguments(input) {
|
|
@@ -1385,6 +1469,7 @@ function contextToolHelp(namespace, args, rankedHistory = false) {
|
|
|
1385
1469
|
throw new Error("Help accepts only action: help");
|
|
1386
1470
|
const fields = namespace === "notes" ? notesFields : historyFields;
|
|
1387
1471
|
return {
|
|
1472
|
+
...namespace === "notes" ? { results: "read: file.content; write/append: file.path" } : {},
|
|
1388
1473
|
actions: Object.fromEntries(Object.entries(fields).map(([action, names]) => [
|
|
1389
1474
|
action,
|
|
1390
1475
|
names.map((name) => (name === "path" ? ["read", "write", "append"].includes(action) : ["text", "query", "item_id"].includes(name)) || action === "read" && name === "window_id" ? name : `${name}?`).join(" ")
|
|
@@ -1392,13 +1477,13 @@ function contextToolHelp(namespace, args, rankedHistory = false) {
|
|
|
1392
1477
|
target: "Durable conversation ID; defaults to caller; reads require the same Context visibility group; write own",
|
|
1393
1478
|
...namespace === "notes" ? {
|
|
1394
1479
|
writes: "write replaces; append adds",
|
|
1395
|
-
paths: "
|
|
1480
|
+
paths: "Virtual note paths, inaccessible to filesystem tools. Relative to /notes; target selects a conversation, read-only unless your own",
|
|
1396
1481
|
usage: '{ "action": "read", "path": "checkpoint" }',
|
|
1397
1482
|
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
1483
|
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
1484
|
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
1485
|
} : {
|
|
1401
|
-
usage: "Search
|
|
1486
|
+
usage: "With query, action defaults to search. Search past chat, don't browse it. Pass returned IDs unchanged",
|
|
1402
1487
|
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
1488
|
}
|
|
1404
1489
|
};
|
|
@@ -1628,7 +1713,7 @@ var refreshFailures = new WeakMap;
|
|
|
1628
1713
|
function createHistoryTool(options) {
|
|
1629
1714
|
const tool = defineTool({
|
|
1630
1715
|
name: "history",
|
|
1631
|
-
description: "Search
|
|
1716
|
+
description: "Search past chat",
|
|
1632
1717
|
parameters: historyParameters,
|
|
1633
1718
|
structuredOutputSchema: Type2.Object({}, { additionalProperties: true }),
|
|
1634
1719
|
prepareArguments: prepareHistoryArguments,
|
|
@@ -1885,6 +1970,75 @@ async function refreshRankedHistory(conversation, ranked, context) {
|
|
|
1885
1970
|
}
|
|
1886
1971
|
}
|
|
1887
1972
|
|
|
1973
|
+
// packages/context/src/input-placement.ts
|
|
1974
|
+
async function waitForInputPlacement(host, id, context) {
|
|
1975
|
+
const requestId = `context:input:${id}`;
|
|
1976
|
+
let revision = 0;
|
|
1977
|
+
let closing = false;
|
|
1978
|
+
let wake;
|
|
1979
|
+
const changed = () => {
|
|
1980
|
+
revision++;
|
|
1981
|
+
wake?.();
|
|
1982
|
+
};
|
|
1983
|
+
const observation = host.harness.observeCommits({
|
|
1984
|
+
advance(publication) {
|
|
1985
|
+
if (publication.changes.some((change) => change.type === "task" && change.value.id === id || change.type === "submission" && change.value.requestId === requestId))
|
|
1986
|
+
changed();
|
|
1987
|
+
},
|
|
1988
|
+
end() {
|
|
1989
|
+
closing = true;
|
|
1990
|
+
changed();
|
|
1991
|
+
}
|
|
1992
|
+
});
|
|
1993
|
+
try {
|
|
1994
|
+
while (true) {
|
|
1995
|
+
context.abortSignal?.throwIfAborted();
|
|
1996
|
+
if (closing)
|
|
1997
|
+
throw new Error("Context host closed before input placement was observed");
|
|
1998
|
+
const before = revision;
|
|
1999
|
+
const task = await host.harness.getTask(id, context);
|
|
2000
|
+
if (!task || task.kind !== INPUT_TASK)
|
|
2001
|
+
throw new Error("Input task does not belong to Context management");
|
|
2002
|
+
const submission = await host.harness.commit((tx) => tx.submissionByRequest(task.conversationId, requestId), context);
|
|
2003
|
+
if (submission)
|
|
2004
|
+
return { status: "submitted", submissionId: submission.id };
|
|
2005
|
+
if (task.state.status === "terminal" || task.state.status === "completing") {
|
|
2006
|
+
const outcome = task.state.outcome;
|
|
2007
|
+
if (outcome.status === "aborted")
|
|
2008
|
+
return {
|
|
2009
|
+
status: "aborted",
|
|
2010
|
+
...outcome.reason ? { reason: outcome.reason } : {}
|
|
2011
|
+
};
|
|
2012
|
+
return {
|
|
2013
|
+
status: "failed",
|
|
2014
|
+
message: outcome.status === "failed" || outcome.status === "faulted" ? outcome.error.message : outcome.status === "orphaned" ? outcome.reason : "Managed input completed without a native submission receipt"
|
|
2015
|
+
};
|
|
2016
|
+
}
|
|
2017
|
+
if (revision !== before)
|
|
2018
|
+
continue;
|
|
2019
|
+
await new Promise((resolve, reject) => {
|
|
2020
|
+
const signal = context.abortSignal;
|
|
2021
|
+
const abort = () => {
|
|
2022
|
+
wake = undefined;
|
|
2023
|
+
reject(signal?.reason);
|
|
2024
|
+
};
|
|
2025
|
+
wake = () => {
|
|
2026
|
+
signal?.removeEventListener("abort", abort);
|
|
2027
|
+
wake = undefined;
|
|
2028
|
+
resolve();
|
|
2029
|
+
};
|
|
2030
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
2031
|
+
if (signal?.aborted)
|
|
2032
|
+
abort();
|
|
2033
|
+
else if (revision !== before || closing)
|
|
2034
|
+
wake();
|
|
2035
|
+
});
|
|
2036
|
+
}
|
|
2037
|
+
} finally {
|
|
2038
|
+
observation.detach();
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
|
|
1888
2042
|
// packages/context/src/notes.ts
|
|
1889
2043
|
import {
|
|
1890
2044
|
defineTool as defineTool2
|
|
@@ -1924,7 +2078,7 @@ function normalize(input, prefix) {
|
|
|
1924
2078
|
function createNotesTool(options) {
|
|
1925
2079
|
const tool = defineTool2({
|
|
1926
2080
|
name: "notes",
|
|
1927
|
-
description: "
|
|
2081
|
+
description: "Virtual filesystem task checkpoints",
|
|
1928
2082
|
parameters: notesParameters,
|
|
1929
2083
|
structuredOutputSchema: Type3.Object({}, { additionalProperties: true }),
|
|
1930
2084
|
prepareArguments: prepareNotesArguments,
|
|
@@ -2095,7 +2249,7 @@ async function readRoles(catalog, id, context) {
|
|
|
2095
2249
|
reasoning
|
|
2096
2250
|
}));
|
|
2097
2251
|
}
|
|
2098
|
-
async function renderModelRoles(catalog, id, context) {
|
|
2252
|
+
async function renderModelRoles(catalog, id, agent, context) {
|
|
2099
2253
|
let roles;
|
|
2100
2254
|
try {
|
|
2101
2255
|
roles = await readRoles(catalog, id, context);
|
|
@@ -2105,8 +2259,11 @@ async function renderModelRoles(catalog, id, context) {
|
|
|
2105
2259
|
}
|
|
2106
2260
|
if (!roles.length)
|
|
2107
2261
|
return "No model roles are available. Call new_context without role.";
|
|
2262
|
+
const matching = roles.filter((role) => role.provider === agent?.model?.provider && role.model === agent?.model?.modelId && role.reasoning === (agent?.thinkingLevel ?? "off")).map((role) => role.id);
|
|
2263
|
+
const currentRole = matching.length === 0 ? "none (no matching preset)" : matching.length === 1 ? matching.join(", ") : `ambiguous (${matching.join(", ")})`;
|
|
2108
2264
|
return [
|
|
2109
|
-
|
|
2265
|
+
`Current role: ${currentRole}`,
|
|
2266
|
+
'Roles are user preferences, not capability limits. Switch for a clear, sustained change of task or scope, not a single specialised prompt. Any role can do general work. Consider an available subagent for a bounded specialist detour. Save notes, then call new_context({role: "name"}); omit role to keep the current role.',
|
|
2110
2267
|
...roles.map((role) => `- ${role.id}: ${role.description}`)
|
|
2111
2268
|
].join(`
|
|
2112
2269
|
`);
|
|
@@ -2199,9 +2356,9 @@ function reportedTokens(message) {
|
|
|
2199
2356
|
function checkpointGuidance(newContextRequests) {
|
|
2200
2357
|
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.";
|
|
2201
2358
|
return [
|
|
2202
|
-
"Notes are recovery state, not a diary.
|
|
2203
|
-
`
|
|
2204
|
-
"
|
|
2359
|
+
"Notes are recovery state, not a diary. Virtual note paths are inaccessible to filesystem tools. Do not store project files or deliverables there. Create notes with relative paths. Maintain one authoritative checkpoint per task or topic with request, constraints, decisions, status, next steps and relevant history IDs. Use notes write to create or replace stale state at milestones, task switches and completion; use append to add to it. Link existing notes instead of duplicating content. Recording does not authorise implementation.",
|
|
2360
|
+
`Do not save every reply or intermediate step. ${rollover} Before handoffs, save the checkpoint and wait for success; include its path. Subagents must maintain their own notes and return paths. After rollover, use notes read to recover the checkpoint, then only necessary links. Do not reread unchanged notes. Use history for missing details.`,
|
|
2361
|
+
"Skill reads do not survive rollover. Reread required skills."
|
|
2205
2362
|
].join(`
|
|
2206
2363
|
|
|
2207
2364
|
`);
|
|
@@ -2223,7 +2380,7 @@ function createContextPolicy(options) {
|
|
|
2223
2380
|
const sections = [
|
|
2224
2381
|
section("context", () => checkpointGuidance(options.newContextRequests)),
|
|
2225
2382
|
...options.newContextRequests === "off" || !options.modelRoles ? [] : [
|
|
2226
|
-
section("context-roles", (input, context) => renderModelRoles(options.modelRoles, input.conversationId, context))
|
|
2383
|
+
section("context-roles", async (input, context) => renderModelRoles(options.modelRoles, input.conversationId, input.agent, context))
|
|
2227
2384
|
],
|
|
2228
2385
|
section("context-state", async (input, context) => {
|
|
2229
2386
|
const [state, hints] = await Promise.all([
|
|
@@ -2364,7 +2521,7 @@ var ToolWindow = defineDoc7({
|
|
|
2364
2521
|
function createToolRollover(host, now, policy) {
|
|
2365
2522
|
const tool = defineTool4({
|
|
2366
2523
|
name: "new_context",
|
|
2367
|
-
description: "Start fresh
|
|
2524
|
+
description: "Start fresh context window. Must save notes first and call alone",
|
|
2368
2525
|
parameters: newContextParameters,
|
|
2369
2526
|
prepareArguments: prepareNewContextArguments,
|
|
2370
2527
|
replay: "safe",
|
|
@@ -2404,7 +2561,7 @@ function createToolRollover(host, now, policy) {
|
|
|
2404
2561
|
throw new Error("Context window is missing or a checkpoint is already in progress");
|
|
2405
2562
|
if (role && !await roleSourceMatches(tx, api.conversationId, role))
|
|
2406
2563
|
throw new Error("The model settings changed. Continue here and request a new role handoff if still needed.");
|
|
2407
|
-
if (!await notesAreFresh(tx, api.conversationId))
|
|
2564
|
+
if (!await notesAreFresh(tx, api.conversationId) || !await notesPrecedeRequest(tx, api.conversationId, api.taskId))
|
|
2408
2565
|
return {
|
|
2409
2566
|
status: "checkpoint_required",
|
|
2410
2567
|
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."
|
|
@@ -2441,7 +2598,7 @@ function createToolRollover(host, now, policy) {
|
|
|
2441
2598
|
const state = await tx.doc(WindowState, api.conversationId);
|
|
2442
2599
|
const slot = live.tools?.[0];
|
|
2443
2600
|
const generation = await tx.task(api.taskId);
|
|
2444
|
-
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);
|
|
2601
|
+
return live.run?.taskId === api.taskId && !generation?.abortRequested && live.tools?.length === 1 && slot?.taskId === receipt.request.tool && slot.status === "done" && slot.entry !== undefined && inbox.items.length === 0 && !state.transition && state.window?.id === receipt.request.window.previous && await notesAreFresh(tx, api.conversationId) && await notesPrecedeRequest(tx, api.conversationId, receipt.request.tool) && (!receipt.request.role || await roleSourceMatches(tx, api.conversationId, receipt.request.role)) && (await foreignTasks(tx, api.conversationId)).every((id) => id === api.taskId);
|
|
2445
2602
|
};
|
|
2446
2603
|
const preparation = await prepareRollover(conv, api.taskId, policy.beforeRollover, {
|
|
2447
2604
|
conversationId: api.conversationId,
|
|
@@ -2481,7 +2638,14 @@ function createToolRollover(host, now, policy) {
|
|
|
2481
2638
|
|
|
2482
2639
|
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.",
|
|
2483
2640
|
timestamp: now()
|
|
2484
|
-
}
|
|
2641
|
+
},
|
|
2642
|
+
...safe ? [
|
|
2643
|
+
{
|
|
2644
|
+
role: "user",
|
|
2645
|
+
content: "[Context management request] Resume from your saved checkpoint.",
|
|
2646
|
+
timestamp: now()
|
|
2647
|
+
}
|
|
2648
|
+
] : []
|
|
2485
2649
|
]
|
|
2486
2650
|
});
|
|
2487
2651
|
}, context);
|
|
@@ -2580,6 +2744,10 @@ function createContextManagement(options) {
|
|
|
2580
2744
|
if (binding?.harness === harness)
|
|
2581
2745
|
binding = undefined;
|
|
2582
2746
|
},
|
|
2747
|
+
async rejoin(id, requestId, context) {
|
|
2748
|
+
const receipt = await host().harness.snapshot(InputReceipt, id, requestId, context);
|
|
2749
|
+
return receipt?.task;
|
|
2750
|
+
},
|
|
2583
2751
|
async submit(id, draft, context) {
|
|
2584
2752
|
await ensureWindow(id, context);
|
|
2585
2753
|
const conv = await conversation(host(), id, context);
|
|
@@ -2607,6 +2775,9 @@ function createContextManagement(options) {
|
|
|
2607
2775
|
host().harness.resume();
|
|
2608
2776
|
return task;
|
|
2609
2777
|
},
|
|
2778
|
+
waitForSubmission(task, context) {
|
|
2779
|
+
return waitForInputPlacement(host(), task, context);
|
|
2780
|
+
},
|
|
2610
2781
|
async retry(id, context) {
|
|
2611
2782
|
const conv = await conversation(host(), id, context);
|
|
2612
2783
|
await conv.commit(async (tx) => {
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type ComponentInstance, type ComponentRequest } from "@howaboua/pi-durable-components";
|
|
2
|
+
import { createContextManagement } from "./index.ts";
|
|
3
|
+
type Management = ReturnType<typeof createContextManagement>;
|
|
4
|
+
/** Optional advanced hooks. Ordinary hosts need only their shared Models grant. */
|
|
5
|
+
export declare const contextOptions: import("@howaboua/pi-durable-components").ComponentCapability<{
|
|
6
|
+
models: import("@earendil-works/pi-ai").Models;
|
|
7
|
+
archiveHistory?: boolean;
|
|
8
|
+
rankedHistory?: import("./history-ranker.ts").RankedHistory;
|
|
9
|
+
beforeRollover?: import("./rollover-preparation.ts").BeforeRollover;
|
|
10
|
+
modelRoles?: import("./model-roles.ts").ContextModelRoles;
|
|
11
|
+
remote?: import("./remote.ts").ContextRemoteCatalog;
|
|
12
|
+
now?: () => number;
|
|
13
|
+
newContextRequests?: import("./index.ts").NewContextRequests;
|
|
14
|
+
hasEligibleContextHistory?: (conversationId: import("@earendil-works/pi-durable").ConversationId, context: import("@earendil-works/chord").Context) => boolean | Promise<boolean>;
|
|
15
|
+
automaticIdleRollover?: boolean;
|
|
16
|
+
idleRolloverMinutes?: 0 | 5 | 15 | 25 | 55 | 115 | 355 | 715;
|
|
17
|
+
taskBoundaryReminderTokens?: number;
|
|
18
|
+
}>;
|
|
19
|
+
export declare function createComponent(request: ComponentRequest): ComponentInstance<Management>;
|
|
20
|
+
export {};
|
|
@@ -18,6 +18,7 @@ export declare function createInput(host: () => ContextHost, rollover: ReturnTyp
|
|
|
18
18
|
readonly type: "input";
|
|
19
19
|
readonly content: import("@earendil-works/pi-durable").UserInput;
|
|
20
20
|
readonly whenBusy?: "steer" | "followUp" | "reject";
|
|
21
|
+
readonly whenIdle?: "reject";
|
|
21
22
|
readonly entry?: import("@earendil-works/pi-durable").InputEntry;
|
|
22
23
|
}, InputState, InputResult, object>;
|
|
23
24
|
export {};
|
|
@@ -13,7 +13,7 @@ export declare function createHistoryTool(options: {
|
|
|
13
13
|
name: string;
|
|
14
14
|
description: string;
|
|
15
15
|
parameters: Type.TObject<{
|
|
16
|
-
action: Type.TOptional<Type.TUnion<Type.TLiteral<"help"
|
|
16
|
+
action: Type.TOptional<Type.TUnion<[Type.TLiteral<"help">, Type.TLiteral<"list_windows">, Type.TLiteral<"list">, Type.TLiteral<"read">, Type.TLiteral<"search">]>>;
|
|
17
17
|
target: Type.TOptional<Type.TString>;
|
|
18
18
|
item_id: Type.TOptional<Type.TString>;
|
|
19
19
|
agent_name: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
|
|
@@ -32,7 +32,7 @@ export declare function createHistoryTool(options: {
|
|
|
32
32
|
replay?: "safe" | "unsafe";
|
|
33
33
|
executionMode?: import("@earendil-works/pi-durable").ToolExecutionMode;
|
|
34
34
|
prepareArguments?(args: unknown): {
|
|
35
|
-
action?:
|
|
35
|
+
action?: "help" | "list" | "list_windows" | "read" | "search";
|
|
36
36
|
target?: string;
|
|
37
37
|
item_id?: string;
|
|
38
38
|
agent_name?: string | null;
|
|
@@ -47,7 +47,7 @@ export declare function createHistoryTool(options: {
|
|
|
47
47
|
tool_namespace?: string | null;
|
|
48
48
|
window_id?: string | null;
|
|
49
49
|
};
|
|
50
|
-
structuredOutputSchema?:
|
|
50
|
+
structuredOutputSchema?: object;
|
|
51
51
|
callers?: readonly ("model" | "tools")[];
|
|
52
52
|
deferred?: true;
|
|
53
53
|
outputLimits?: {
|
|
@@ -56,7 +56,7 @@ export declare function createHistoryTool(options: {
|
|
|
56
56
|
readonly retain?: "head" | "tail";
|
|
57
57
|
};
|
|
58
58
|
execute(args: {
|
|
59
|
-
action?:
|
|
59
|
+
action?: "help" | "list" | "list_windows" | "read" | "search";
|
|
60
60
|
target?: string;
|
|
61
61
|
item_id?: string;
|
|
62
62
|
agent_name?: string | null;
|
|
@@ -43,8 +43,12 @@ export declare function createContextManagement(options: {
|
|
|
43
43
|
bind(harness: Harness, storage: Storage): void;
|
|
44
44
|
/** Release only after draining host calls and closing this Harness and its task invocations. */
|
|
45
45
|
unbind(harness: Harness): void;
|
|
46
|
+
/** Read an existing receipt without opening a window, creating a document or resuming work. */
|
|
47
|
+
rejoin(id: ConversationId, requestId: string, context: Context): Promise<TaskId<InputResult> | undefined>;
|
|
46
48
|
submit(id: ConversationId, draft: InputSubmissionDraft, context: Context): Promise<TaskId<InputResult>>;
|
|
47
49
|
newContext(id: ConversationId, context: Context): Promise<TaskId<import("./window-state.ts").TransitionResult>>;
|
|
50
|
+
/** Resolves at native admission, before the turn's final answer. Observation cancellation leaves work owned. */
|
|
51
|
+
waitForSubmission(task: TaskId<InputResult>, context: Context): Promise<import("@howaboua/pi-durable-components").ComponentInputPlacement>;
|
|
48
52
|
retry(id: ConversationId, context: Context): Promise<void>;
|
|
49
53
|
status(id: ConversationId, context: Context): Promise<{
|
|
50
54
|
window: Readonly<{
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Context } from "@earendil-works/chord";
|
|
2
|
+
import type { TaskId } from "@earendil-works/pi-durable";
|
|
3
|
+
import type { ComponentInputPlacement } from "@howaboua/pi-durable-components";
|
|
4
|
+
import { type ContextHost, type InputResult } from "./lifecycle.ts";
|
|
5
|
+
/** Observe this component's native receipt, not its final answer or private checkpoint layout. */
|
|
6
|
+
export declare function waitForInputPlacement(host: ContextHost, id: TaskId<InputResult>, context: Context): Promise<ComponentInputPlacement>;
|
|
@@ -20,7 +20,7 @@ export type PreparedRole = {
|
|
|
20
20
|
thinkingLevel: ModelThinkingLevel;
|
|
21
21
|
};
|
|
22
22
|
};
|
|
23
|
-
export declare function renderModelRoles(catalog: ContextModelRoles | undefined, id: ConversationId, context: Context): Promise<string>;
|
|
23
|
+
export declare function renderModelRoles(catalog: ContextModelRoles | undefined, id: ConversationId, agent: Pick<Agent, "model" | "thinkingLevel">, context: Context): Promise<string>;
|
|
24
24
|
export declare function prepareRole(catalog: ContextModelRoles | undefined, id: string, conversationId: ConversationId, source: Agent, models: Models, context: Context): Promise<PreparedRole>;
|
|
25
25
|
/** Checked in the same transaction as the model selection and window cut. */
|
|
26
26
|
export declare function roleSourceMatches(tx: Tx, id: ConversationId, role: PreparedRole): Promise<boolean>;
|
|
@@ -10,6 +10,7 @@ export type NoteMetadata = {
|
|
|
10
10
|
type NoteFreshness = {
|
|
11
11
|
windowId: string;
|
|
12
12
|
userEntry: EntryId | null;
|
|
13
|
+
assistantEntry?: EntryId;
|
|
13
14
|
taskId: TaskId;
|
|
14
15
|
updatedAt: number;
|
|
15
16
|
};
|
|
@@ -31,6 +32,8 @@ export type SavedNote = {
|
|
|
31
32
|
export declare function readSavedNotes(storage: Storage, conversationId: ConversationId, context: Context): Promise<SavedNote[]>;
|
|
32
33
|
export declare function readNoteText(tx: Tx, id: ConversationId, path: string): Promise<string>;
|
|
33
34
|
export declare function notesAreFresh(tx: Tx, id: ConversationId): Promise<boolean>;
|
|
35
|
+
/** A requested cut needs a completed save in the immediately preceding native tool round. */
|
|
36
|
+
export declare function notesPrecedeRequest(tx: Tx, id: ConversationId, request: TaskId): Promise<boolean>;
|
|
34
37
|
/** Commit before validation/mutation so a rejected replacement cannot reuse an older save. */
|
|
35
38
|
export declare function beginNoteWrite(tx: Tx, id: ConversationId, taskId: TaskId): Promise<void>;
|
|
36
39
|
/** Receipt, body, catalog and freshness commit together under the original task identity. */
|
|
@@ -9,7 +9,7 @@ export declare function createNotesTool(options: {
|
|
|
9
9
|
name: string;
|
|
10
10
|
description: string;
|
|
11
11
|
parameters: Type.TObject<{
|
|
12
|
-
action: Type.TOptional<Type.TUnion<Type.TLiteral<"
|
|
12
|
+
action: Type.TOptional<Type.TUnion<[Type.TLiteral<"help">, Type.TLiteral<"list">, Type.TLiteral<"read">, Type.TLiteral<"search">, Type.TLiteral<"append">, Type.TLiteral<"write">]>>;
|
|
13
13
|
target: Type.TOptional<Type.TString>;
|
|
14
14
|
agent_name: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
|
|
15
15
|
file_order: Type.TOptional<Type.TUnion<[Type.TLiteral<"ascending">, Type.TLiteral<"descending">]>>;
|
|
@@ -29,7 +29,7 @@ export declare function createNotesTool(options: {
|
|
|
29
29
|
replay?: "safe" | "unsafe";
|
|
30
30
|
executionMode?: import("@earendil-works/pi-durable").ToolExecutionMode;
|
|
31
31
|
prepareArguments?(args: unknown): {
|
|
32
|
-
action?:
|
|
32
|
+
action?: "append" | "help" | "list" | "read" | "search" | "write";
|
|
33
33
|
target?: string;
|
|
34
34
|
agent_name?: string | null;
|
|
35
35
|
file_order?: "ascending" | "descending";
|
|
@@ -45,7 +45,7 @@ export declare function createNotesTool(options: {
|
|
|
45
45
|
offset_chars?: number;
|
|
46
46
|
text?: string;
|
|
47
47
|
};
|
|
48
|
-
structuredOutputSchema?:
|
|
48
|
+
structuredOutputSchema?: object;
|
|
49
49
|
callers?: readonly ("model" | "tools")[];
|
|
50
50
|
deferred?: true;
|
|
51
51
|
outputLimits?: {
|
|
@@ -54,7 +54,7 @@ export declare function createNotesTool(options: {
|
|
|
54
54
|
readonly retain?: "head" | "tail";
|
|
55
55
|
};
|
|
56
56
|
execute(args: {
|
|
57
|
-
action?:
|
|
57
|
+
action?: "append" | "help" | "list" | "read" | "search" | "write";
|
|
58
58
|
target?: string;
|
|
59
59
|
agent_name?: string | null;
|
|
60
60
|
file_order?: "ascending" | "descending";
|