ceulen 0.29.2 → 0.31.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.
@@ -0,0 +1,72 @@
1
+ // Spill store — where an oversized tool result's full text is written.
2
+ //
3
+ // Adapted from DeepSeek Harness `packages/spill/spill-local/src/store.ts`.
4
+ // One private temp root per process (DSH's `privateRoot`), one file per spill.
5
+ // `encodeSegment` is DSH's injective escaping: tool names and call ids are not
6
+ // trusted (`../../etc/passwd`, NUL, separators), so each is encoded to a single
7
+ // safe path segment rather than sanitised by deletion (which could collide).
8
+
9
+ import { mkdtempSync } from "node:fs";
10
+ import { mkdir, writeFile } from "node:fs/promises";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+
14
+ /** Prefix of the private per-process root. */
15
+ export const DEFAULT_ROOT_PREFIX = "ceulen-spill-";
16
+
17
+ let defaultRoot: string | undefined;
18
+ /** Monotonic counter making every spill file unique (see saveSpill). */
19
+ let spillSeq = 0;
20
+
21
+ /** The lazily-created private per-process spill root. */
22
+ export function privateRoot(): string {
23
+ defaultRoot ??= mkdtempSync(join(tmpdir(), DEFAULT_ROOT_PREFIX));
24
+ return defaultRoot;
25
+ }
26
+
27
+ /** Test seam: override the root (a path that cannot be created exercises the
28
+ * fail-open path). Passing undefined returns to the lazy temp root. */
29
+ export function setSpillRootForTests(root: string | undefined): void {
30
+ defaultRoot = root;
31
+ }
32
+
33
+ const SAFE = /[A-Za-z0-9._-]/;
34
+
35
+ /**
36
+ * Encode arbitrary text as ONE filesystem-safe path segment, injectively.
37
+ * Each code unit is kept literal when safe (except `~`) or escaped as `~XXXX`;
38
+ * `~` is itself escaped, so distinct inputs never collide. The whole-segment
39
+ * tokens `.` and `..` are escaped so they can never traverse.
40
+ */
41
+ export function encodeSegment(raw: string): string {
42
+ if (raw.length === 0) return "~";
43
+ if (raw === ".") return "~002E";
44
+ if (raw === "..") return "~002E~002E";
45
+ let out = "";
46
+ for (const unit of raw) {
47
+ const code = unit.codePointAt(0) ?? 0;
48
+ if (code > 0xffff) {
49
+ // Non-BMP: encode both surrogate halves so the mapping stays injective.
50
+ for (let i = 0; i < unit.length; i++) out += `~${unit.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")}`;
51
+ continue;
52
+ }
53
+ out += unit !== "~" && SAFE.test(unit) ? unit : `~${code.toString(16).toUpperCase().padStart(4, "0")}`;
54
+ }
55
+ return out;
56
+ }
57
+
58
+ /**
59
+ * Write the full text of one tool result and return its absolute path.
60
+ * Creates the root on first use (a missing parent would otherwise make the
61
+ * write fail and spill would skip silently every time).
62
+ */
63
+ export async function saveSpill(toolName: string, callId: string, text: string): Promise<string> {
64
+ const root = privateRoot();
65
+ await mkdir(root, { recursive: true });
66
+ // Monotonic suffix: a retried call reusing a toolCallId must never overwrite
67
+ // a spill an older transcript entry still points at — each spill is
68
+ // immutable once the model has been told its path.
69
+ const file = join(root, `${encodeSegment(toolName)}-${encodeSegment(callId)}-${++spillSeq}.txt`);
70
+ await writeFile(file, text, { encoding: "utf8", mode: 0o600 });
71
+ return file;
72
+ }
@@ -0,0 +1,287 @@
1
+ // Spill policy — token-budgeted head/tail retention of oversized tool results.
2
+ //
3
+ // Ported from DeepSeek Harness `packages/spill/spill-policy` (retention.ts,
4
+ // notice.ts) + `packages/llm/token-meter/src/estimate.ts` (the fixed-density
5
+ // heuristic). Deliberate deviations, each load-bearing:
6
+ //
7
+ // - NO image retention: pi tool results carry ImageContent only from `read`,
8
+ // and image-bearing reads are excluded from spilling entirely (fail-open:
9
+ // an image result is returned untouched). DSH prices images through a
10
+ // per-route token calculator; pi exposes no such seam to extensions.
11
+ // - ONE notice wording instead of DSH's `describeOmitted` library: that
12
+ // library exists so DSH's browser can RECOGNIZE a persisted notice; ceulen
13
+ // only ever writes one.
14
+ // - Spill is scoped to RETURNED content. pi's read/bash truncate INSIDE the
15
+ // tool before `tool_result` fires (read.js:117 truncateHead at
16
+ // 2000 lines/50KB; bash.js:261-270 sets fullOutputPath), so bytes they drop
17
+ // are already gone. Those paths are excluded; the beneficiaries are the
18
+ // tools with no self-truncation (extension tools: subagent reports, github,
19
+ // web_extract, munin). The exclusion is `details.fullOutputPath` rather than
20
+ // a tool list, which is what covers codemode: it self-truncates at 10,000
21
+ // tokens (execute.js:248) and reports fullOutputPath, so at its default
22
+ // budget it never reaches this seam (live herdr finding).
23
+
24
+ /** Fixed text-density estimate (DSH CHARS_PER_TOKEN). */
25
+ export const CHARS_PER_TOKEN = 4;
26
+ /** Per-block structural overhead for JSON framing and type tags (DSH BLOCK_OVERHEAD). */
27
+ export const BLOCK_OVERHEAD = 4;
28
+ /** DSH's base-preset budget (`packages/bundle/base/cordis.patch.yml` maxInlineTokens). */
29
+ export const DEFAULT_SPILL_MAX_TOKENS = 12_500;
30
+
31
+ /** Text whose head can be split from its tail; images are indivisible. */
32
+ export interface RetainableText {
33
+ type: "text";
34
+ text: string;
35
+ }
36
+
37
+ /** Retained ends plus the exact quantities excluded from the original. */
38
+ export interface RetainedContent {
39
+ head: RetainableText[];
40
+ tail: RetainableText[];
41
+ omittedBytes: number;
42
+ }
43
+
44
+ /** Heuristic token price of one text (DSH estimateContent, text arm). */
45
+ export function estimateTextTokens(text: string): number {
46
+ return Math.ceil(text.length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD;
47
+ }
48
+
49
+ /** Heuristic token price of a block list's text arms. */
50
+ export function estimateTokens(blocks: readonly { type: string; text?: string }[]): number {
51
+ let total = 0;
52
+ for (const block of blocks) {
53
+ if (block.type === "text" && typeof block.text === "string") total += estimateTextTokens(block.text);
54
+ }
55
+ return total;
56
+ }
57
+
58
+ /** Preserve a UTF-16 surrogate pair when a budget cut would split it. */
59
+ export function textSlice(text: string, length: number, tail: boolean): string {
60
+ let cut = tail ? text.length - length : length;
61
+ if (cut <= 0) return tail ? text : "";
62
+ if (cut >= text.length) return tail ? "" : text;
63
+ const previous = text.charCodeAt(cut - 1);
64
+ const current = text.charCodeAt(cut);
65
+ if (previous >= 0xd800 && previous <= 0xdbff && current >= 0xdc00 && current <= 0xdfff) {
66
+ cut += tail ? 1 : -1;
67
+ }
68
+ return tail ? text.slice(cut) : text.slice(0, cut);
69
+ }
70
+
71
+ /** Largest contiguous text end fitting a monotonic token estimate (DSH fitText). */
72
+ export function fitText(text: string, budget: number, tail: boolean): string {
73
+ let low = 0;
74
+ let high = text.length;
75
+ while (low < high) {
76
+ const middle = Math.ceil((low + high) / 2);
77
+ const candidate = textSlice(text, middle, tail);
78
+ if (candidate.length === 0 || estimateTextTokens(candidate) <= budget) low = middle;
79
+ else high = middle - 1;
80
+ }
81
+ return textSlice(text, low, tail);
82
+ }
83
+
84
+ /**
85
+ * Retain contiguous ends of a text block without partial UTF-16 units.
86
+ * Half the budget goes to the head and half to the tail (DSH retainContent);
87
+ * a single oversized block is split between both ends.
88
+ * @param texts ordered text blocks whose total price exceeds `budget`.
89
+ * @param budget non-negative token budget, after reserving the notice.
90
+ */
91
+ export function retainContent(texts: readonly string[], budget: number): RetainedContent {
92
+ const head: RetainableText[] = [];
93
+ const tail: RetainableText[] = [];
94
+ let first = 0;
95
+ let last = texts.length - 1;
96
+ let headCharacters = 0;
97
+
98
+ let remaining = Math.ceil(budget / 2);
99
+ while (first <= last) {
100
+ const text = texts[first]!;
101
+ const cost = estimateTextTokens(text);
102
+ if (cost <= remaining) {
103
+ head.push({ type: "text", text });
104
+ remaining -= cost;
105
+ first++;
106
+ continue;
107
+ }
108
+ const fitted = fitText(text, remaining, false);
109
+ headCharacters = fitted.length;
110
+ if (fitted.length > 0) head.push({ type: "text", text: fitted });
111
+ break;
112
+ }
113
+
114
+ remaining = Math.floor(budget / 2);
115
+ while (last >= first) {
116
+ // When head and tail meet inside ONE block, the tail starts where the head
117
+ // stopped (DSH's `last === first` arm) so no text is counted twice.
118
+ const original = texts[last]!;
119
+ const text = last === first ? original.slice(headCharacters) : original;
120
+ const cost = estimateTextTokens(text);
121
+ if (cost <= remaining) {
122
+ if (text.length > 0) tail.push({ type: "text", text });
123
+ remaining -= cost;
124
+ last--;
125
+ continue;
126
+ }
127
+ const fitted = fitText(text, remaining, true);
128
+ if (fitted.length > 0) tail.push({ type: "text", text: fitted });
129
+ break;
130
+ }
131
+ tail.reverse();
132
+
133
+ const bytes = (blocks: readonly RetainableText[]): number =>
134
+ blocks.reduce((total, block) => total + Buffer.byteLength(block.text, "utf8"), 0);
135
+ const original = texts.reduce((total, text) => total + Buffer.byteLength(text, "utf8"), 0);
136
+ return {
137
+ head,
138
+ tail,
139
+ omittedBytes: original - bytes(head) - bytes(tail),
140
+ };
141
+ }
142
+
143
+ /** Longest line pi's read returns in one go (DEFAULT_MAX_BYTES, read.js:117). */
144
+ export const PI_READ_LINE_LIMIT = 50 * 1024;
145
+
146
+ /**
147
+ * Bytes pi's bash returns before truncating (truncate.js DEFAULT_MAX_BYTES).
148
+ * Like the line cap, exceeding this makes bash drop the page's HEAD while our
149
+ * offset advances past it. The token budget is NOT a substitute: a user who
150
+ * raises `repair.spillMaxTokens` to 200,000 asks for a 100,000-byte page, which
151
+ * is nearly twice this cap (measured) — so the byte window must be clamped
152
+ * independently of the budget and of the line window.
153
+ */
154
+ export const PI_BASH_BYTE_LIMIT = 50 * 1024;
155
+ /** Bytes a page may print, with headroom under pi's cap for the offset marker
156
+ * and a partial trailing line. */
157
+ export const PAGE_BYTE_LIMIT = 45_000;
158
+
159
+ /**
160
+ * Lines pi's bash returns before truncating (truncate.js DEFAULT_MAX_LINES).
161
+ * CRITICAL: bash truncates with `truncateTail` — it keeps the LAST 2000 lines
162
+ * and DROPS THE HEAD (bash.js:270 "Showing lines X-Y"). A byte-capped page of
163
+ * short lines therefore loses its head while our offset has already advanced
164
+ * past those bytes, so they are gone for good. Measured: a 6,246-byte page of
165
+ * 3-byte lines is 2,083 lines — 83 lines (249 bytes) silently dropped.
166
+ */
167
+ export const PI_BASH_LINE_LIMIT = 2_000;
168
+ /** Lines a recovery page may print, well under pi's cap so the marker and any
169
+ * partial trailing line never push the result over it. */
170
+ export const PAGE_LINE_LIMIT = 1_900;
171
+
172
+ /**
173
+ * Largest byte count a `cat | head -c N` recovery may print WITHOUT producing
174
+ * another over-budget result (which would re-spill and loop the model).
175
+ *
176
+ * The hint must page UNDER the ACTIVE budget, not under pi's 50 KB read limit:
177
+ * 50,000 ASCII chars estimates to 12,504 tokens with block overhead, which
178
+ * exceeds the 12,500 default — so `head -c 50000` re-spills (measured). Half
179
+ * the budget leaves room for the caller's own framing and for CJK/emoji text,
180
+ * where 1 char is still 1 estimate unit but 3-4 bytes on disk.
181
+ */
182
+ export function maxRecoveryBytes(maxTokens: number): number {
183
+ const chars = Math.floor(maxTokens / 2) - BLOCK_OVERHEAD;
184
+ return Math.max(0, chars);
185
+ }
186
+
187
+ /**
188
+ * The byte window a page may print, shrunk so the page cannot exceed
189
+ * `lineLimit` lines even in the worst case of the shortest possible line.
190
+ *
191
+ * A page is capped on BOTH axes because pi's bash caps both: exceeding
192
+ * `PI_BASH_LINE_LIMIT` makes bash drop the page's HEAD (see that constant),
193
+ * which silently loses bytes the offset has already skipped. With `minLine`
194
+ * bytes per line (1 for a file of bare newlines) the safe byte window is
195
+ * `minLine * lineLimit`; the caller estimates `minLine` from the payload.
196
+ * The estimate is deliberately conservative — an under-sized page is a
197
+ * harmless extra round trip, an over-sized one loses data.
198
+ */
199
+ export function maxRecoveryPageBytes(maxTokens: number, minLine = 1): number {
200
+ const byBudget = maxRecoveryBytes(maxTokens);
201
+ const byLines = Math.max(1, minLine) * PAGE_LINE_LIMIT;
202
+ // THREE independent caps: the token budget (no re-spill), the line cap (bash
203
+ // drops the head past 2000 lines), and pi's 50 KiB byte cap (same head loss).
204
+ // The budget alone does NOT imply the byte cap: a raised spillMaxTokens asks
205
+ // for a page larger than pi will ever return.
206
+ return Math.max(1, Math.min(byBudget, byLines, PAGE_BYTE_LIMIT));
207
+ }
208
+
209
+ /**
210
+ * The notice appended to a retained preview.
211
+ *
212
+ * BOTH payload shapes page by bytes, because `read` is never a safe recovery
213
+ * for a spilled result — the spill file exceeds the budget BY DEFINITION, so
214
+ * any read that returns enough of it re-spills and loops the model:
215
+ *
216
+ * - long-line payloads: pi's read REFUSES a single line over 50 KB
217
+ * ("Line 1 is 146.5KB, exceeds 50.0KB limit. Use bash: sed -n '1p' …"), so
218
+ * `read` is a dead end outright (measured in a herdr pane against ceulen's
219
+ * own spill file).
220
+ * - short-line payloads: read succeeds but caps at 50 KB / 2000 lines, which
221
+ * estimates to 12,504 tokens — OVER the 12,500 default — and at a lowered
222
+ * budget (say 2,000) even a 9 KB / 100-line read costs 2,254 tokens and
223
+ * spills again. `read` has no byte-budget parameter, so no line limit can be
224
+ * proven safe; byte offsets can.
225
+ */
226
+ export function formatSpillNotice(
227
+ omittedBytes: number,
228
+ filePath: string,
229
+ longestLine = 0,
230
+ maxTokens = DEFAULT_SPILL_MAX_TOKENS,
231
+ shortestLine = Number.POSITIVE_INFINITY,
232
+ ): string {
233
+ // Dual cap: the BYTE window keeps the page under the token budget, the LINE
234
+ // window keeps it under pi's bash cap — exceeding the latter makes bash drop
235
+ // the page's head while our offset advances past it (data loss).
236
+ const chunk = maxRecoveryPageBytes(maxTokens, shortestLine);
237
+ const why = longestLine > PI_READ_LINE_LIMIT
238
+ ? "the long line is over read's 50KB limit"
239
+ : "read would return more than this result's budget and spill again";
240
+ // UTF-8 SAFETY: a raw `head -c N` splits multibyte characters at the page
241
+ // boundary, and bash decodes each page INDEPENDENTLY — so the character is
242
+ // lost in BOTH pages (measured: a 3-byte `日` straddling byte 996 decoded to
243
+ // U+FFFD at page 1's end AND page 2's start). `iconv -c` drops the trailing
244
+ // partial sequence, and the page reports the ACTUAL next offset (offset +
245
+ // bytes printed) so paging never re-reads or skips a byte. Verified by full
246
+ // round trip at chunk sizes 7 / 996 / 997 on multibyte fixtures: exact.
247
+ // OFFSET is a shell VARIABLE set inside the -c body, not a literal to be
248
+ // pasted: a naive template substitution breaks on the second page, because
249
+ // the value appears twice (the tail -c argument and the next-offset
250
+ // arithmetic). Start at 1 and feed each page's printed offset back in.
251
+ const recovery = `Retrieve it in <=${PAGE_LINE_LIMIT}-line, ~${chunk}-byte UTF-8-safe pages with bash (${why}); `
252
+ + `set OFFSET=1, then for each page feed the printed next OFFSET back in: `
253
+ + `bash -c 'OFFSET=$1; f=$(mktemp); cat ${filePath} | tail -c +$OFFSET | head -c ${chunk} `
254
+ + `| iconv -f UTF-8 -t UTF-8 -c 2>/dev/null | head -n ${PAGE_LINE_LIMIT} > "$f"; cat "$f"; `
255
+ + `printf "[next OFFSET = %d]\\n" $((OFFSET + $(wc -c < "$f"))); rm -f "$f"' _ OFFSET`;
256
+ return `\n\n[... ${omittedBytes} bytes omitted ...]\nFull output saved to: ${filePath}\n${recovery}`;
257
+ }
258
+
259
+ /** Longest line length in a text (0 for an empty string). */
260
+ export function longestLineLength(text: string): number {
261
+ let longest = 0;
262
+ let start = 0;
263
+ for (let i = 0; i <= text.length; i++) {
264
+ if (i === text.length || text.charCodeAt(i) === 10) {
265
+ if (i - start > longest) longest = i - start;
266
+ start = i + 1;
267
+ }
268
+ }
269
+ return longest;
270
+ }
271
+
272
+ /**
273
+ * Shortest NON-EMPTY line length (1 when there are none) — the worst case for
274
+ * the line cap, since short lines mean many lines per byte window.
275
+ */
276
+ export function shortestLineLength(text: string): number {
277
+ let shortest = Number.POSITIVE_INFINITY;
278
+ let start = 0;
279
+ for (let i = 0; i <= text.length; i++) {
280
+ if (i === text.length || text.charCodeAt(i) === 10) {
281
+ const length = i - start;
282
+ if (length > 0 && length < shortest) shortest = length;
283
+ start = i + 1;
284
+ }
285
+ }
286
+ return shortest === Number.POSITIVE_INFINITY ? 1 : shortest;
287
+ }
@@ -0,0 +1,85 @@
1
+ // Time context: timestamp/duration formatting and the refresh window.
2
+ //
3
+ // pi injects no model-visible date/time anywhere (dist/core/system-prompt.js
4
+ // renders with `timestamp: 0`), which is the whole reason this exists. DSH
5
+ // parity: ISO stamp + numeric offset + IANA zone, compact elapsed, 10-minute
6
+ // default refresh.
7
+ import assert from "node:assert/strict";
8
+ import { describe, it } from "node:test";
9
+ import {
10
+ DEFAULT_CLOCK_REFRESH_MS,
11
+ formatDuration,
12
+ formatTimestamp,
13
+ renderClock,
14
+ shouldInject,
15
+ } from "../lib/clock.js";
16
+
17
+ describe("formatDuration", () => {
18
+ it("emits compact whole-second units", () => {
19
+ assert.equal(formatDuration(0), "0s");
20
+ assert.equal(formatDuration(7_000), "7s");
21
+ assert.equal(formatDuration(90_000), "1m 30s");
22
+ assert.equal(formatDuration(3_661_000), "1h 1m 1s");
23
+ assert.equal(formatDuration(90_061_000), "1d 1h 1m 1s");
24
+ });
25
+
26
+ it("clamps a backward clock reading instead of emitting a negative span", () => {
27
+ assert.equal(formatDuration(-5_000), "0s");
28
+ });
29
+ });
30
+
31
+ describe("formatTimestamp", () => {
32
+ it("renders an ISO stamp with a numeric offset and the zone name", () => {
33
+ const stamp = formatTimestamp(Date.UTC(2026, 10, 23, 3, 30, 0), "Asia/Bangkok");
34
+ assert.match(stamp, /^2026-11-23T10:30:00\+07:00 \(Asia\/Bangkok\)$/);
35
+ });
36
+
37
+ it("renders UTC with a +00:00 offset", () => {
38
+ const stamp = formatTimestamp(Date.UTC(2026, 10, 23, 3, 30, 0), "UTC");
39
+ assert.match(stamp, /^2026-11-23T03:30:00\+00:00 \(UTC\)$/);
40
+ });
41
+
42
+ it("falls back to the process zone for an unknown zone rather than dropping the clock", () => {
43
+ const stamp = formatTimestamp(Date.UTC(2026, 10, 23, 3, 30, 0), "Not/AZone");
44
+ assert.match(stamp, /^2026-11-23T\d{2}:30:00[+-]\d{2}:\d{2} \(/);
45
+ });
46
+ });
47
+
48
+ describe("renderClock", () => {
49
+ it("emits the two load-bearing lines", () => {
50
+ const body = renderClock(Date.UTC(2026, 10, 23, 3, 30, 0), 8_130_000, "UTC");
51
+ const lines = body.split("\n");
52
+ assert.match(lines[0]!, /^Time: 2026-11-23T03:30:00\+00:00 \(UTC\)$/);
53
+ assert.equal(lines[1], "Elapsed since last activity: 2h 15m 30s");
54
+ });
55
+
56
+ it("reports an unavailable elapsed span on the first injection", () => {
57
+ assert.match(renderClock(Date.now(), undefined, "UTC"), /Elapsed since last activity: unavailable/);
58
+ });
59
+ });
60
+
61
+ describe("refresh window", () => {
62
+ const now = 1_000_000_000;
63
+
64
+ it("injects on the first call", () => {
65
+ assert.equal(shouldInject(undefined, now, DEFAULT_CLOCK_REFRESH_MS), true);
66
+ });
67
+
68
+ it("suppresses inside the window and allows at the boundary", () => {
69
+ const state = { lastInjection: now - 60_000 };
70
+ assert.equal(shouldInject(state, now, DEFAULT_CLOCK_REFRESH_MS), false);
71
+ assert.equal(shouldInject({ lastInjection: now - DEFAULT_CLOCK_REFRESH_MS }, now, DEFAULT_CLOCK_REFRESH_MS), true);
72
+ });
73
+
74
+ it("treats a non-positive interval as every-step", () => {
75
+ assert.equal(shouldInject({ lastInjection: now }, now, 0), true);
76
+ });
77
+
78
+ it("does not park forever when the wall clock moves backwards", () => {
79
+ assert.equal(shouldInject({ lastInjection: now + 60_000 }, now, DEFAULT_CLOCK_REFRESH_MS), true);
80
+ });
81
+
82
+ it("defaults to 10 minutes (DSH refreshIntervalMs)", () => {
83
+ assert.equal(DEFAULT_CLOCK_REFRESH_MS, 600_000);
84
+ });
85
+ });