@howaboua/pi-durable-context 0.10.0 → 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 +146 -50
- package/dist/index.js +146 -50
- 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/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 +5 -5
package/README.md
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
Continue long conversations through saved notes and clean context windows. Notes, retained history, pending input and rollover progress live in the same SQLite database as your Durable conversation. No Codex account or provider-specific storage is required.
|
|
4
4
|
|
|
5
|
-
Requires Node 22.19 or newer and Durable 1.
|
|
5
|
+
Requires Node 22.19 or newer and Durable 1.5.0.
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
|
-
npm install https://github.com/IgorWarzocha/pi-durable-components/releases/download/v0.
|
|
8
|
+
npm install https://github.com/IgorWarzocha/pi-durable-components/releases/download/v0.11.0/howaboua-pi-durable-context-0.11.0.tgz
|
|
9
9
|
```
|
|
10
10
|
|
|
11
11
|
## Connect your host
|
package/dist/activation.js
CHANGED
|
@@ -144,8 +144,12 @@ async function until(watch, predicate, signal) {
|
|
|
144
144
|
await new Promise((resolve, reject) => {
|
|
145
145
|
abort = () => reject(signal.reason);
|
|
146
146
|
signal.addEventListener("abort", abort, { once: true });
|
|
147
|
-
watch.start(async (
|
|
148
|
-
if (
|
|
147
|
+
watch.start(async (call) => {
|
|
148
|
+
if (call.kind === "failed") {
|
|
149
|
+
reject(call.error);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (predicate(call.value))
|
|
149
153
|
resolve();
|
|
150
154
|
});
|
|
151
155
|
if (signal.aborted)
|
|
@@ -153,8 +157,8 @@ async function until(watch, predicate, signal) {
|
|
|
153
157
|
else if (watch.value && predicate(watch.value))
|
|
154
158
|
resolve();
|
|
155
159
|
watch.closed.then((end) => {
|
|
156
|
-
if (end.
|
|
157
|
-
reject(new Error(`Context watch ended: ${end.
|
|
160
|
+
if (end.kind !== "stopped")
|
|
161
|
+
reject(end.kind === "failed" || end.kind === "listener_error" ? end.error : new Error(`Context watch ended: ${end.kind}`));
|
|
158
162
|
});
|
|
159
163
|
});
|
|
160
164
|
} finally {
|
|
@@ -241,13 +245,18 @@ function normalizeQueryInput(namespace, input) {
|
|
|
241
245
|
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
242
246
|
throw new Error("Supply an action object; use {} for help");
|
|
243
247
|
const params = { ...input };
|
|
248
|
+
if (namespace === "history" && params["action"] === undefined && "query" in params)
|
|
249
|
+
params["action"] = "search";
|
|
244
250
|
const aliases = actions[namespace];
|
|
245
251
|
const action = aliases[String(params["action"])] ?? params["action"];
|
|
246
252
|
if (action !== undefined)
|
|
247
253
|
params["action"] = action;
|
|
248
254
|
if (namespace === "notes") {
|
|
249
|
-
|
|
255
|
+
alias(params, "address", "path");
|
|
256
|
+
if (action === "write" || action === "append") {
|
|
250
257
|
alias(params, "content", "text");
|
|
258
|
+
alias(params, "body", "text");
|
|
259
|
+
}
|
|
251
260
|
if (action === "list" || action === "search") {
|
|
252
261
|
alias(params, "prefix", "path");
|
|
253
262
|
alias(params, "path_prefix", "path");
|
|
@@ -260,6 +269,8 @@ function normalizeQueryInput(namespace, input) {
|
|
|
260
269
|
alias(params, "max_results", "limit");
|
|
261
270
|
}
|
|
262
271
|
const used = usedPresentation[`${namespace}:${String(action)}`] ?? [];
|
|
272
|
+
if (namespace === "history" && action !== "read")
|
|
273
|
+
delete params["offset_chars"];
|
|
263
274
|
for (const hint of presentation)
|
|
264
275
|
if (!used.includes(hint))
|
|
265
276
|
delete params[hint];
|
|
@@ -365,6 +376,63 @@ async function notesAreFresh(tx, id) {
|
|
|
365
376
|
} while (cursor !== undefined);
|
|
366
377
|
return true;
|
|
367
378
|
}
|
|
379
|
+
async function notesPrecedeRequest(tx, id, request) {
|
|
380
|
+
const saved = (await tx.doc(NotesState, id)).lastWrite;
|
|
381
|
+
const requesting = await tx.task(request);
|
|
382
|
+
if (!saved || requesting?.kind !== ToolTask.definition.name)
|
|
383
|
+
return false;
|
|
384
|
+
const input = requesting.input;
|
|
385
|
+
if (input.kind === "nested")
|
|
386
|
+
return false;
|
|
387
|
+
let owner = saved.taskId;
|
|
388
|
+
let savedAssistant = saved.assistantEntry;
|
|
389
|
+
while (owner !== undefined) {
|
|
390
|
+
const task = await tx.task(owner);
|
|
391
|
+
if (!task || task.kind === GenerationTask.definition.name)
|
|
392
|
+
break;
|
|
393
|
+
if (task.kind === ToolTask.definition.name) {
|
|
394
|
+
const call = task.input;
|
|
395
|
+
if (call.kind !== "nested")
|
|
396
|
+
savedAssistant = call.assistant;
|
|
397
|
+
}
|
|
398
|
+
owner = task.owner;
|
|
399
|
+
}
|
|
400
|
+
if (savedAssistant === undefined)
|
|
401
|
+
return false;
|
|
402
|
+
const completed = new Map;
|
|
403
|
+
let cursor;
|
|
404
|
+
do {
|
|
405
|
+
const page = await tx.scanEntries({ conversationId: id, maxEntryId: input.assistant }, 64, cursor);
|
|
406
|
+
for (const entry of page.items) {
|
|
407
|
+
if (entry.id === input.assistant)
|
|
408
|
+
continue;
|
|
409
|
+
for (const message of entry.model ?? []) {
|
|
410
|
+
if (message.role === "toolResult")
|
|
411
|
+
completed.set(message.toolCallId, !message.isError);
|
|
412
|
+
if (message.role !== "assistant")
|
|
413
|
+
continue;
|
|
414
|
+
const calls = message.content.filter((block) => block.type === "toolCall");
|
|
415
|
+
if (calls.length)
|
|
416
|
+
return entry.id === savedAssistant && calls.every((call) => completed.has(call.id) && (call.name !== "notes" || !isNoteWrite(call.arguments) || completed.get(call.id) === true));
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
cursor = page.next;
|
|
420
|
+
} while (cursor !== undefined);
|
|
421
|
+
return false;
|
|
422
|
+
}
|
|
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
|
+
}
|
|
368
436
|
async function beginNoteWrite(tx, id, taskId) {
|
|
369
437
|
const receipt = await tx.doc(WriteReceipt, taskId);
|
|
370
438
|
if (receipt.attempted || receipt.file)
|
|
@@ -401,9 +469,11 @@ async function mutateNote(tx, input) {
|
|
|
401
469
|
nextCatalog.push(metadata);
|
|
402
470
|
else
|
|
403
471
|
nextCatalog[index] = metadata;
|
|
472
|
+
const assistantEntry = await currentToolRound(tx, input.conversationId);
|
|
404
473
|
const freshness = {
|
|
405
474
|
windowId,
|
|
406
475
|
userEntry,
|
|
476
|
+
...assistantEntry === undefined ? {} : { assistantEntry },
|
|
407
477
|
taskId: input.taskId,
|
|
408
478
|
updatedAt
|
|
409
479
|
};
|
|
@@ -425,7 +495,7 @@ function noteMetadata(file) {
|
|
|
425
495
|
async function renderNotesThreadHint(reader, id, context, maxBytes = 4000) {
|
|
426
496
|
const state = await reader.snapshot(NotesState, id, context);
|
|
427
497
|
const files = [...state?.files ?? []].sort((left, right) => right.updatedAt - left.updatedAt || left.path.localeCompare(right.path));
|
|
428
|
-
const header = "Recent notes (up to 5, most-recent first). More may exist; use notes list or search:";
|
|
498
|
+
const header = "Recent notes in virtual storage (up to 5, most-recent first). More may exist; use notes list or search:";
|
|
429
499
|
const lines = [];
|
|
430
500
|
for (const file of files) {
|
|
431
501
|
if (lines.length >= 5)
|
|
@@ -452,13 +522,24 @@ async function startInstruction(tx, id, owner, kind, content, now) {
|
|
|
452
522
|
return;
|
|
453
523
|
await tx.appendEntry(id, {
|
|
454
524
|
kind,
|
|
455
|
-
model: [
|
|
525
|
+
model: [
|
|
526
|
+
{ role: "system", content, timestamp: now },
|
|
527
|
+
{
|
|
528
|
+
role: "user",
|
|
529
|
+
content: "[Context management request] Carry out the context instructions above.",
|
|
530
|
+
timestamp: now
|
|
531
|
+
}
|
|
532
|
+
]
|
|
456
533
|
});
|
|
457
534
|
const generation = await tx.createTask(GenerationTask2, {}, {
|
|
458
535
|
ownership: { kind: "task", taskId: owner },
|
|
459
536
|
conversationId: id
|
|
460
537
|
});
|
|
461
|
-
(await tx.doc(LiveDoc2, id)).run = {
|
|
538
|
+
(await tx.doc(LiveDoc2, id)).run = {
|
|
539
|
+
taskId: generation,
|
|
540
|
+
inputs: [],
|
|
541
|
+
turns: 0
|
|
542
|
+
};
|
|
462
543
|
return generation;
|
|
463
544
|
}
|
|
464
545
|
async function waitInstruction(host, id, generation, context) {
|
|
@@ -1219,21 +1300,6 @@ import {
|
|
|
1219
1300
|
// packages/context/src/tool-contract.ts
|
|
1220
1301
|
import { Type } from "typebox";
|
|
1221
1302
|
import { Check } from "typebox/value";
|
|
1222
|
-
var HISTORY_ACTIONS = [
|
|
1223
|
-
"help",
|
|
1224
|
-
"list_windows",
|
|
1225
|
-
"list",
|
|
1226
|
-
"read",
|
|
1227
|
-
"search"
|
|
1228
|
-
];
|
|
1229
|
-
var NOTES_ACTIONS = [
|
|
1230
|
-
"help",
|
|
1231
|
-
"list",
|
|
1232
|
-
"read",
|
|
1233
|
-
"search",
|
|
1234
|
-
"append",
|
|
1235
|
-
"write"
|
|
1236
|
-
];
|
|
1237
1303
|
var contextOutputLimits = { maxBytes: Infinity, maxLines: Infinity };
|
|
1238
1304
|
function contextTextSlice(text, offset, limit) {
|
|
1239
1305
|
if (offset > 0 && (text.codePointAt(offset - 1) ?? 0) > 65535)
|
|
@@ -1258,7 +1324,13 @@ var target = Type.Optional(Type.String({
|
|
|
1258
1324
|
description: "Durable conversation ID; defaults to caller"
|
|
1259
1325
|
}));
|
|
1260
1326
|
var historyParameters = Type.Object({
|
|
1261
|
-
action: Type.Optional(Type.Union(
|
|
1327
|
+
action: Type.Optional(Type.Union([
|
|
1328
|
+
Type.Literal("help"),
|
|
1329
|
+
Type.Literal("list_windows"),
|
|
1330
|
+
Type.Literal("list"),
|
|
1331
|
+
Type.Literal("read"),
|
|
1332
|
+
Type.Literal("search")
|
|
1333
|
+
])),
|
|
1262
1334
|
target,
|
|
1263
1335
|
item_id: Type.Optional(Type.String()),
|
|
1264
1336
|
agent_name: Type.Optional(nullableString),
|
|
@@ -1283,7 +1355,14 @@ var historyParameters = Type.Object({
|
|
|
1283
1355
|
}))
|
|
1284
1356
|
}, { additionalProperties: false });
|
|
1285
1357
|
var notesParameters = Type.Object({
|
|
1286
|
-
action: Type.Optional(Type.Union(
|
|
1358
|
+
action: Type.Optional(Type.Union([
|
|
1359
|
+
Type.Literal("help"),
|
|
1360
|
+
Type.Literal("list"),
|
|
1361
|
+
Type.Literal("read"),
|
|
1362
|
+
Type.Literal("search"),
|
|
1363
|
+
Type.Literal("append"),
|
|
1364
|
+
Type.Literal("write")
|
|
1365
|
+
])),
|
|
1287
1366
|
target,
|
|
1288
1367
|
agent_name: Type.Optional(nullableString),
|
|
1289
1368
|
file_order: Type.Optional(Type.Union([Type.Literal("ascending"), Type.Literal("descending")])),
|
|
@@ -1295,7 +1374,7 @@ var notesParameters = Type.Object({
|
|
|
1295
1374
|
limit: Type.Optional(positiveInteger),
|
|
1296
1375
|
max_matches_per_file: Type.Optional(positiveInteger),
|
|
1297
1376
|
path: Type.Optional(Type.Union([Type.String(), Type.Null()], {
|
|
1298
|
-
description: "
|
|
1377
|
+
description: "Virtual note path, not a project file; prefix for list/search"
|
|
1299
1378
|
})),
|
|
1300
1379
|
query: Type.Optional(Type.String()),
|
|
1301
1380
|
recent_file_first: Type.Optional(Type.Boolean()),
|
|
@@ -1305,11 +1384,16 @@ var notesParameters = Type.Object({
|
|
|
1305
1384
|
offset_chars: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
1306
1385
|
text: Type.Optional(Type.String())
|
|
1307
1386
|
}, { additionalProperties: false });
|
|
1308
|
-
var newContextParameters = Type.Object({
|
|
1387
|
+
var newContextParameters = Type.Object({
|
|
1388
|
+
role: Type.Optional(Type.String({
|
|
1389
|
+
minLength: 1,
|
|
1390
|
+
description: "Configured model-role ID, not an agent name or handoff text"
|
|
1391
|
+
}))
|
|
1392
|
+
}, { additionalProperties: false });
|
|
1309
1393
|
function prepareNewContextArguments(input) {
|
|
1310
1394
|
const args = input ?? {};
|
|
1311
1395
|
if (!Check(newContextParameters, args))
|
|
1312
|
-
throw new Error('Use {} to keep the current
|
|
1396
|
+
throw new Error('Use {} to keep the current role, or {role: "name"} for a configured model-role ID.');
|
|
1313
1397
|
return args;
|
|
1314
1398
|
}
|
|
1315
1399
|
function prepareNotesArguments(input) {
|
|
@@ -1368,6 +1452,7 @@ function contextToolHelp(namespace, args, rankedHistory = false) {
|
|
|
1368
1452
|
throw new Error("Help accepts only action: help");
|
|
1369
1453
|
const fields = namespace === "notes" ? notesFields : historyFields;
|
|
1370
1454
|
return {
|
|
1455
|
+
...namespace === "notes" ? { results: "read: file.content; write/append: file.path" } : {},
|
|
1371
1456
|
actions: Object.fromEntries(Object.entries(fields).map(([action, names]) => [
|
|
1372
1457
|
action,
|
|
1373
1458
|
names.map((name) => (name === "path" ? ["read", "write", "append"].includes(action) : ["text", "query", "item_id"].includes(name)) || action === "read" && name === "window_id" ? name : `${name}?`).join(" ")
|
|
@@ -1375,13 +1460,13 @@ function contextToolHelp(namespace, args, rankedHistory = false) {
|
|
|
1375
1460
|
target: "Durable conversation ID; defaults to caller; reads require the same Context visibility group; write own",
|
|
1376
1461
|
...namespace === "notes" ? {
|
|
1377
1462
|
writes: "write replaces; append adds",
|
|
1378
|
-
paths: "
|
|
1463
|
+
paths: "Virtual note paths, inaccessible to filesystem tools. Relative to /notes; target selects a conversation, read-only unless your own",
|
|
1379
1464
|
usage: '{ "action": "read", "path": "checkpoint" }',
|
|
1380
1465
|
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",
|
|
1381
1466
|
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",
|
|
1382
1467
|
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"
|
|
1383
1468
|
} : {
|
|
1384
|
-
usage: "Search
|
|
1469
|
+
usage: "With query, action defaults to search. Search past chat, don't browse it. Pass returned IDs unchanged",
|
|
1385
1470
|
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"
|
|
1386
1471
|
}
|
|
1387
1472
|
};
|
|
@@ -1611,7 +1696,7 @@ var refreshFailures = new WeakMap;
|
|
|
1611
1696
|
function createHistoryTool(options) {
|
|
1612
1697
|
const tool = defineTool({
|
|
1613
1698
|
name: "history",
|
|
1614
|
-
description: "Search
|
|
1699
|
+
description: "Search past chat",
|
|
1615
1700
|
parameters: historyParameters,
|
|
1616
1701
|
structuredOutputSchema: Type2.Object({}, { additionalProperties: true }),
|
|
1617
1702
|
prepareArguments: prepareHistoryArguments,
|
|
@@ -1878,13 +1963,15 @@ async function waitForInputPlacement(host, id, context) {
|
|
|
1878
1963
|
revision++;
|
|
1879
1964
|
wake?.();
|
|
1880
1965
|
};
|
|
1881
|
-
const
|
|
1882
|
-
|
|
1966
|
+
const observation = host.harness.observeCommits({
|
|
1967
|
+
advance(publication) {
|
|
1968
|
+
if (publication.changes.some((change) => change.type === "task" && change.value.id === id || change.type === "submission" && change.value.requestId === requestId))
|
|
1969
|
+
changed();
|
|
1970
|
+
},
|
|
1971
|
+
end() {
|
|
1972
|
+
closing = true;
|
|
1883
1973
|
changed();
|
|
1884
|
-
|
|
1885
|
-
const stopClose = host.harness.subscribeClose(() => {
|
|
1886
|
-
closing = true;
|
|
1887
|
-
changed();
|
|
1974
|
+
}
|
|
1888
1975
|
});
|
|
1889
1976
|
try {
|
|
1890
1977
|
while (true) {
|
|
@@ -1931,8 +2018,7 @@ async function waitForInputPlacement(host, id, context) {
|
|
|
1931
2018
|
});
|
|
1932
2019
|
}
|
|
1933
2020
|
} finally {
|
|
1934
|
-
|
|
1935
|
-
stopClose();
|
|
2021
|
+
observation.detach();
|
|
1936
2022
|
}
|
|
1937
2023
|
}
|
|
1938
2024
|
|
|
@@ -1975,7 +2061,7 @@ function normalize(input, prefix) {
|
|
|
1975
2061
|
function createNotesTool(options) {
|
|
1976
2062
|
const tool = defineTool2({
|
|
1977
2063
|
name: "notes",
|
|
1978
|
-
description: "
|
|
2064
|
+
description: "Virtual filesystem task checkpoints",
|
|
1979
2065
|
parameters: notesParameters,
|
|
1980
2066
|
structuredOutputSchema: Type3.Object({}, { additionalProperties: true }),
|
|
1981
2067
|
prepareArguments: prepareNotesArguments,
|
|
@@ -2146,7 +2232,7 @@ async function readRoles(catalog, id, context) {
|
|
|
2146
2232
|
reasoning
|
|
2147
2233
|
}));
|
|
2148
2234
|
}
|
|
2149
|
-
async function renderModelRoles(catalog, id, context) {
|
|
2235
|
+
async function renderModelRoles(catalog, id, agent, context) {
|
|
2150
2236
|
let roles;
|
|
2151
2237
|
try {
|
|
2152
2238
|
roles = await readRoles(catalog, id, context);
|
|
@@ -2156,8 +2242,11 @@ async function renderModelRoles(catalog, id, context) {
|
|
|
2156
2242
|
}
|
|
2157
2243
|
if (!roles.length)
|
|
2158
2244
|
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(", ")})`;
|
|
2159
2247
|
return [
|
|
2160
|
-
|
|
2248
|
+
`Current role: ${currentRole}`,
|
|
2249
|
+
'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.',
|
|
2161
2250
|
...roles.map((role) => `- ${role.id}: ${role.description}`)
|
|
2162
2251
|
].join(`
|
|
2163
2252
|
`);
|
|
@@ -2250,9 +2339,9 @@ function reportedTokens(message) {
|
|
|
2250
2339
|
function checkpointGuidance(newContextRequests) {
|
|
2251
2340
|
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.";
|
|
2252
2341
|
return [
|
|
2253
|
-
"Notes are recovery state, not a diary.
|
|
2254
|
-
`
|
|
2255
|
-
"
|
|
2342
|
+
"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.",
|
|
2343
|
+
`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.`,
|
|
2344
|
+
"Skill reads do not survive rollover. Reread required skills."
|
|
2256
2345
|
].join(`
|
|
2257
2346
|
|
|
2258
2347
|
`);
|
|
@@ -2274,7 +2363,7 @@ function createContextPolicy(options) {
|
|
|
2274
2363
|
const sections = [
|
|
2275
2364
|
section("context", () => checkpointGuidance(options.newContextRequests)),
|
|
2276
2365
|
...options.newContextRequests === "off" || !options.modelRoles ? [] : [
|
|
2277
|
-
section("context-roles", (input, context) => renderModelRoles(options.modelRoles, input.conversationId, context))
|
|
2366
|
+
section("context-roles", async (input, context) => renderModelRoles(options.modelRoles, input.conversationId, input.agent, context))
|
|
2278
2367
|
],
|
|
2279
2368
|
section("context-state", async (input, context) => {
|
|
2280
2369
|
const [state, hints] = await Promise.all([
|
|
@@ -2415,7 +2504,7 @@ var ToolWindow = defineDoc7({
|
|
|
2415
2504
|
function createToolRollover(host, now, policy) {
|
|
2416
2505
|
const tool = defineTool4({
|
|
2417
2506
|
name: "new_context",
|
|
2418
|
-
description: "Start fresh
|
|
2507
|
+
description: "Start fresh context window. Must save notes first and call alone",
|
|
2419
2508
|
parameters: newContextParameters,
|
|
2420
2509
|
prepareArguments: prepareNewContextArguments,
|
|
2421
2510
|
replay: "safe",
|
|
@@ -2455,7 +2544,7 @@ function createToolRollover(host, now, policy) {
|
|
|
2455
2544
|
throw new Error("Context window is missing or a checkpoint is already in progress");
|
|
2456
2545
|
if (role && !await roleSourceMatches(tx, api.conversationId, role))
|
|
2457
2546
|
throw new Error("The model settings changed. Continue here and request a new role handoff if still needed.");
|
|
2458
|
-
if (!await notesAreFresh(tx, api.conversationId))
|
|
2547
|
+
if (!await notesAreFresh(tx, api.conversationId) || !await notesPrecedeRequest(tx, api.conversationId, api.taskId))
|
|
2459
2548
|
return {
|
|
2460
2549
|
status: "checkpoint_required",
|
|
2461
2550
|
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."
|
|
@@ -2492,7 +2581,7 @@ function createToolRollover(host, now, policy) {
|
|
|
2492
2581
|
const state = await tx.doc(WindowState, api.conversationId);
|
|
2493
2582
|
const slot = live.tools?.[0];
|
|
2494
2583
|
const generation = await tx.task(api.taskId);
|
|
2495
|
-
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);
|
|
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 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);
|
|
2496
2585
|
};
|
|
2497
2586
|
const preparation = await prepareRollover(conv, api.taskId, policy.beforeRollover, {
|
|
2498
2587
|
conversationId: api.conversationId,
|
|
@@ -2532,7 +2621,14 @@ function createToolRollover(host, now, policy) {
|
|
|
2532
2621
|
|
|
2533
2622
|
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.",
|
|
2534
2623
|
timestamp: now()
|
|
2535
|
-
}
|
|
2624
|
+
},
|
|
2625
|
+
...safe ? [
|
|
2626
|
+
{
|
|
2627
|
+
role: "user",
|
|
2628
|
+
content: "[Context management request] Resume from your saved checkpoint.",
|
|
2629
|
+
timestamp: now()
|
|
2630
|
+
}
|
|
2631
|
+
] : []
|
|
2536
2632
|
]
|
|
2537
2633
|
});
|
|
2538
2634
|
}, context);
|
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,
|
|
@@ -1895,13 +1980,15 @@ async function waitForInputPlacement(host, id, context) {
|
|
|
1895
1980
|
revision++;
|
|
1896
1981
|
wake?.();
|
|
1897
1982
|
};
|
|
1898
|
-
const
|
|
1899
|
-
|
|
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;
|
|
1900
1990
|
changed();
|
|
1901
|
-
|
|
1902
|
-
const stopClose = host.harness.subscribeClose(() => {
|
|
1903
|
-
closing = true;
|
|
1904
|
-
changed();
|
|
1991
|
+
}
|
|
1905
1992
|
});
|
|
1906
1993
|
try {
|
|
1907
1994
|
while (true) {
|
|
@@ -1948,8 +2035,7 @@ async function waitForInputPlacement(host, id, context) {
|
|
|
1948
2035
|
});
|
|
1949
2036
|
}
|
|
1950
2037
|
} finally {
|
|
1951
|
-
|
|
1952
|
-
stopClose();
|
|
2038
|
+
observation.detach();
|
|
1953
2039
|
}
|
|
1954
2040
|
}
|
|
1955
2041
|
|
|
@@ -1992,7 +2078,7 @@ function normalize(input, prefix) {
|
|
|
1992
2078
|
function createNotesTool(options) {
|
|
1993
2079
|
const tool = defineTool2({
|
|
1994
2080
|
name: "notes",
|
|
1995
|
-
description: "
|
|
2081
|
+
description: "Virtual filesystem task checkpoints",
|
|
1996
2082
|
parameters: notesParameters,
|
|
1997
2083
|
structuredOutputSchema: Type3.Object({}, { additionalProperties: true }),
|
|
1998
2084
|
prepareArguments: prepareNotesArguments,
|
|
@@ -2163,7 +2249,7 @@ async function readRoles(catalog, id, context) {
|
|
|
2163
2249
|
reasoning
|
|
2164
2250
|
}));
|
|
2165
2251
|
}
|
|
2166
|
-
async function renderModelRoles(catalog, id, context) {
|
|
2252
|
+
async function renderModelRoles(catalog, id, agent, context) {
|
|
2167
2253
|
let roles;
|
|
2168
2254
|
try {
|
|
2169
2255
|
roles = await readRoles(catalog, id, context);
|
|
@@ -2173,8 +2259,11 @@ async function renderModelRoles(catalog, id, context) {
|
|
|
2173
2259
|
}
|
|
2174
2260
|
if (!roles.length)
|
|
2175
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(", ")})`;
|
|
2176
2264
|
return [
|
|
2177
|
-
|
|
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.',
|
|
2178
2267
|
...roles.map((role) => `- ${role.id}: ${role.description}`)
|
|
2179
2268
|
].join(`
|
|
2180
2269
|
`);
|
|
@@ -2267,9 +2356,9 @@ function reportedTokens(message) {
|
|
|
2267
2356
|
function checkpointGuidance(newContextRequests) {
|
|
2268
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.";
|
|
2269
2358
|
return [
|
|
2270
|
-
"Notes are recovery state, not a diary.
|
|
2271
|
-
`
|
|
2272
|
-
"
|
|
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."
|
|
2273
2362
|
].join(`
|
|
2274
2363
|
|
|
2275
2364
|
`);
|
|
@@ -2291,7 +2380,7 @@ function createContextPolicy(options) {
|
|
|
2291
2380
|
const sections = [
|
|
2292
2381
|
section("context", () => checkpointGuidance(options.newContextRequests)),
|
|
2293
2382
|
...options.newContextRequests === "off" || !options.modelRoles ? [] : [
|
|
2294
|
-
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))
|
|
2295
2384
|
],
|
|
2296
2385
|
section("context-state", async (input, context) => {
|
|
2297
2386
|
const [state, hints] = await Promise.all([
|
|
@@ -2432,7 +2521,7 @@ var ToolWindow = defineDoc7({
|
|
|
2432
2521
|
function createToolRollover(host, now, policy) {
|
|
2433
2522
|
const tool = defineTool4({
|
|
2434
2523
|
name: "new_context",
|
|
2435
|
-
description: "Start fresh
|
|
2524
|
+
description: "Start fresh context window. Must save notes first and call alone",
|
|
2436
2525
|
parameters: newContextParameters,
|
|
2437
2526
|
prepareArguments: prepareNewContextArguments,
|
|
2438
2527
|
replay: "safe",
|
|
@@ -2472,7 +2561,7 @@ function createToolRollover(host, now, policy) {
|
|
|
2472
2561
|
throw new Error("Context window is missing or a checkpoint is already in progress");
|
|
2473
2562
|
if (role && !await roleSourceMatches(tx, api.conversationId, role))
|
|
2474
2563
|
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))
|
|
2564
|
+
if (!await notesAreFresh(tx, api.conversationId) || !await notesPrecedeRequest(tx, api.conversationId, api.taskId))
|
|
2476
2565
|
return {
|
|
2477
2566
|
status: "checkpoint_required",
|
|
2478
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."
|
|
@@ -2509,7 +2598,7 @@ function createToolRollover(host, now, policy) {
|
|
|
2509
2598
|
const state = await tx.doc(WindowState, api.conversationId);
|
|
2510
2599
|
const slot = live.tools?.[0];
|
|
2511
2600
|
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);
|
|
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);
|
|
2513
2602
|
};
|
|
2514
2603
|
const preparation = await prepareRollover(conv, api.taskId, policy.beforeRollover, {
|
|
2515
2604
|
conversationId: api.conversationId,
|
|
@@ -2549,7 +2638,14 @@ function createToolRollover(host, now, policy) {
|
|
|
2549
2638
|
|
|
2550
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.",
|
|
2551
2640
|
timestamp: now()
|
|
2552
|
-
}
|
|
2641
|
+
},
|
|
2642
|
+
...safe ? [
|
|
2643
|
+
{
|
|
2644
|
+
role: "user",
|
|
2645
|
+
content: "[Context management request] Resume from your saved checkpoint.",
|
|
2646
|
+
timestamp: now()
|
|
2647
|
+
}
|
|
2648
|
+
] : []
|
|
2553
2649
|
]
|
|
2554
2650
|
});
|
|
2555
2651
|
}, context);
|
|
@@ -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;
|
|
@@ -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";
|
|
@@ -17,7 +17,7 @@ export declare function contextToolResult(result: JsonObject, details?: JsonObje
|
|
|
17
17
|
details: JsonObject;
|
|
18
18
|
};
|
|
19
19
|
export declare const historyParameters: Type.TObject<{
|
|
20
|
-
action: Type.TOptional<Type.TUnion<Type.TLiteral<"help"
|
|
20
|
+
action: Type.TOptional<Type.TUnion<[Type.TLiteral<"help">, Type.TLiteral<"list_windows">, Type.TLiteral<"list">, Type.TLiteral<"read">, Type.TLiteral<"search">]>>;
|
|
21
21
|
target: Type.TOptional<Type.TString>;
|
|
22
22
|
item_id: Type.TOptional<Type.TString>;
|
|
23
23
|
agent_name: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
|
|
@@ -33,7 +33,7 @@ export declare const historyParameters: Type.TObject<{
|
|
|
33
33
|
window_id: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
|
|
34
34
|
}>;
|
|
35
35
|
export declare const notesParameters: Type.TObject<{
|
|
36
|
-
action: Type.TOptional<Type.TUnion<Type.TLiteral<"
|
|
36
|
+
action: Type.TOptional<Type.TUnion<[Type.TLiteral<"help">, Type.TLiteral<"list">, Type.TLiteral<"read">, Type.TLiteral<"search">, Type.TLiteral<"append">, Type.TLiteral<"write">]>>;
|
|
37
37
|
target: Type.TOptional<Type.TString>;
|
|
38
38
|
agent_name: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
|
|
39
39
|
file_order: Type.TOptional<Type.TUnion<[Type.TLiteral<"ascending">, Type.TLiteral<"descending">]>>;
|
|
@@ -60,6 +60,7 @@ export declare function prepareNewContextArguments(input: unknown): {
|
|
|
60
60
|
export declare function prepareNotesArguments(input: unknown): NotesArguments;
|
|
61
61
|
export declare function prepareHistoryArguments(input: unknown): HistoryArguments;
|
|
62
62
|
export declare function contextToolHelp(namespace: "notes" | "history", args: NotesArguments | HistoryArguments, rankedHistory?: boolean): {
|
|
63
|
+
results?: string;
|
|
63
64
|
actions: {
|
|
64
65
|
[k: string]: string;
|
|
65
66
|
};
|
|
@@ -71,6 +72,7 @@ export declare function contextToolHelp(namespace: "notes" | "history", args: No
|
|
|
71
72
|
paging: string;
|
|
72
73
|
defaults: string;
|
|
73
74
|
} | {
|
|
75
|
+
results?: string;
|
|
74
76
|
actions: {
|
|
75
77
|
[k: string]: string;
|
|
76
78
|
};
|
|
@@ -22,7 +22,7 @@ export declare function createToolRollover(host: () => ContextHost, now: () => n
|
|
|
22
22
|
prepareArguments?(args: unknown): {
|
|
23
23
|
role?: string;
|
|
24
24
|
};
|
|
25
|
-
structuredOutputSchema?:
|
|
25
|
+
structuredOutputSchema?: object;
|
|
26
26
|
callers?: readonly ("model" | "tools")[];
|
|
27
27
|
deferred?: true;
|
|
28
28
|
outputLimits?: {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@howaboua/pi-durable-context",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Local notes, retained history and durable context rollover",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -42,12 +42,12 @@
|
|
|
42
42
|
"sideEffects": false,
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"typebox": "1.3.27",
|
|
45
|
-
"@howaboua/pi-durable-components": "0.
|
|
45
|
+
"@howaboua/pi-durable-components": "0.11.0"
|
|
46
46
|
},
|
|
47
47
|
"peerDependencies": {
|
|
48
|
-
"@earendil-works/chord": "1.
|
|
49
|
-
"@earendil-works/pi-ai": "1.
|
|
50
|
-
"@earendil-works/pi-durable": "1.
|
|
48
|
+
"@earendil-works/chord": "1.5.0",
|
|
49
|
+
"@earendil-works/pi-ai": "1.5.0",
|
|
50
|
+
"@earendil-works/pi-durable": "1.5.0",
|
|
51
51
|
"@modelcontextprotocol/sdk": ">=1.25.2 <2"
|
|
52
52
|
},
|
|
53
53
|
"publishConfig": {
|