@hachej/boring-agent 0.4.3 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +8 -0
- package/README.md +45 -10
- package/THIRD_PARTY_NOTICES.md +240 -0
- package/dist/documents.d.ts +82 -0
- package/dist/documents.js +198 -0
- package/dist/memory/optchat-core.d.ts +13 -5
- package/dist/memory/optchat-core.js +26 -16
- package/dist/memory/optchat.d.ts +28 -8
- package/dist/memory/optchat.js +227 -54
- package/licenses/Apache-2.0.txt +202 -0
- package/package.json +15 -4
package/dist/memory/optchat.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
// Adapted from VictorTaelin/uniichat, Copyright 2026 Higher Order Company, Apache-2.0.
|
|
2
|
+
// Changed: Pi-native tasks, documents, message adaptation and host memory controls. See ../../NOTICE and ../../licenses/Apache-2.0.txt.
|
|
1
3
|
// OptChat memory as one native pi-durable extension, opt-in per conversation.
|
|
2
4
|
// The Pi transcript is the append-only log and is never rewritten. While the extension is selected, `beforeRequest` shows
|
|
3
5
|
// the model one view of everything before the current turn: a tiling of the log by summary-tree nodes, one `id+n|text`
|
|
@@ -15,7 +17,17 @@ export { OptChatLog, OptChatTree, advanceFold, emptyFold, leavesOf, renderView,
|
|
|
15
17
|
export const OptChatNodes = defineDocFamily({
|
|
16
18
|
kind: 'boring.memory.optchat.nodes', version: 1, family: true, scope: 'conversation', history: 'latest', fork: 'current', initial: () => ({ nodes: {} }),
|
|
17
19
|
});
|
|
18
|
-
/**
|
|
20
|
+
/** Seed memories, stored once per conversation and inherited by forks. They precede the Pi transcript in the memory only. */
|
|
21
|
+
export const OptChatNotes = defineDoc({
|
|
22
|
+
kind: 'boring.memory.optchat.notes', version: 1, scope: 'conversation', history: 'latest', fork: 'current',
|
|
23
|
+
initial: () => ({ seeded: false, notes: [] }),
|
|
24
|
+
});
|
|
25
|
+
/** Memory-only tombstones. Values are leaf counts, never the forgotten content. Pi's transcript is unchanged. */
|
|
26
|
+
export const OptChatEdits = defineDoc({
|
|
27
|
+
kind: 'boring.memory.optchat.edits', version: 1, scope: 'conversation', history: 'latest', fork: 'current',
|
|
28
|
+
initial: () => ({ revision: 0, forgotten: {} }),
|
|
29
|
+
});
|
|
30
|
+
/** Compactor bookkeeping of one conversation: calls, spend and the last failure of each node, including its retry streak. */
|
|
19
31
|
export const OptChatState = defineDoc({
|
|
20
32
|
kind: 'boring.memory.optchat.state', version: 1, scope: 'conversation', history: 'latest', fork: 'initial',
|
|
21
33
|
initial: () => ({ calls: 0, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }, failures: {} }),
|
|
@@ -28,6 +40,7 @@ class Session {
|
|
|
28
40
|
stored = new Map();
|
|
29
41
|
tree;
|
|
30
42
|
fold = emptyFold();
|
|
43
|
+
compactFold = emptyFold();
|
|
31
44
|
/** Summary tasks may be created for leaves below this; the current turn's steps are held back while a request runs. */
|
|
32
45
|
upTo = 0;
|
|
33
46
|
lastRequest;
|
|
@@ -41,11 +54,33 @@ class Session {
|
|
|
41
54
|
if (this.log.set(leaves) < before) {
|
|
42
55
|
this.tree.reset();
|
|
43
56
|
this.fold = emptyFold();
|
|
57
|
+
this.compactFold = emptyFold();
|
|
44
58
|
}
|
|
45
59
|
}
|
|
46
60
|
}
|
|
47
61
|
const message = (text) => ({ role: 'user', content: text.map(part => ({ type: 'text', text: part })), timestamp: Date.now() });
|
|
48
62
|
const LIVE = ['pending', 'running', 'waiting'];
|
|
63
|
+
function redacted(item) {
|
|
64
|
+
if (item.role === 'system')
|
|
65
|
+
return item;
|
|
66
|
+
if (item.role === 'assistant')
|
|
67
|
+
return { ...item, content: item.content.flatMap((part) => part.type === 'toolCall'
|
|
68
|
+
? [{ type: 'toolCall', id: part.id, name: 'forgotten', arguments: {} }]
|
|
69
|
+
: part.type === 'text' ? [{ type: 'text', text: '(forgotten)' }] : []) };
|
|
70
|
+
if (item.role === 'toolResult')
|
|
71
|
+
return { ...item, toolName: 'forgotten', content: [{ type: 'text', text: '(forgotten)' }] };
|
|
72
|
+
return { ...item, content: '(forgotten)' };
|
|
73
|
+
}
|
|
74
|
+
/** Pi's TextContent has no per-block cache marker. Keep the reference's four-line blocks without inventing one. */
|
|
75
|
+
function chatBlocks(lines) {
|
|
76
|
+
const rows = lines ? lines.split('\n') : [];
|
|
77
|
+
const blocks = ['<chat>\n'];
|
|
78
|
+
let i = 0;
|
|
79
|
+
for (; i + 4 <= rows.length; i += 4)
|
|
80
|
+
blocks.push(`${rows.slice(i, i + 4).join('\n')}\n`);
|
|
81
|
+
blocks.push(`${rows.slice(i).map(line => `${line}\n`).join('')}</chat>\n`);
|
|
82
|
+
return blocks;
|
|
83
|
+
}
|
|
49
84
|
const addUsage = (sum, usage) => {
|
|
50
85
|
if (!sum)
|
|
51
86
|
return structuredClone(usage);
|
|
@@ -68,12 +103,17 @@ const addUsage = (sum, usage) => {
|
|
|
68
103
|
export function createOptChatMemory(options) {
|
|
69
104
|
const nodeBytes = options.nodeBytes ?? DEFAULTS.nodeBytes, viewBytes = options.viewBytes ?? DEFAULTS.viewBytes, jobs = options.jobs ?? DEFAULTS.jobs;
|
|
70
105
|
const tries = options.tries ?? DEFAULTS.tries, cap = options.cap ?? DEFAULTS.cap, retryMs = options.retryMs ?? DEFAULTS.retryMs, settleMs = options.settleTimeoutMs ?? DEFAULTS.settleTimeoutMs;
|
|
106
|
+
const compactBytes = options.compactBytes ?? DEFAULTS.compactBytes;
|
|
71
107
|
const agentName = options.agentName ?? 'OptChat';
|
|
72
108
|
const extensionName = options.name ?? 'boring.memory.optchat';
|
|
73
109
|
const taskKind = `${extensionName}.node`;
|
|
74
110
|
const system = compactPrompt(agentName);
|
|
75
111
|
const scale = scaleLine(nodeBytes);
|
|
112
|
+
const notes = [...(options.notes ?? [])];
|
|
113
|
+
const logOptions = (seed, edits) => ({ notes: seed, forgotten: edits.forgotten, ...(options.workOf ? { workOf: options.workOf } : {}) });
|
|
76
114
|
const sessions = new Map();
|
|
115
|
+
const naps = new Map();
|
|
116
|
+
const retryDelay = (failure) => Math.min(60_000, retryMs * 2 ** Math.min(30, (failure.attempts ?? 1) - 1));
|
|
77
117
|
const aborter = new AbortController();
|
|
78
118
|
const hostContext = withAbortSignal(aborter.signal, options.context);
|
|
79
119
|
const session = (id) => {
|
|
@@ -85,6 +125,8 @@ export function createOptChatMemory(options) {
|
|
|
85
125
|
/** Read the stored summaries. Tasks write them (in this process or another, before or after a restart), so every read goes to the documents. */
|
|
86
126
|
async function loadStored(s, reader, context) {
|
|
87
127
|
const total = s.log.leaves.length;
|
|
128
|
+
s.stored.clear();
|
|
129
|
+
s.tree.reset();
|
|
88
130
|
for (let level = 0; span(level) <= total; level++) {
|
|
89
131
|
const nodes = Math.floor(total / span(level));
|
|
90
132
|
for (let shard = 0; shard * SHARD < nodes; shard++) {
|
|
@@ -100,14 +142,38 @@ export function createOptChatMemory(options) {
|
|
|
100
142
|
throw new Error(`No conversation ${String(id)}`);
|
|
101
143
|
return found;
|
|
102
144
|
}
|
|
145
|
+
/** The compactor has an independent fold. Copy before advancing: native tasks and requests can overlap. */
|
|
146
|
+
function compactView(s, to) {
|
|
147
|
+
const cached = session(s.id).compactFold;
|
|
148
|
+
const fold = cached.T > to ? emptyFold() : { T: cached.T, size: cached.size, parts: cached.parts.map(part => ({ ...part })) };
|
|
149
|
+
return advanceFold(fold, s.tree, to, compactBytes);
|
|
150
|
+
}
|
|
103
151
|
/** Bring a session up to date with the committed context and its stored summaries. */
|
|
104
152
|
async function refresh(id) {
|
|
105
153
|
const s = session(id);
|
|
106
154
|
const view = await (await conversationOf(id)).context(options.context);
|
|
107
|
-
|
|
155
|
+
const seed = await seedNotes(id);
|
|
156
|
+
const edits = await memoryEdits(id);
|
|
157
|
+
s.sync(leavesOf(view.messages, cap, logOptions(seed, edits)).leaves);
|
|
108
158
|
await loadStored(s, options.harness(), options.context);
|
|
109
159
|
return s;
|
|
110
160
|
}
|
|
161
|
+
async function memoryEdits(id) {
|
|
162
|
+
return await options.harness().snapshot(OptChatEdits, id, options.context) ?? { revision: 0, forgotten: {} };
|
|
163
|
+
}
|
|
164
|
+
async function seedNotes(id) {
|
|
165
|
+
const stored = await options.harness().snapshot(OptChatNotes, id, options.context);
|
|
166
|
+
if (stored?.seeded)
|
|
167
|
+
return stored.notes;
|
|
168
|
+
return (await conversationOf(id)).commit(async (tx) => {
|
|
169
|
+
const doc = await tx.doc(OptChatNotes, id);
|
|
170
|
+
if (!doc.seeded) {
|
|
171
|
+
doc.notes = [...notes];
|
|
172
|
+
doc.seeded = true;
|
|
173
|
+
}
|
|
174
|
+
return [...doc.notes];
|
|
175
|
+
}, options.context);
|
|
176
|
+
}
|
|
111
177
|
// ---- The summarizer (runs inside the native task) ----------------------------------------------------------------------
|
|
112
178
|
/** One node by the reference protocol (§4.2, §4.3): context first, then the step; over-long lines are resubmitted cut at the limit; the shortest wins. */
|
|
113
179
|
async function askModel(job, runtimeModels, signal) {
|
|
@@ -131,7 +197,7 @@ export function createOptChatMemory(options) {
|
|
|
131
197
|
const step = `For scale, this line is exactly ${scale.bytes} bytes:\n${scale.text}\n\n` + (job.level === 0
|
|
132
198
|
? `Compress this message into one line, in at most ${nodeBytes} bytes:\n${job.source[0]}`
|
|
133
199
|
: `Merge these two lines into one, in at most ${nodeBytes} bytes:\n${lines.join('\n')}`);
|
|
134
|
-
const conversation = [message([
|
|
200
|
+
const conversation = [message([...chatBlocks(job.context), step])];
|
|
135
201
|
const attempts = [];
|
|
136
202
|
let usage, calls = 0, spender;
|
|
137
203
|
try {
|
|
@@ -186,29 +252,48 @@ export function createOptChatMemory(options) {
|
|
|
186
252
|
// A private view of this conversation: a request may be folding and rendering the shared session right now.
|
|
187
253
|
const s = new Session(id, nodeBytes);
|
|
188
254
|
const load = async () => {
|
|
189
|
-
|
|
255
|
+
const seed = (await runtime.snapshot(OptChatNotes, id, context))?.notes ?? [];
|
|
256
|
+
const edits = await runtime.snapshot(OptChatEdits, id, context) ?? { revision: 0, forgotten: {} };
|
|
257
|
+
s.sync(leavesOf((await runtime.context(id, context)).messages, cap, logOptions(seed, edits)).leaves);
|
|
190
258
|
await loadStored(s, runtime, context);
|
|
259
|
+
return edits.revision;
|
|
191
260
|
};
|
|
192
|
-
await load();
|
|
261
|
+
const revision = await load();
|
|
193
262
|
const ready = () => s.log.fp(level, index) === of && (level === 0 || (s.tree.text(level - 1, 2 * index) !== undefined && s.tree.text(level - 1, 2 * index + 1) !== undefined));
|
|
194
263
|
if (!ready() || s.tree.text(level, index) !== undefined)
|
|
195
264
|
return stale(); // the history changed, a child is missing, or the node needs no summary
|
|
196
|
-
const to = Math.min(upTo,
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
265
|
+
const to = Math.min(upTo, index * span(level));
|
|
266
|
+
const shared = session(id);
|
|
267
|
+
shared.sync(s.log.leaves);
|
|
268
|
+
const fold = compactView(s, to);
|
|
269
|
+
if (fold.size > compactBytes)
|
|
270
|
+
return stale(); // admission will build preceding parents before trying this node again
|
|
271
|
+
if (fold.T >= shared.compactFold.T)
|
|
272
|
+
shared.compactFold = fold;
|
|
200
273
|
const source = level === 0 ? [s.log.leaves[index].line] : [s.tree.text(level - 1, 2 * index), s.tree.text(level - 1, 2 * index + 1)];
|
|
201
|
-
const job = { conversationId: id, level, index, range: [index * span(level), (index + 1) * span(level) - 1], source, context: bareLines(
|
|
202
|
-
|
|
274
|
+
const job = { conversationId: id, level, index, range: [index * span(level), (index + 1) * span(level) - 1], source, context: bareLines(fold, s.tree, to), nodeBytes };
|
|
275
|
+
let summary;
|
|
276
|
+
try {
|
|
277
|
+
summary = await askModel(job, runtime.models, runtime.signal);
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
if (runtime.signal.aborted)
|
|
281
|
+
throw error;
|
|
282
|
+
summary = { error, calls: 0 }; // model resolution can fail before any request is sent
|
|
283
|
+
}
|
|
203
284
|
await load();
|
|
204
285
|
if (!ready())
|
|
205
286
|
return stale(summary); // the history changed while the model ran: its line is dropped, its spend is kept
|
|
206
287
|
let firstFailure = false;
|
|
207
288
|
await runtime.commit(async (tx) => {
|
|
208
289
|
const state = await bookkeeping(tx, id, summary);
|
|
290
|
+
const edits = await tx.doc(OptChatEdits, id);
|
|
291
|
+
if (edits.revision !== revision)
|
|
292
|
+
return { status: 'terminal', outcome: { status: 'completed', result: { built: false } } };
|
|
209
293
|
if (summary.text === undefined) {
|
|
210
|
-
|
|
211
|
-
|
|
294
|
+
const previous = state.failures[`${level}:${index}`];
|
|
295
|
+
firstFailure = previous?.of !== of;
|
|
296
|
+
state.failures[`${level}:${index}`] = { at: Date.now(), of, attempts: firstFailure ? 1 : (previous?.attempts ?? 1) + 1, error: String(summary.error?.message ?? summary.error) };
|
|
212
297
|
return { status: 'terminal', outcome: { status: 'failed', error: { message: state.failures[`${level}:${index}`].error } } };
|
|
213
298
|
}
|
|
214
299
|
const doc = await tx.doc(OptChatNodes, id, shardKey(level, index), 0);
|
|
@@ -242,6 +327,8 @@ export function createOptChatMemory(options) {
|
|
|
242
327
|
continue;
|
|
243
328
|
if (level > 0 && (s.tree.text(level - 1, 2 * index) === undefined || s.tree.text(level - 1, 2 * index + 1) === undefined))
|
|
244
329
|
continue;
|
|
330
|
+
if (compactView(s, index * span(level)).size > compactBytes)
|
|
331
|
+
break;
|
|
245
332
|
found.push({ level, index });
|
|
246
333
|
}
|
|
247
334
|
}
|
|
@@ -250,7 +337,7 @@ export function createOptChatMemory(options) {
|
|
|
250
337
|
/**
|
|
251
338
|
* Make sure every node that can be built has one live background task, up to `jobs` live tasks of the conversation. Host
|
|
252
339
|
* admission only: Pi schedules and runs the tasks. One live task per node key (found by scanning native tasks in the same
|
|
253
|
-
* commit that creates them); a node
|
|
340
|
+
* commit that creates them); a node inside its backoff window waits for the idle admission loop.
|
|
254
341
|
*/
|
|
255
342
|
async function admit(s, skip) {
|
|
256
343
|
const wanted = candidates(s).map(({ level, index }) => ({ level, index, of: s.log.fp(level, index) }));
|
|
@@ -276,7 +363,7 @@ export function createOptChatMemory(options) {
|
|
|
276
363
|
if (found.has(key) || skip.has(key))
|
|
277
364
|
continue;
|
|
278
365
|
const failure = failures[nodeKey(node.level, node.index)];
|
|
279
|
-
if (failure && failure.of === node.of && now - failure.at <
|
|
366
|
+
if (failure && failure.of === node.of && now - failure.at < retryDelay(failure)) {
|
|
280
367
|
waiting++;
|
|
281
368
|
continue;
|
|
282
369
|
}
|
|
@@ -301,22 +388,45 @@ export function createOptChatMemory(options) {
|
|
|
301
388
|
cancel();
|
|
302
389
|
}
|
|
303
390
|
}
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
const
|
|
310
|
-
|
|
391
|
+
/** Abortable host wait between admission attempts. Pi still owns each node task and its recovery. */
|
|
392
|
+
async function pause(ms) {
|
|
393
|
+
if (aborter.signal.aborted)
|
|
394
|
+
return;
|
|
395
|
+
await new Promise(resolve => {
|
|
396
|
+
const done = () => { clearTimeout(timer); aborter.signal.removeEventListener('abort', done); resolve(); };
|
|
397
|
+
const timer = setTimeout(done, Math.max(1, ms));
|
|
398
|
+
aborter.signal.addEventListener('abort', done, { once: true });
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
async function drain(id) {
|
|
402
|
+
while (!aborter.signal.aborted) {
|
|
403
|
+
const s = await refresh(id);
|
|
404
|
+
s.upTo = s.log.leaves.length;
|
|
405
|
+
const { live } = await admit(s, new Set());
|
|
406
|
+
if (live.size > 0) {
|
|
407
|
+
if (!await settleAny([...live.values()], undefined, hostContext))
|
|
408
|
+
return;
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
const failures = (await options.harness().snapshot(OptChatState, id, options.context))?.failures ?? {};
|
|
412
|
+
const delays = candidates(s).flatMap(({ level, index }) => {
|
|
413
|
+
const failure = failures[nodeKey(level, index)];
|
|
414
|
+
return failure && failure.of === s.log.fp(level, index) ? [failure.at + retryDelay(failure) - Date.now()] : [];
|
|
415
|
+
});
|
|
416
|
+
if (delays.length === 0)
|
|
311
417
|
return;
|
|
312
|
-
|
|
313
|
-
if (!done)
|
|
314
|
-
return; // disposed
|
|
315
|
-
if (!done.built)
|
|
316
|
-
skip.add(done.key);
|
|
317
|
-
await loadStored(s, options.harness(), options.context);
|
|
418
|
+
await pause(Math.min(...delays));
|
|
318
419
|
}
|
|
319
420
|
}
|
|
421
|
+
function nap(id) {
|
|
422
|
+
const key = String(id);
|
|
423
|
+
const existing = naps.get(key);
|
|
424
|
+
if (existing)
|
|
425
|
+
return existing;
|
|
426
|
+
const running = drain(id).finally(() => { naps.delete(key); });
|
|
427
|
+
naps.set(key, running);
|
|
428
|
+
return running;
|
|
429
|
+
}
|
|
320
430
|
/** Wait until every line of the view is a summary (§6). Never shows cut text: on timeout the rest shows the placeholder. */
|
|
321
431
|
async function settle(s, covered, context) {
|
|
322
432
|
const deadline = Date.now() + settleMs, skip = new Set();
|
|
@@ -339,6 +449,45 @@ export function createOptChatMemory(options) {
|
|
|
339
449
|
skip.add(done.key);
|
|
340
450
|
}
|
|
341
451
|
}
|
|
452
|
+
/** Context can copy an earlier fact into a later summary. Invalidate those too, atomically with the tombstone. */
|
|
453
|
+
async function forgetMessage(id, messageIndex) {
|
|
454
|
+
if (!Number.isInteger(messageIndex) || messageIndex < 0)
|
|
455
|
+
throw new Error('Invalid message index');
|
|
456
|
+
const conversation = await conversationOf(id);
|
|
457
|
+
const seed = await seedNotes(id);
|
|
458
|
+
for (;;) {
|
|
459
|
+
const edits = await memoryEdits(id);
|
|
460
|
+
const messages = (await conversation.context(options.context)).messages;
|
|
461
|
+
if (messageIndex >= messages.length || messages[messageIndex].role === 'system')
|
|
462
|
+
throw new Error('No forgettable message at that index');
|
|
463
|
+
const ordinal = messages.slice(0, messageIndex).filter(item => item.role !== 'system').length;
|
|
464
|
+
if (edits.forgotten[String(ordinal)] !== undefined)
|
|
465
|
+
return;
|
|
466
|
+
const { leaves, before } = leavesOf(messages, cap, logOptions(seed, edits));
|
|
467
|
+
const start = before[messageIndex], end = before[messageIndex + 1];
|
|
468
|
+
const changed = await conversation.commit(async (tx) => {
|
|
469
|
+
const doc = await tx.doc(OptChatEdits, id);
|
|
470
|
+
if (doc.revision !== edits.revision)
|
|
471
|
+
return false;
|
|
472
|
+
doc.forgotten[String(ordinal)] = end - start;
|
|
473
|
+
doc.revision++;
|
|
474
|
+
const state = await tx.doc(OptChatState, id);
|
|
475
|
+
for (let level = 0; span(level) <= leaves.length; level++) {
|
|
476
|
+
for (let index = Math.floor(start / span(level)); (index + 1) * span(level) <= leaves.length; index++) {
|
|
477
|
+
const shard = await tx.doc(OptChatNodes, id, shardKey(level, index), 0);
|
|
478
|
+
delete shard.nodes[String(index)];
|
|
479
|
+
delete state.failures[nodeKey(level, index)];
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return true;
|
|
483
|
+
}, options.context);
|
|
484
|
+
if (!changed)
|
|
485
|
+
continue;
|
|
486
|
+
sessions.delete(String(id));
|
|
487
|
+
void nap(id).catch(() => { });
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
342
491
|
// ---- The extension -----------------------------------------------------------------------------------------------------
|
|
343
492
|
const text = (value) => ({ output: [{ type: 'text', text: value }] });
|
|
344
493
|
const zoomTool = defineTool({
|
|
@@ -363,30 +512,53 @@ export function createOptChatMemory(options) {
|
|
|
363
512
|
hooks: [
|
|
364
513
|
hook(GenerationTask, {
|
|
365
514
|
beforeRequest: async (request, api, context) => {
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
const
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
515
|
+
for (;;) {
|
|
516
|
+
const seed = await seedNotes(api.conversationId);
|
|
517
|
+
const edits = await memoryEdits(api.conversationId);
|
|
518
|
+
const { leaves, before } = leavesOf(request.messages, cap, logOptions(seed, edits));
|
|
519
|
+
const last = request.messages.findLastIndex(item => item.role === 'user' || (item.role !== 'system' && options.workOf?.(item)));
|
|
520
|
+
const covered = last < 0 ? 0 : before[last];
|
|
521
|
+
if (covered === 0 && Object.keys(edits.forgotten).length === 0 && !request.messages.some(item => options.workOf?.(item)))
|
|
522
|
+
return undefined;
|
|
523
|
+
const cached = session(api.conversationId);
|
|
524
|
+
cached.sync(leaves);
|
|
525
|
+
const s = new Session(api.conversationId, nodeBytes);
|
|
526
|
+
s.sync(leaves);
|
|
527
|
+
s.upTo = covered;
|
|
528
|
+
if (cached.fold.T <= covered)
|
|
529
|
+
s.fold = { T: cached.fold.T, size: cached.fold.size, parts: cached.fold.parts.map(part => ({ ...part })) };
|
|
530
|
+
const started = Date.now();
|
|
531
|
+
const settled = await settle(s, covered, context);
|
|
532
|
+
if ((await memoryEdits(api.conversationId)).revision !== edits.revision)
|
|
533
|
+
continue;
|
|
534
|
+
const view = renderView(s.fold, s.tree);
|
|
535
|
+
const blocks = chatBlocks(view.split('\n').slice(1, -1).join('\n')).map(text => ({ type: 'text', text }));
|
|
536
|
+
let ordinal = 0;
|
|
537
|
+
const calls = new Set();
|
|
538
|
+
const messages = request.messages.flatMap((item, index) => {
|
|
539
|
+
const forgotten = item.role !== 'system' && edits.forgotten[String(ordinal++)] !== undefined;
|
|
540
|
+
if (index < last)
|
|
541
|
+
return item.role === 'system' ? [item] : [];
|
|
542
|
+
const retained = forgotten ? redacted(item) : item;
|
|
543
|
+
const work = item.role !== 'system' && options.workOf?.(item);
|
|
544
|
+
// A report can start midway through a tool batch. Never send results without their calls.
|
|
545
|
+
const normalize = (index === last && work && retained.role !== 'user') || (retained.role === 'toolResult' && !calls.has(retained.toolCallId));
|
|
546
|
+
const current = normalize ? message([leavesOf([retained], Infinity, { workOf: () => !!work }).leaves[0].line]) : retained;
|
|
547
|
+
if (current.role === 'assistant')
|
|
548
|
+
for (const part of current.content)
|
|
549
|
+
if (part.type === 'toolCall')
|
|
550
|
+
calls.add(part.id);
|
|
551
|
+
if (index > last || current.role === 'system')
|
|
552
|
+
return [current];
|
|
553
|
+
if (current.role === 'assistant')
|
|
554
|
+
return [{ ...current, content: [...blocks, ...current.content] }];
|
|
555
|
+
const body = typeof current.content === 'string' ? [{ type: 'text', text: current.content }] : current.content;
|
|
556
|
+
return [{ ...current, content: [...blocks, ...body] }];
|
|
557
|
+
});
|
|
558
|
+
cached.lastRequest = { at: new Date().toISOString(), covered, requestMessages: messages.length, logMessages: request.messages.length, viewBytes: byteLength(view), waitedMs: Date.now() - started, settled };
|
|
559
|
+
cached.fold = s.fold;
|
|
560
|
+
return { messages };
|
|
561
|
+
}
|
|
390
562
|
},
|
|
391
563
|
// A finished answer: once the run has committed it, create its summary tasks (background, so they never hold the run) so the next request finds its view ready.
|
|
392
564
|
onYield: (_answer, api) => {
|
|
@@ -414,7 +586,7 @@ export function createOptChatMemory(options) {
|
|
|
414
586
|
const state = await options.harness().snapshot(OptChatState, id, options.context);
|
|
415
587
|
const failures = Object.entries(state?.failures ?? {}).filter(([key, failure]) => { const [level, index] = key.split(':').map(Number); return failure.of === s.log.fp(level, index); }).map(([, failure]) => failure);
|
|
416
588
|
const busy = (await options.harness().inspect(options.context)).tasks.filter(task => task.record.kind === taskKind && task.record.conversationId === id).length;
|
|
417
|
-
const retrying = failures.filter(failure => Date.now() - failure.at <
|
|
589
|
+
const retrying = failures.filter(failure => Date.now() - failure.at < retryDelay(failure)).length;
|
|
418
590
|
const latest = failures.reduce((best, failure) => !best || failure.at > best.at ? failure : best, undefined);
|
|
419
591
|
return {
|
|
420
592
|
leaves: s.log.leaves.length, summaries,
|
|
@@ -426,7 +598,8 @@ export function createOptChatMemory(options) {
|
|
|
426
598
|
},
|
|
427
599
|
async zoom(id, nth, n) { return zoomText((await refresh(id)).tree, nth, n); },
|
|
428
600
|
async date(id, nth) { return dateText((await refresh(id)).log, nth); },
|
|
601
|
+
forgetMessage,
|
|
429
602
|
forget(id) { sessions.delete(String(id)); },
|
|
430
|
-
async dispose() { aborter.abort(); },
|
|
603
|
+
async dispose() { aborter.abort(); await Promise.allSettled(naps.values()); },
|
|
431
604
|
};
|
|
432
605
|
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Higher Order Company
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|