piroboros 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +39 -0
  4. package/README.md +219 -2
  5. package/agents/astrelia.md +31 -0
  6. package/agents/avaritia.md +31 -0
  7. package/agents/elaria.md +31 -0
  8. package/agents/nytheria.md +32 -0
  9. package/agents/raskreia.md +32 -0
  10. package/agents/samaela.md +40 -0
  11. package/agents/vaelia.md +35 -0
  12. package/agents/vesperia.md +45 -0
  13. package/bin/piroboros.mjs +17 -0
  14. package/dist/auth.js +105 -0
  15. package/dist/base.js +19 -0
  16. package/dist/chat/budget.js +87 -0
  17. package/dist/chat/compactloop.js +63 -0
  18. package/dist/chat/compactor.js +529 -0
  19. package/dist/chat/extension.js +36 -0
  20. package/dist/chat/hook.js +40 -0
  21. package/dist/chat/log.js +316 -0
  22. package/dist/chat/outbound.js +114 -0
  23. package/dist/chat/plan.js +63 -0
  24. package/dist/chat/prompt.js +115 -0
  25. package/dist/chat/status.js +37 -0
  26. package/dist/chat/stuck.js +83 -0
  27. package/dist/chat/tools.js +163 -0
  28. package/dist/chat/tree.js +72 -0
  29. package/dist/chat/turn.js +305 -0
  30. package/dist/chat/view.js +163 -0
  31. package/dist/conclave/agents.js +113 -0
  32. package/dist/conclave/pipeline.js +715 -0
  33. package/dist/conclave/report.js +43 -0
  34. package/dist/config.js +608 -0
  35. package/dist/durable.js +112 -0
  36. package/dist/guard.js +346 -0
  37. package/dist/lock.js +56 -0
  38. package/dist/main.js +354 -0
  39. package/dist/memory/akashic/api.js +121 -0
  40. package/dist/memory/akashic/confusables.js +41 -0
  41. package/dist/memory/akashic/scanner.js +67 -0
  42. package/dist/memory/akashic/snapshot.js +31 -0
  43. package/dist/memory/akashic/store.js +1254 -0
  44. package/dist/memory/akashic/tools.js +168 -0
  45. package/dist/memory/akashic/vault.js +984 -0
  46. package/dist/memory/host.js +124 -0
  47. package/dist/memory/mnemosia/adapters/akashic-memories.js +180 -0
  48. package/dist/memory/mnemosia/adapters/contract.js +219 -0
  49. package/dist/memory/mnemosia/agents.js +387 -0
  50. package/dist/memory/mnemosia/brief.js +890 -0
  51. package/dist/memory/mnemosia/claims.js +609 -0
  52. package/dist/memory/mnemosia/conflicts.js +769 -0
  53. package/dist/memory/mnemosia/escalation.js +257 -0
  54. package/dist/memory/mnemosia/feedback.js +108 -0
  55. package/dist/memory/mnemosia/filters.js +248 -0
  56. package/dist/memory/mnemosia/intent.js +221 -0
  57. package/dist/memory/mnemosia/open.js +34 -0
  58. package/dist/memory/mnemosia/orchestrator.js +926 -0
  59. package/dist/memory/mnemosia/plan.js +266 -0
  60. package/dist/memory/mnemosia/policy.js +426 -0
  61. package/dist/memory/mnemosia/progressive.js +550 -0
  62. package/dist/memory/mnemosia/provenance.js +458 -0
  63. package/dist/memory/mnemosia/qualifiers.js +428 -0
  64. package/dist/memory/mnemosia/rank.js +525 -0
  65. package/dist/memory/mnemosia/relations.js +156 -0
  66. package/dist/memory/mnemosia/requirements.js +138 -0
  67. package/dist/memory/mnemosia/rerank.js +253 -0
  68. package/dist/memory/mnemosia/retention.js +174 -0
  69. package/dist/memory/mnemosia/rollback.js +337 -0
  70. package/dist/memory/mnemosia/select.js +607 -0
  71. package/dist/memory/mnemosia/similarity.js +164 -0
  72. package/dist/memory/mnemosia/situation.js +251 -0
  73. package/dist/memory/mnemosia/task.js +418 -0
  74. package/dist/memory/mnemosia/temporal.js +136 -0
  75. package/dist/memory/mnemosia/tokens.js +66 -0
  76. package/dist/memory/mnemosia/tools.js +160 -0
  77. package/dist/memory/mnemosia/trace.js +306 -0
  78. package/dist/memory/mnemosia/types.js +298 -0
  79. package/dist/models.js +360 -0
  80. package/dist/paths.js +103 -0
  81. package/dist/redact.js +79 -0
  82. package/dist/runtime.js +354 -0
  83. package/dist/search-format.js +102 -0
  84. package/dist/search.js +351 -0
  85. package/dist/setup.js +366 -0
  86. package/dist/shell.js +110 -0
  87. package/dist/skills.js +311 -0
  88. package/dist/tui/app.js +1009 -0
  89. package/dist/tui/commands.js +120 -0
  90. package/dist/tui/keys.js +83 -0
  91. package/dist/tui/pane.js +387 -0
  92. package/dist/tui/panel.js +60 -0
  93. package/dist/tui/picker.js +25 -0
  94. package/dist/tui/sanitize.js +59 -0
  95. package/dist/tui/settings.js +198 -0
  96. package/dist/tui/setup.js +256 -0
  97. package/dist/tui/theme.js +26 -0
  98. package/dist/tui/thinking/parse.js +1094 -0
  99. package/dist/tui/thinking/select.js +86 -0
  100. package/dist/tui/thinking/state.js +137 -0
  101. package/dist/tui/thinking/types.js +3 -0
  102. package/dist/tui/thinking/view.js +74 -0
  103. package/dist/tui/viewport.js +208 -0
  104. package/dist/undo.js +258 -0
  105. package/dist/web.js +933 -0
  106. package/models.json.example +34 -0
  107. package/package.json +62 -4
  108. package/settings.json.example +28 -0
  109. package/skills/conclave/SKILL.md +76 -0
@@ -0,0 +1,529 @@
1
+ import { compactorStatus, withDefaults } from "../config.js";
2
+ import { ctx, defineExtension, defineTask, ROOT } from "../durable.js";
3
+ import { resolveModel } from "../models.js";
4
+ import { redactOutbound, redactSensitive } from "../redact.js";
5
+ import { CursorDoc, emptyQueue, joinUp, kindLabel, nodeKey, NodeDoc, partText, QueueDoc, readRow, snapshotNodeText } from "./log.js";
6
+ import { collectLiterals, newScrubMemo, outboundVerdict, scrubLines } from "./outbound.js";
7
+ import { CHAT_PROMPT, compactMergeTask, compactMessageTask, tooLongRetry } from "./prompt.js";
8
+ import { applyView, CviewDoc, planAdvance, ViewDoc } from "./tree.js";
9
+ import { lineBytes, lineFirst, lineSize, lineText, NODE_TEXT_MAX, shrink, utf8Bytes } from "./view.js";
10
+ // The compactor (D6, D7): BuildNode tasks that write the model-made nodes, the compact pass that feeds them and
11
+ // joins their results, and the gate that makes a turn wait for them. Nodes are created only in the commit that has
12
+ // just built them (a BuildNode completion, or an inline join), and existence is read by snapshot, never probed with
13
+ // tx.doc. Requests carry no tools. Anything that leaves the machine goes through `outbound` at the moment it is sent.
14
+ export const CVIEW_MAX = 32_000;
15
+ export const CVIEW_TARGET = 16_000;
16
+ export const MAX_CALLS = 5;
17
+ export const MAX_ERRORS = 3;
18
+ /** One compactor request may take this long; a longer one is cut and counts as a provider error. */
19
+ export const COMPACTOR_REQUEST_TIMEOUT_MS = 300_000;
20
+ /** Provider "busy" replies (HTTP 429 or 503) that one node may retry before they count as errors. */
21
+ export const MAX_BUSY = 20;
22
+ /** A busy reply waits this many times longer than an error does. */
23
+ const BUSY_FACTOR = 5;
24
+ /** The message of a failed call starts with its HTTP status, as in "429 model concurrency full". */
25
+ export const isBusy = (message) => message !== undefined && /^\W*(?:HTTP\s*)?(?:status\s*)?(?:429|503)\b/iu.test(message);
26
+ /** Failed tasks in a row that open the breaker. */
27
+ export const BREAKER_STREAK = 3;
28
+ /** How many leaves may be unbuilt before a leaf starts (D6). */
29
+ const LEAF_WINDOW = 8;
30
+ const ERROR_CHARS = 300;
31
+ /** Context-line texts kept between tasks: a 32,000-byte view holds a few hundred lines. */
32
+ const CONTEXT_CACHE_MAX = 4_096;
33
+ const without = (list, item) => {
34
+ const at = list.indexOf(item);
35
+ if (at >= 0)
36
+ list.splice(at, 1);
37
+ };
38
+ const parseKey = (key) => {
39
+ const [level, index] = key.split(":").map(Number);
40
+ return [level, index];
41
+ };
42
+ /**
43
+ * Nodes the queue shows are not built: a node over a leaf still in `leaves` (a parent needs both children), and a node
44
+ * waiting, running or failed. `leaves` is ascending: the index pass appends in message order.
45
+ */
46
+ const unbuiltIn = (queue) => {
47
+ const queued = new Set([...queue.merges, ...queue.running, ...queue.failed]);
48
+ const leaves = Array.from(queue.leaves); // a plain copy: the snapshot's arrays are slow to index
49
+ return (level, index) => {
50
+ if (queued.has(nodeKey(level, index)))
51
+ return true;
52
+ const lo = index * 2 ** level;
53
+ let a = 0;
54
+ let b = leaves.length;
55
+ while (a < b) {
56
+ const mid = (a + b) >> 1;
57
+ if (leaves[mid] < lo)
58
+ a = mid + 1;
59
+ else
60
+ b = mid;
61
+ }
62
+ return a < leaves.length && leaves[a] < lo + 2 ** level;
63
+ };
64
+ };
65
+ const oneLine = (text) => text.replace(/\s+/gu, " ").trim().slice(0, ERROR_CHARS);
66
+ export class Compactor {
67
+ extension;
68
+ deps;
69
+ harness;
70
+ /** Set when a gate gave up; cleared when a node is built. D7 keeps it in memory. */
71
+ tripped;
72
+ task;
73
+ /** Scrub results by chunk for each strictness, bounded by scrubLines; cleared when the credential literals change. */
74
+ memos = new Map();
75
+ memoSignature = "";
76
+ /** Texts of built nodes read as prompt context; see rebuild. */
77
+ contextTexts = new Map();
78
+ constructor(deps) {
79
+ this.deps = deps;
80
+ this.task = makeTask(this);
81
+ this.extension = defineExtension({ name: "compactor", tasks: [this.task] });
82
+ }
83
+ bind(harness) {
84
+ this.harness = harness;
85
+ }
86
+ get h() {
87
+ if (this.harness === undefined)
88
+ throw new Error("the compactor is not bound to a harness");
89
+ return this.harness;
90
+ }
91
+ settings() {
92
+ return this.deps.settings();
93
+ }
94
+ requestTimeoutMs() {
95
+ return this.deps.requestTimeoutMs ?? COMPACTOR_REQUEST_TIMEOUT_MS;
96
+ }
97
+ backoff(tries) {
98
+ const list = this.deps.backoffMs ?? [1_000, 2_000];
99
+ return list[Math.min(tries, list.length) - 1] ?? 0;
100
+ }
101
+ /** The wait after the `busy`-th busy reply of one node. */
102
+ busyBackoff(busy) {
103
+ return this.backoff(Math.min(busy, 2)) * (busy >= 3 ? 2 : 1) * BUSY_FACTOR; // 1, 2, then 4 seconds times the factor
104
+ }
105
+ /** The state of the compactor now. Evaluated on every call, so a changed setting applies at once. */
106
+ state() {
107
+ const settings = this.deps.settings();
108
+ const label = compactorStatus(settings);
109
+ if (label === "not configured")
110
+ return { label, reason: "no compactor model is set" };
111
+ if (label === "disabled")
112
+ return { label, reason: "compactor.enabled is false" };
113
+ const verdict = outboundVerdict(settings, resolveModel(this.deps.models, settings.compactor.model));
114
+ return verdict.ok ? { label } : { label: "disabled", reason: verdict.reason };
115
+ }
116
+ /** Remove what must not leave the machine from `text`; a failure to read auth.json fails the request. */
117
+ scrubFor(strict) {
118
+ const literals = collectLiterals(this.deps.authPath, this.deps.env);
119
+ // The memo is only valid for one set of literals: a changed credential starts it over.
120
+ const signature = literals.join("\0");
121
+ if (signature !== this.memoSignature) {
122
+ this.memos.clear();
123
+ this.memoSignature = signature;
124
+ }
125
+ const memo = this.memos.get(strict) ?? newScrubMemo();
126
+ this.memos.set(strict, memo);
127
+ return (text) => scrubLines(text, (part) => redactOutbound(part, { literals, strict }), memo, literals);
128
+ }
129
+ /** A failure message that is safe to store and show. It never throws. */
130
+ clean(message) {
131
+ try {
132
+ return oneLine(this.scrubFor(true)(message));
133
+ }
134
+ catch {
135
+ return oneLine(redactSensitive(message));
136
+ }
137
+ }
138
+ systemPrompt() {
139
+ const own = this.deps.instructions?.();
140
+ return own === undefined ? CHAT_PROMPT : `${CHAT_PROMPT}\n\n${own}`;
141
+ }
142
+ open(queue) {
143
+ if (this.tripped !== undefined)
144
+ return this.tripped;
145
+ return queue.streak >= BREAKER_STREAK ? `${queue.streak} builds failed in a row` : undefined;
146
+ }
147
+ /* --- the compact pass --------------------------------------------------------------------------------------- */
148
+ /**
149
+ * One pass: join the parents of finished nodes, advance the compaction view, retry failed nodes after a new
150
+ * message, and start tasks up to the concurrency cap. Returns true when it changed anything, so the caller loops.
151
+ */
152
+ async pass() {
153
+ const harness = this.h;
154
+ const queue = await harness.snapshot(QueueDoc, ctx);
155
+ if (queue === undefined)
156
+ return false;
157
+ const cursor = await harness.snapshot(CursorDoc, ctx);
158
+ const T = cursor?.T ?? 0;
159
+ const configured = this.state().label === "configured";
160
+ const done = queue.completed.slice(0, 64);
161
+ if (done.length > 0)
162
+ this.tripped = undefined;
163
+ const created = new Map();
164
+ const wanted = new Set();
165
+ // Nothing commits during the walk, so a node read once (built or not) is not read again by this pass.
166
+ const seen = new Map();
167
+ const lookup = async (level, index) => {
168
+ const key = nodeKey(level, index);
169
+ const made = created.get(key);
170
+ if (made !== undefined)
171
+ return made;
172
+ if (!seen.has(key))
173
+ seen.set(key, await snapshotNodeText(harness, level, index));
174
+ return seen.get(key);
175
+ };
176
+ for (const key of done) {
177
+ const [level, index] = parseKey(key);
178
+ const text = await lookup(level, index);
179
+ if (text !== undefined)
180
+ await joinUp(level, index, text, created, wanted, lookup);
181
+ }
182
+ const view = await harness.snapshot(ViewDoc, ctx);
183
+ const batch = view?.batchSeq ?? 0;
184
+ const before = await harness.snapshot(CviewDoc, ctx);
185
+ const target = Math.max(before?.T ?? 0, Math.min(queue.leaves[0] ?? T, T));
186
+ // It merges down to 16,000 when the chat view has batched, and keeps going while a merge was waiting for a parent.
187
+ const next = await planAdvance(harness, before, target, CVIEW_MAX, CVIEW_TARGET, (v, nodes) => { if (v.shrinking || batch !== queue.cviewBatch)
188
+ shrink(v, nodes, CVIEW_MAX, CVIEW_TARGET); }, unbuiltIn(queue));
189
+ const viewChanged = next.T !== (before?.T ?? 0) || next.bytes !== (before?.bytes ?? 0) || next.lines.length !== (before?.lines.length ?? 0);
190
+ const starts = [];
191
+ let changed = done.length > 0 || created.size > 0 || wanted.size > 0 || viewChanged || batch !== queue.cviewBatch;
192
+ await harness.commit(async (tx) => {
193
+ const q = await tx.doc(QueueDoc);
194
+ for (const [key, text] of created)
195
+ await tx.doc(NodeDoc, key, { text, bytes: utf8Bytes(text) });
196
+ for (const key of done)
197
+ without(q.completed, key);
198
+ const listed = (key) => q.merges.includes(key) || q.running.includes(key) || q.failed.includes(key);
199
+ for (const key of wanted)
200
+ if (!listed(key))
201
+ q.merges.push(key);
202
+ if (T > q.seenT) {
203
+ // A new message is the retry signal for failed nodes. Failed leaves stay in `leaves`; failed merges go back in line.
204
+ for (const key of q.failed.splice(0))
205
+ if (parseKey(key)[0] > 0 && !q.merges.includes(key))
206
+ q.merges.push(key);
207
+ q.seenT = T;
208
+ changed = true;
209
+ }
210
+ if (viewChanged)
211
+ await applyView(tx, before, next, CviewDoc);
212
+ q.cviewBatch = batch;
213
+ if (configured) {
214
+ const cap = Math.min(8, withDefaults(this.deps.settings()).compactor.maxConcurrent, this.open(q) === undefined ? 8 : 1);
215
+ const slots = cap - q.running.length;
216
+ const keys = [];
217
+ for (const id of q.leaves.slice(0, LEAF_WINDOW))
218
+ if (keys.length < slots && !q.running.includes(nodeKey(0, id)) && !q.failed.includes(nodeKey(0, id)))
219
+ keys.push(nodeKey(0, id));
220
+ while (keys.length < slots && q.merges.length > 0)
221
+ keys.push(q.merges.shift());
222
+ for (const key of keys) {
223
+ q.running.push(key);
224
+ starts.push(parseKey(key));
225
+ }
226
+ }
227
+ for (const [level, index] of starts)
228
+ await tx.createTask(this.task, { level, index }, { ownership: { kind: "conversation" }, conversationId: ROOT, background: true });
229
+ }, ctx);
230
+ return changed || starts.length > 0;
231
+ }
232
+ /* --- the gate (D7) ------------------------------------------------------------------------------------------ */
233
+ /** Wait until every leaf below `T` is built, the breaker opens, or `gateTimeoutMs` passes. The turn proceeds either way. */
234
+ async gate(T, signal) {
235
+ const harness = this.h;
236
+ if (this.state().label !== "configured")
237
+ return { kind: "skipped" };
238
+ const deadline = Date.now() + withDefaults(this.deps.settings()).gateTimeoutMs;
239
+ while (signal?.aborted !== true) {
240
+ const queue = (await harness.snapshot(QueueDoc, ctx)) ?? emptyQueue();
241
+ if ((queue.leaves[0] ?? T) >= T)
242
+ return { kind: "built" };
243
+ const open = this.open(queue);
244
+ if (open !== undefined)
245
+ return { kind: "degraded", message: `compactor degraded (${open}); this turn's view shows placeholders for unbuilt lines` };
246
+ const left = deadline - Date.now();
247
+ if (left <= 0) {
248
+ this.tripped = "the gate timed out";
249
+ return { kind: "degraded", message: `compactor too slow: the gate timed out after ${Math.round(withDefaults(this.deps.settings()).gateTimeoutMs / 1000)} s; this turn's view shows placeholders for unbuilt lines until a node is built` };
250
+ }
251
+ // The wait ends at the next commit, at the stop signal, or after 250 ms, whichever comes first.
252
+ let unsubscribe = () => { };
253
+ let timer;
254
+ let wake = () => { };
255
+ await new Promise((resolve) => {
256
+ wake = resolve;
257
+ unsubscribe = harness.subscribeCommits(() => resolve());
258
+ timer = setTimeout(resolve, Math.min(left, 250));
259
+ signal?.addEventListener("abort", wake, { once: true });
260
+ }).finally(() => {
261
+ unsubscribe();
262
+ clearTimeout(timer);
263
+ signal?.removeEventListener("abort", wake);
264
+ });
265
+ }
266
+ return { kind: "skipped" };
267
+ }
268
+ /* --- status ------------------------------------------------------------------------------------------------- */
269
+ async report() {
270
+ const queue = (await this.h.snapshot(QueueDoc, ctx)) ?? emptyQueue();
271
+ const state = this.state();
272
+ const settings = this.deps.settings();
273
+ const breaker = this.open(queue);
274
+ return {
275
+ ...state,
276
+ ...(settings.compactor?.model === undefined ? {} : { model: settings.compactor.model }),
277
+ maxConcurrent: withDefaults(settings).compactor.maxConcurrent,
278
+ waiting: queue.leaves.length + queue.merges.length + queue.failed.filter((key) => parseKey(key)[0] > 0).length,
279
+ inFlight: queue.running.length,
280
+ built: queue.built,
281
+ retries: queue.retries,
282
+ busyRetries: queue.busy ?? 0,
283
+ breaker: breaker === undefined ? "closed" : "open",
284
+ ...(breaker === undefined ? {} : { breakerReason: breaker }),
285
+ lastError: queue.lastError,
286
+ };
287
+ }
288
+ /** The line the TUI keeps on screen when the compactor is not doing its job, or undefined. */
289
+ async note() {
290
+ const state = this.state();
291
+ if (state.label === "not configured")
292
+ return undefined;
293
+ if (state.label === "disabled")
294
+ return `compactor disabled: ${state.reason}`;
295
+ const open = this.open((await this.h.snapshot(QueueDoc, ctx)) ?? emptyQueue());
296
+ return open === undefined ? undefined : `compactor degraded (${open}); lines that are not summarized yet show as placeholders`;
297
+ }
298
+ }
299
+ const textOf = (message) => message.content.filter((block) => block.type === "text").map((block) => block.text ?? "").join("").replace(/\r\n?/gu, "\n").replace(/^\d+\+\d+\|/u, "").trim();
300
+ /** The first 512 bytes of a reply, for the "Too long" retry. */
301
+ const cut = (text) => Buffer.from(text).subarray(0, NODE_TEXT_MAX).toString("utf8").replace(/�+$/u, "");
302
+ /**
303
+ * The last resort when every try stayed over the limit: `text` cut to at most `max` bytes, at the last clause boundary
304
+ * (`; `, `. ` or `, `), else at the last space, else at the byte limit. The cut never splits a character.
305
+ */
306
+ export function clauseCut(text, max = NODE_TEXT_MAX) {
307
+ const bytes = Buffer.from(text);
308
+ if (bytes.length <= max)
309
+ return text;
310
+ let end = max;
311
+ while (end > 0 && (bytes[end] & 0xc0) === 0x80)
312
+ end -= 1; // the byte at `end` would start in the middle of a character
313
+ const head = bytes.subarray(0, end).toString("utf8");
314
+ const clause = Math.max(head.lastIndexOf("; "), head.lastIndexOf(". "), head.lastIndexOf(", "));
315
+ if (clause > 0)
316
+ return head.slice(0, clause + 1);
317
+ const space = head.lastIndexOf(" ");
318
+ return (space > 0 ? head.slice(0, space) : head).trimEnd();
319
+ }
320
+ const shortest = (replies) => replies.reduce((best, reply) => (utf8Bytes(reply) < utf8Bytes(best) ? reply : best));
321
+ /** Contiguous view lines from message `first`, as their levels run-length coded: "40:5*3,4*1" is three level-5 lines from message 40, then one level-4 line. */
322
+ export const packShape = (first, levels) => {
323
+ if (levels.length === 0)
324
+ return "";
325
+ const runs = [];
326
+ for (let k = 0; k < levels.length;) {
327
+ let n = 1;
328
+ while (levels[k + n] === levels[k])
329
+ n += 1;
330
+ runs.push(`${levels[k]}*${n}`);
331
+ k += n;
332
+ }
333
+ return `${first}:${runs.join(",")}`;
334
+ };
335
+ /**
336
+ * The request text of a node, from committed data alone: the message (or the two built halves) for the task, and the
337
+ * node texts of the context lines for the chat. Nodes and log rows never change once written, so the same node and
338
+ * shape give the same bytes on every call, before or after a restart.
339
+ */
340
+ export async function rebuild(runtime, context, input, shape, texts = new Map()) {
341
+ const { level, index } = input;
342
+ let task;
343
+ if (level === 0) {
344
+ const row = await readRow(runtime, index);
345
+ const entry = row === undefined ? undefined : await runtime.entry(row[0], context);
346
+ const text = row === undefined || entry === undefined ? undefined : partText(entry, row[1]);
347
+ if (row === undefined || text === undefined)
348
+ throw new Error(`message ${index} cannot be read for compaction`);
349
+ task = compactMessageTask(index, kindLabel(row[2]), text);
350
+ }
351
+ else {
352
+ const size = 2 ** level;
353
+ const first = index * size;
354
+ const half = size / 2;
355
+ const a = await snapshotNodeText(runtime, level - 1, index * 2);
356
+ const b = await snapshotNodeText(runtime, level - 1, index * 2 + 1);
357
+ if (a === undefined || b === undefined)
358
+ throw new Error(`the halves of ${first}+${size} are not both built`);
359
+ const one = (id, text) => `${id}+${half}|${text.replace(/\n/gu, " ")}`;
360
+ task = compactMergeTask(`${first}+${half}`, `${first + half}+${half}`, first, first + size - 1, one(first, a), one(first + half, b));
361
+ }
362
+ let lines = "";
363
+ const [start, runs] = shape === "" ? ["0", ""] : shape.split(":");
364
+ let first = Number(start);
365
+ for (const run of runs === "" ? [] : runs.split(",")) {
366
+ const [l, count] = run.split("*").map(Number);
367
+ for (let k = 0; k < count; k += 1) {
368
+ const at = first / 2 ** l;
369
+ const key = nodeKey(l, at);
370
+ // A built node never changes, so `texts` (the caller's bounded cache, first in first out) may hold it for good.
371
+ let text = texts.get(key);
372
+ if (text === undefined) {
373
+ text = await snapshotNodeText(runtime, l, at);
374
+ if (text === undefined)
375
+ throw new Error(`node ${key} of the context is missing`);
376
+ texts.set(key, text);
377
+ if (texts.size > CONTEXT_CACHE_MAX)
378
+ texts.delete(texts.keys().next().value);
379
+ }
380
+ lines += lineText([l, at, text]);
381
+ first += 2 ** l;
382
+ }
383
+ }
384
+ return { chat: `<chat>\n${lines}</chat>`, task };
385
+ }
386
+ function makeTask(compactor) {
387
+ const settle = async (runtime, context, input, change, outcome) => {
388
+ const key = nodeKey(input.level, input.index);
389
+ await runtime.commit(async (tx) => {
390
+ const q = await tx.doc(QueueDoc);
391
+ change(q);
392
+ const live = q.running.includes(key);
393
+ without(q.running, key);
394
+ if (outcome.error !== undefined) {
395
+ if (!q.failed.includes(key))
396
+ q.failed.push(key);
397
+ q.streak += 1;
398
+ q.lastError = outcome.error;
399
+ return { status: "terminal", outcome: { status: "failed", error: { message: outcome.error } } };
400
+ }
401
+ const text = outcome.text;
402
+ // A task whose key is no longer running has been settled elsewhere; it creates nothing.
403
+ if (live) {
404
+ if (input.level === 0)
405
+ without(q.leaves, input.index);
406
+ q.completed.push(key);
407
+ q.built += 1;
408
+ q.streak = 0;
409
+ await tx.doc(NodeDoc, key, { text, bytes: utf8Bytes(text) });
410
+ }
411
+ return { status: "terminal", outcome: { status: "completed", result: { key, bytes: utf8Bytes(text), calls: outcome.calls ?? 0 } } };
412
+ }, context);
413
+ };
414
+ const fail = (runtime, context, input, message) => settle(runtime, context, input, () => { }, { error: compactor.clean(message) });
415
+ return defineTask({
416
+ name: "piroboros.buildNode",
417
+ version: 2,
418
+ initial: () => ({ phase: "prepare" }),
419
+ phases: {
420
+ prepare: async (task, runtime, context) => {
421
+ const { level, index } = task.input;
422
+ try {
423
+ // Context: the built lines of the compaction view that end before the node (D5), kept as their levels only. The view
424
+ // is 32,000 bytes when the compactor keeps up; when it lags the view cannot merge and grows, so the newest 32,000 bytes are used.
425
+ const last = level === 0 ? index - 1 : (index + 1) * 2 ** level - 1;
426
+ const cview = await runtime.snapshot(CviewDoc, context);
427
+ const built = [];
428
+ for (const line of cview?.lines ?? []) {
429
+ if (line[2] === null || lineFirst(line) + lineSize(line) - 1 > last)
430
+ break;
431
+ built.push([line[0], line[1], line[2]]);
432
+ }
433
+ let from = built.length;
434
+ for (let bytes = 0; from > 0 && bytes + lineBytes(built[from - 1]) <= CVIEW_MAX; from -= 1)
435
+ bytes += lineBytes(built[from - 1]);
436
+ const kept = built.slice(from);
437
+ await runtime.commit(() => ({ status: "running", checkpoint: { phase: "ask", shape: packShape(kept.length === 0 ? 0 : lineFirst(kept[0]), kept.map((line) => line[0])), replies: [], calls: 0, errors: 0, at: runtime.now() } }), context);
438
+ }
439
+ catch (error) {
440
+ runtime.signal.throwIfAborted();
441
+ await fail(runtime, context, task.input, error instanceof Error ? error.message : String(error));
442
+ }
443
+ },
444
+ ask: async (task, runtime, context) => {
445
+ const cp = task.state.checkpoint;
446
+ try {
447
+ // Every request re-reads the settings: the model, the consent and the credentials are checked now.
448
+ const settings = compactor.settings();
449
+ const model = compactorStatus(settings) === "configured" ? resolveModel(runtime.models, settings.compactor.model) : undefined;
450
+ const verdict = model === undefined ? { ok: false, reason: "the compactor is not configured or its model is not available" } : outboundVerdict(settings, model);
451
+ if (model === undefined || !verdict.ok)
452
+ return await fail(runtime, context, task.input, `not sent: ${verdict.ok ? "no model" : verdict.reason}`);
453
+ const scrub = compactor.scrubFor(verdict.strict);
454
+ const stamp = cp.at;
455
+ const built = await rebuild(runtime, context, task.input, cp.shape, compactor.contextTexts);
456
+ const messages = [{ role: "user", content: [{ type: "text", text: scrub(built.chat) }, { type: "text", text: scrub(built.task) }], timestamp: stamp }];
457
+ for (const reply of cp.replies) {
458
+ messages.push({ role: "assistant", content: [{ type: "text", text: scrub(reply) }], api: model.api, provider: model.provider, model: model.id, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, stopReason: "stop", timestamp: stamp });
459
+ messages.push({ role: "user", content: [{ type: "text", text: tooLongRetry(utf8Bytes(reply), scrub(cut(reply))) }], timestamp: stamp });
460
+ }
461
+ const thinking = withDefaults(settings).compactor.thinking;
462
+ const reply = await runtime.models.completeSimple(model, { systemPrompt: scrub(compactor.systemPrompt()), messages }, {
463
+ signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(compactor.requestTimeoutMs())]),
464
+ maxTokens: model.maxTokens > 0 ? Math.min(model.maxTokens, 8_192) : 8_192,
465
+ ...(thinking === "off" ? {} : { reasoning: thinking }),
466
+ });
467
+ runtime.signal.throwIfAborted();
468
+ const usage = reply.usage;
469
+ const spend = (q) => {
470
+ q.usage.calls += 1;
471
+ q.usage.input += usage?.input ?? 0;
472
+ q.usage.output += usage?.output ?? 0;
473
+ q.usage.cacheRead += usage?.cacheRead ?? 0;
474
+ q.usage.cacheWrite += usage?.cacheWrite ?? 0;
475
+ };
476
+ if (reply.stopReason === "error" || reply.stopReason === "aborted") {
477
+ const message = compactor.clean(reply.errorMessage ?? "the provider returned an error");
478
+ // A busy provider (429, 503) is waited out with a longer backoff and no strike, up to MAX_BUSY times for this node.
479
+ const busy = (cp.busy ?? 0) + 1;
480
+ if (isBusy(reply.errorMessage) && busy <= MAX_BUSY) {
481
+ await runtime.commit(async (tx) => {
482
+ const q = await tx.doc(QueueDoc);
483
+ spend(q);
484
+ q.busy = (q.busy ?? 0) + 1;
485
+ q.lastError = message;
486
+ return { status: "running", checkpoint: { ...cp, busy } };
487
+ }, context);
488
+ return await runtime.sleep(runtime.now() + compactor.busyBackoff(busy), context);
489
+ }
490
+ const errors = cp.errors + 1;
491
+ if (errors >= MAX_ERRORS)
492
+ return await settle(runtime, context, task.input, spend, { error: `${message} (after ${errors} tries)` });
493
+ await runtime.commit(async (tx) => {
494
+ const q = await tx.doc(QueueDoc);
495
+ spend(q);
496
+ q.retries += 1;
497
+ q.lastError = message;
498
+ return { status: "running", checkpoint: { ...cp, errors } };
499
+ }, context);
500
+ return await runtime.sleep(runtime.now() + compactor.backoff(errors), context);
501
+ }
502
+ const text = textOf(reply);
503
+ const calls = cp.calls + 1;
504
+ const replies = text === "" || utf8Bytes(text) <= NODE_TEXT_MAX ? cp.replies : [...cp.replies, text];
505
+ if (text !== "" && utf8Bytes(text) <= NODE_TEXT_MAX)
506
+ return await settle(runtime, context, task.input, spend, { text, calls });
507
+ if (calls >= MAX_CALLS) {
508
+ if (replies.length === 0)
509
+ return await settle(runtime, context, task.input, spend, { error: "the compactor returned no text" });
510
+ return await settle(runtime, context, task.input, spend, { text: clauseCut(shortest(replies)), calls });
511
+ }
512
+ await runtime.commit(async (tx) => {
513
+ const q = await tx.doc(QueueDoc);
514
+ spend(q);
515
+ q.retries += 1;
516
+ return { status: "running", checkpoint: { ...cp, calls, replies } };
517
+ }, context);
518
+ }
519
+ catch (error) {
520
+ runtime.signal.throwIfAborted();
521
+ await fail(runtime, context, task.input, error instanceof Error ? error.message : String(error));
522
+ }
523
+ },
524
+ },
525
+ abort: async (task, runtime, context) => {
526
+ await settle(runtime, context, task.input, () => { }, { error: "the build was aborted" });
527
+ },
528
+ });
529
+ }
@@ -0,0 +1,36 @@
1
+ import { CompactionTask, defineExtension, hook, section } from "../durable.js";
2
+ import { budgetHook } from "./budget.js";
3
+ import { viewHook } from "./hook.js";
4
+ import { planTool } from "./plan.js";
5
+ import { CHAT_PROMPT, VIEWTOOLS_LEGEND } from "./prompt.js";
6
+ import { createStuckHooks } from "./stuck.js";
7
+ import { dateTool, zoomTool } from "./tools.js";
8
+ // The extensions of D12 that belong to the chat design. The tool set and every section are static, so the system
9
+ // prompt and the tool declarations are byte-identical from turn to turn.
10
+ /** zoom, date and the view legend. Root and children. */
11
+ export const viewtools = defineExtension({
12
+ name: "viewtools",
13
+ tools: [zoomTool, dateTool],
14
+ sections: [section("view", () => VIEWTOOLS_LEGEND)],
15
+ });
16
+ /** The full prompt, the view insertion and the compaction decline. Root only. */
17
+ export const chat = defineExtension({
18
+ name: "chat",
19
+ sections: [section("chat", () => CHAT_PROMPT, { tag: false })],
20
+ hooks: [viewHook, hook(CompactionTask, { beforeCompact: () => ({ decline: true }) })],
21
+ });
22
+ /** Last in every conversation: the staged trimming of the current turn. */
23
+ export const budget = defineExtension({
24
+ name: "budget",
25
+ hooks: [budgetHook],
26
+ });
27
+ /** The plan tool (H5). Left out of the selection when settings.planning is false. */
28
+ export const planning = defineExtension({
29
+ name: "planning",
30
+ tools: [planTool],
31
+ });
32
+ /** Stuck detection (H3), with its own streak state. One per runtime. */
33
+ export function createStuck(onStop) {
34
+ const { hooks, endRun } = createStuckHooks(onStop);
35
+ return Object.assign(defineExtension({ name: "stuck", hooks }), { endRun });
36
+ }
@@ -0,0 +1,40 @@
1
+ import { ctx, GenerationTask, hook } from "../durable.js";
2
+ import { PlanDoc, planBlock } from "./plan.js";
3
+ import { TurnStateDoc, ViewDoc } from "./tree.js";
4
+ import { renderLines, viewBlocks } from "./view.js";
5
+ // The beforeRequest hook (D1, D21): request = [tools][static system][view][per-turn state + new message(s)]
6
+ // [current-turn entries]. The view is inserted into the first user message as separate text blocks, so the
7
+ // stored transcript never holds it. The hook reads committed documents only, so a rerun gives the same bytes.
8
+ const pad = (n, width = 2) => String(n).padStart(width, "0");
9
+ /** `2026-10-11 14:03:22 UTC+02:00`, in the local zone, with the offset that applied at that moment. */
10
+ export function formatDate(ms) {
11
+ const d = new Date(ms);
12
+ const offset = -d.getTimezoneOffset();
13
+ const sign = offset < 0 ? "-" : "+";
14
+ const abs = Math.abs(offset);
15
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())} UTC${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`;
16
+ }
17
+ export const turnBlock = (turn) => `<turn>${formatDate(turn.at)}; cwd: ${turn.cwd}</turn>`;
18
+ /** Insert the view and the per-turn block into the first user message. Undefined when there is no user message. */
19
+ export function insertView(messages, lines, turn, plan = []) {
20
+ const at = messages.findIndex((message) => message.role === "user");
21
+ if (at < 0)
22
+ return undefined;
23
+ const first = messages[at];
24
+ const rendered = renderLines(lines, turn?.windowStart ?? 0, turn?.compactor ?? "configured");
25
+ const text = (value) => ({ type: "text", text: value });
26
+ const own = typeof first.content === "string" ? [text(first.content)] : first.content;
27
+ const content = [...viewBlocks(rendered).map(text), ...(turn === undefined ? [] : [text(turnBlock(turn))]), ...(plan.length === 0 ? [] : [text(planBlock(plan))]), ...own];
28
+ const out = messages.slice();
29
+ out[at] = { ...first, content };
30
+ return out;
31
+ }
32
+ export const viewHook = hook(GenerationTask, {
33
+ async beforeRequest(request, api) {
34
+ const view = await api.snapshot(ViewDoc, ctx);
35
+ const turn = await api.snapshot(TurnStateDoc, ctx);
36
+ const plan = await api.snapshot(PlanDoc, api.conversationId, ctx);
37
+ const messages = insertView(request.messages, (view?.lines ?? []), turn, (plan?.items ?? []));
38
+ return messages === undefined ? undefined : { messages };
39
+ },
40
+ });