diff --git a/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/README.md b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fffda9b628a26748075fc707e979c229ee000868 --- /dev/null +++ b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/README.md @@ -0,0 +1,162 @@ +# Facet sandbox — isolated-vm + +**Unmodified pi facet code running in a V8 isolate with no ambient authority.** +Full JIT, so ~1.8× native rather than the 8–17× a WASM interpreter costs. + +```bash +npm install +npm run demo # a facet: contributions, components, commands, callbacks +npm run audit # escape audit — the interesting one +npm run bench # crossing cost, isolate cost, 300 components +npm test # 412 property assertions +``` + +Node 22+ (`--experimental-strip-types`). See `../facet-sandbox-poc` for the +QuickJS-WASM equivalent. + +## The safety claim, and why it is structural + +isolated-vm **can** be used unsafely, and that is what `facets.md` §14.2 objected +to. The footgun is handing the guest a live handle to a host object — via +`derefInto()`, or by returning a `Reference` from a host call — after which the +guest walks that object's prototype chain into the host realm. + +This membrane makes that impossible **by construction, not by care**: + +1. `encode()` is the only way a host value reaches the guest, and it is + `JSON.stringify` with a replacer. **Its output is a string.** A string cannot + carry a reference. +2. Host callables never cross. They become an integer id into `hostTable`, which + lives entirely host-side. The guest receives a **number**. +3. Exactly **one** `Reference` is ever given to the guest — `__invokeRef`, the + single call-in point. +4. `derefInto()` is used exactly once, on the guest's **own** global. No host + object is ever its argument. + +The guest's entire view of the host is `{ number, string }`. There is no object +graph, so there is nothing to walk. + +### Audit results (`npm run audit`) + +``` +Ambient authority: + require / process / fetch ["undefined","undefined","undefined"] + global names visible 64 globals + +Classic escape ladders: + Function('return process')() undefined + constructor walk on host data undefined + +The isolated-vm Reference footgun: + __invokeRef.deref() blocked: TypeError ("Cannot dereference + this from current isolate") + __invokeRef.copySync() blocked: TypeError + __invokeRef.getSync('constructor') blocked: TypeError + derefInto() is callable? inert (object) + invoke derefInto() result blocked: TypeError + host globals via derefInto() no host globals + +Resource bounds: + spinning guest interrupted after 205ms + isolate usable afterwards true +``` + +One probe gave a **false positive** in a first draft: testing `f.deref === undefined` +to prove a returned host function is a Proxy rather than a Reference. The +membrane's proxy returns a proxy for *every* property, so `f.deref` is truthy. +That is not a leak — calling it routes to `hostFn["deref"]`, which does not exist +and throws host-side. The audit now calls it instead of checking for absence. + +## Performance + +| | isolated-vm | QuickJS | native | +| --- | --- | --- | --- | +| 300 markdown components, small | **70 ms** | 494 ms | ~40 ms | +| 300 markdown components, typical | **108 ms** | 1118 ms | 64 ms | +| 300 markdown components, large | **419 ms** | 4260 ms | ~150 ms | +| 146 KB bundle load | **35 ms** | 104 ms | — | +| membrane crossing | **4.5 µs** | 7–17 µs | — | +| per compartment | 1080 KB, 5.5 ms | **77 KB, 0.8 ms** | — | + +**~1.8× native at typical size.** QuickJS is 8–17× and gets worse with input size. + +Isolates cost **14× more memory than a QuickJS runtime** (1080 KB vs 77 KB) and +are slower to create. For a handful of facets that is irrelevant; for hundreds it +would not be. + +`Intl.Segmenter` **exists** here, which is the single hard blocker for reusing +`packages/tui` components under QuickJS. That alone may decide it. + +## Limitations + +**Budgets do not nest.** A timeout bounds one `evalSync`. A guest function +re-entered *by the host* — a contributed callback, a component method — gets +`callGuestRef`'s own budget, not the outer one. Asserted explicitly in +`property-test.ts`; a runaway callback took 5005 ms under an outer budget of 50 ms. +Bounding total facet time needs separate accounting. + +**Async is a settle-callback, not a native promise.** `applySync` is synchronous, +so a host Promise cannot cross. The host returns a token, the guest builds a real +Promise against it, and the host settles it by calling back in. Verified: two +sequential guest `await`s while the host event loop ticked 22 times. + +**Native addon, and the ABI matrix is real.** `isolated-vm` ships prebuilds and +only falls back to `node-gyp rebuild` when none matches — which is why install +takes a second, not an hour. It is **not** building V8; V8 is already in the Node +binary. But coverage is narrow: + +| version | engines | prebuilds | +| --- | --- | --- | +| **6.2.0** | `>=22.0.0` | linux-x64/arm64, darwin-arm64, win32-x64 — abi127, abi137 | +| 7.0.1 | `>=24.0.0` | — | +| 7.0.0 | `>=26.0.0` | — | + +darwin-**x64** is absent everywhere. Installing `isolated-vm@7` on Node 22 falls +through to a source build and **fails without Python and a C++ toolchain** — +verified here. Note also that 6.2.0 is `latest` on npm despite 7.0.1 existing, +because it published one day later. + +The project is **not abandonware** — 6.0.1 (Jul 2025) through 7.0.1 (Aug 2026), +actively released. §14.2's "maintenance mode" claim is out of date and should be +corrected. The real risk is different: adopting it couples your minimum Node +version to theirs, and they dropped Node 20 in 6.x and Node 22 in 7.x within a +year. Shipping SEA builds moves that from every user's install to your CI. + +**Memory: references release, but lazily.** The `WeakRef` + `FinalizationRegistry` +interning table ports unchanged from the QuickJS membrane and works — 20 000 +crossings went to **0 live refs**. But finalization is not prompt: 5 000 refs were +still live 200 ms after a forced GC. Under sustained churn refs accumulate faster +than the collector reclaims them, and a 32 MB isolate did hit its limit. + +The consequence is an API rule, not a membrane fix: **do not create references in +a hot path.** `slots.claim(factory)` at construct is one reference forever; a +component method returning a fresh closure every frame is one per frame. + +**Hitting `memoryLimit` kills the facet cleanly.** It throws a catchable +`"Isolate was disposed during execution due to memory limit"` and the host +survives — but the isolate is dead and unrecoverable, so teardown must tolerate +an already-disposed isolate. `dispose()` on it throws `"Isolate is already +disposed"`; the membrane guards this. + +> **Do not call `isolate.getHeapStatisticsSync()` on a stressed isolate.** It +> **aborted the whole process** during testing — a hard crash, not an exception. +> A `heapMB()` helper was removed from the membrane rather than shipped. + +**Still one process, one engine.** A separate isolate is a far stronger boundary +than SES, but Figma's argument for QuickJS was that a *different VM* cannot +confuse objects because the representations differ. Here the guarantee is V8's +isolate boundary plus the membrane's discipline — strong, and structurally +enforced above, but not the same category of claim. + +## Files + +- `src/membrane.ts` — the membrane. The safety argument is in the header comment. +- `src/facet-example.js` — unmodified facet code: `ctx.use()`, `slots.claim()` + with a closure, a class instance returned to the host, a subscribe callback. +- `src/demo-facet.ts` — loads it and exercises four boundary crossings. +- `src/escape-audit.ts` — the audit above. +- `src/property-test.ts` — 412 assertions: random `JsonValue` round-trips both + directions, identity across crossings, callables, error propagation, reference + release under GC, prototype pollution both ways, budgets, async, disposal. +- `src/bench.ts` — the numbers above. +- `src/markdown-bundle.js` — the real pi `Markdown` component, esbuild-bundled. diff --git a/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/package.json b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fb597ecc6bfcab660001a7b67fcbdc01534df6bf --- /dev/null +++ b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/package.json @@ -0,0 +1,13 @@ +{ + "name": "facet-sandbox-ivm", + "private": true, + "type": "module", + "description": "Running pi facets in an isolated-vm isolate: full JIT, no ambient authority.", + "scripts": { + "demo": "node --experimental-strip-types src/demo-facet.ts", + "audit": "node --experimental-strip-types src/escape-audit.ts", + "bench": "node --experimental-strip-types src/bench.ts", + "test": "node --experimental-strip-types --expose-gc src/property-test.ts" + }, + "dependencies": { "isolated-vm": "6.2.0" } +} diff --git a/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/bench.ts b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/bench.ts new file mode 100644 index 0000000000000000000000000000000000000000..f917c767e769e247ba4e78fae9a851ac66adb227 --- /dev/null +++ b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/bench.ts @@ -0,0 +1,48 @@ +/** + * Cost of the isolate, the membrane, and a real component at transcript scale. + * Compare against `../facet-sandbox-poc` (QuickJS) and native. + */ +import ivm from "isolated-vm"; +import { readFileSync } from "node:fs"; +import { createCompartment } from "./membrane.ts"; + +// ── membrane crossing ───────────────────────────────────────────────────── +{ + const c = await createCompartment(); + await c.endow("__h", { echo: (v: unknown) => v }); + c.load(`globalThis.spin = function (n) { for (var i = 0; i < n; i++) __h.echo("x"); };`); + c.load(`spin(2000);`); + const N = 20000, t = Date.now(); + c.load(`spin(${N});`, 60000); + console.log(`membrane crossing: ${((Date.now() - t) * 1000 / N).toFixed(1)} µs`); + c.dispose(); +} + +// ── isolate creation ────────────────────────────────────────────────────── +{ + const before = process.memoryUsage().rss, t = Date.now(); + const held = Array.from({ length: 50 }, () => { + const iso = new ivm.Isolate({ memoryLimit: 32 }); + const ctx = iso.createContextSync(); + ctx.evalSync(`var c = { render: function () { return ["x"]; } };`); + return iso; + }); + console.log(`50 isolates: ${(((process.memoryUsage().rss - before) / 50) / 1024).toFixed(0)} KB each, ${Date.now() - t} ms total`); + for (const i of held) i.dispose(); +} + +// ── real Markdown at transcript scale ───────────────────────────────────── +{ + const iso = new ivm.Isolate({ memoryLimit: 512 }); + const ctx = iso.createContextSync(); + ctx.global.setSync("global", ctx.global.derefInto()); + const t = Date.now(); + ctx.evalSync(readFileSync(new URL("./markdown-bundle.js", import.meta.url), "utf8"), { timeout: 60000 }); + console.log(`146 KB bundle load: ${Date.now() - t} ms`); + for (const [label, pts] of [["small", 2], ["typical", 8], ["large", 35]] as [string, number][]) { + ctx.evalSync(`__bench(${pts}, 20, 50)`, { timeout: 120000 }); // warm the JIT + const ms = ctx.evalSync(`__bench(${pts}, 300, 3)`, { timeout: 300000 }); + console.log(`300 markdown components, ${label.padEnd(8)} ${ms.toFixed(0)} ms per full repaint`); + } + iso.dispose(); +} diff --git a/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/demo-facet.ts b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/demo-facet.ts new file mode 100644 index 0000000000000000000000000000000000000000..eda12e7fadc9622bb92b756f098a46eecbe493e6 --- /dev/null +++ b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/demo-facet.ts @@ -0,0 +1,22 @@ +import { readFileSync } from "node:fs"; +import { createCompartment } from "./membrane.ts"; +const mounted = new Map(), commands = new Map(), notifications = [], subs = []; +const Tui = { + slots: { claim: (s, f) => mounted.set(s, f) }, + commands: { add: (n, h) => commands.set(n, h) }, + notify: (m) => notifications.push(m), +}; +const Transcript = { tail: { subscribe: (f) => subs.push(f) } }; +const c = await createCompartment(); +await c.endow("__host", { use: (t) => (t === "Tui" ? Tui : Transcript) }); +c.load(readFileSync(new URL("./facet-example.js", import.meta.url), "utf8")); +c.load(`globalThis.__r = __facet.construct({ use: function (t) { return __host.use(t); } });`); +console.log("contributions:", { slots: [...mounted.keys()], commands: [...commands.keys()], subs: subs.length }); +const comp = mounted.get("footer")({ label: "presses" }); +console.log(comp.render(30).join("\n")); +comp.handleInput("abc"); +console.log(comp.render(30).join("\n")); +console.log("command ->", commands.get("footer.reset")()); +subs[0]({ entries: [1, 2, 3] }); +console.log("notifications:", notifications); +c.dispose(); diff --git a/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/escape-audit.ts b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/escape-audit.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f3692435894b36c54d3698bd677da42defb664c --- /dev/null +++ b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/escape-audit.ts @@ -0,0 +1,63 @@ +/** + * Escape audit. + * + * The claim the membrane makes is that the guest's entire view of the host is + * `{ number, string }` — no object graph, so nothing to walk. This tries to + * break that, including the specific `Reference` footgun that makes isolated-vm + * dangerous when used naively. + */ +import { createCompartment } from "./membrane.ts"; + +const c = await createCompartment(); +const seen: string[] = []; +await c.endow("__h", { + sink: (v: string) => seen.push(v), + give: () => ({ nested: { a: 1 } }), + giveFn: () => () => "host function result", +}); + +const probe = (name: string, src: string) => { + c.load(`globalThis.__p = String(${src});`); + c.load(`__h.sink(__p);`); + const got = seen.pop(); + const bad = got !== undefined && /GOT (?!undefined)|INVOKED|CALLABLE|^object$/.test(got) && !/blocked/.test(got); + console.log(` ${bad ? "!!" : "ok"} ${name.padEnd(34)} ${got}`); + return !bad; +}; + +console.log("Ambient authority:"); +let ok = true; +ok = probe("require / process / fetch", `JSON.stringify([typeof require, typeof process, typeof fetch])`) && ok; +ok = probe("global names visible", `Object.getOwnPropertyNames(globalThis).length + " globals"`) && ok; + +console.log("\nClassic escape ladders:"); +ok = probe("Function('return process')()", `(function(){ try { return String((function(){}).constructor("return typeof process")()); } catch(e){ return "blocked: "+e.name; } })()`) && ok; +ok = probe("constructor walk on host data", `(function(){ try { var o = __h.give(); return String(o.constructor.constructor("return typeof process")()); } catch(e){ return "blocked: "+e.name; } })()`) && ok; + +console.log("\nThe isolated-vm Reference footgun:"); +ok = probe("__invokeRef.deref()", `(function(){ try { return "GOT " + typeof __invokeRef.deref(); } catch(e){ return "blocked: "+e.name; } })()`) && ok; +ok = probe("__invokeRef.copySync()", `(function(){ try { return "GOT " + typeof __invokeRef.copySync(); } catch(e){ return "blocked: "+e.name; } })()`) && ok; +ok = probe("__invokeRef.getSync('constructor')", `(function(){ try { return "GOT " + typeof __invokeRef.getSync("constructor"); } catch(e){ return "blocked: "+e.name; } })()`) && ok; +ok = probe("derefInto() is callable?", `(function(){ var d = __invokeRef.derefInto(); return typeof d === "function" ? "CALLABLE" : "inert (" + typeof d + ")"; })()`) && ok; +ok = probe("invoke derefInto() result", `(function(){ try { __invokeRef.derefInto()(); return "INVOKED"; } catch(e){ return "blocked: "+e.name; } })()`) && ok; +ok = probe("host globals via derefInto()", `(function(){ var d = __invokeRef.derefInto(); return String(d.process || d.global || "no host globals"); })()`) && ok; + +console.log("\nWhat a host FUNCTION looks like to the guest:"); +ok = probe("typeof a returned host fn", `(function(){ var f = __h.giveFn(); return typeof f; })()`) && ok; +// NOTE: `f.deref` is NOT undefined — the membrane's proxy returns a proxy for +// every property. That is not a leak: calling it routes to hostFn["deref"], +// which does not exist, and throws host-side. Testing for the property's +// absence gave a false positive in a first draft of this audit. +ok = probe("calling f.deref() reaches nothing", `(function(){ try { var f = __h.giveFn(); f.deref(); return "INVOKED"; } catch(e){ return "blocked: "+e.name; } })()`) && ok; +ok = probe("calling the host fn works", `(function(){ var f = __h.giveFn(); return String(f()); })()`) && ok; + +console.log("\nResource bounds:"); +const t0 = Date.now(); +let interrupted = false; +try { c.load(`while(true){}`, 200); } catch { interrupted = true; } +console.log(` ${interrupted ? "ok" : "!!"} spinning guest interrupted after ${Date.now() - t0}ms`); +console.log(` ok isolate usable afterwards ${c.load(`1+1`) === 2}`); + +c.dispose(); +console.log(`\n${ok && interrupted ? "AUDIT PASSED" : "AUDIT FAILED"}`); +process.exit(ok && interrupted ? 0 : 1); diff --git a/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/facet-example.js b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/facet-example.js new file mode 100644 index 0000000000000000000000000000000000000000..0bdf0a9b45e7f0c5d45faade52bdfccb3647c209 --- /dev/null +++ b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/facet-example.js @@ -0,0 +1,42 @@ +// ── REAL facet code. Nothing here knows it is sandboxed. ──────────────────── +// No imports rewritten, no string marshalling, no __dispatch. It uses the +// host API exactly as facets.md §11.1 describes it. + +class FooterComponent { + constructor(props) { this.label = props.label; this.count = 0; } + render(width) { + const text = ` ${this.label}: ${this.count} `; + const pad = Math.max(0, width - text.length - 2); + const bar = "\u2500".repeat(Math.max(0, width - 2)); + return [`\u250c${bar}\u2510`, `\u2502${text}${" ".repeat(pad)}\u2502`, `\u2514${bar}\u2518`]; + } + handleInput(data) { this.count += data.length; } +} + +const facet = { + id: "@demo/footer:tui", + uses: ["Tui", "Transcript"], + + construct(ctx) { + const tui = ctx.use("Tui"); + const transcript = ctx.use("Transcript"); + + // A factory crossing guest → host, by reference. + tui.slots.claim("footer", (props) => new FooterComponent(props)); + + // A command handler, likewise. + tui.commands.add("footer.reset", () => { + tui.notify("footer reset"); + return "ok"; + }); + + // A subscription: host calls back into the guest. + transcript.tail.subscribe((tail) => { + tui.notify(`transcript now has ${tail.entries.length} entries`); + }); + + return []; + }, +}; + +globalThis.__facet = facet; diff --git a/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/iso-vs-ctx.ts b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/iso-vs-ctx.ts new file mode 100644 index 0000000000000000000000000000000000000000..48cf8f27bc6b92a7792c63ec0696cacd8c1dbbfd --- /dev/null +++ b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/iso-vs-ctx.ts @@ -0,0 +1,34 @@ +import ivm from "isolated-vm"; +const rss = () => process.memoryUsage().rss / 1024 / 1024; + +// 1. Are two CONTEXTS in one isolate isolated from each other? +{ + const iso = new ivm.Isolate({ memoryLimit: 64 }); + const a = iso.createContextSync(), b = iso.createContextSync(); + a.evalSync(`globalThis.secret = "from-A"`); + console.log("context B sees A's global:", b.evalSync(`typeof globalThis.secret`)); + // Can a spin in A be timed out without harming B? + try { a.evalSync(`while(true){}`, { timeout: 100 }); } catch { /* expected */ } + console.log("B usable after A was interrupted:", b.evalSync(`1+1`) === 2); + // Does A's memory bomb kill B? + try { a.evalSync(`var x=[]; for(;;) x.push(new Array(50000).fill(1));`, { timeout: 15000 }); } + catch (e: any) { console.log("A bomb:", e.message.slice(0, 45)); } + try { console.log("B after A's bomb:", b.evalSync(`1+1`)); } + catch (e: any) { console.log("B after A's bomb: DEAD -", e.message.slice(0, 40)); } + try { iso.dispose(); } catch {} +} + +// 2. Cost per facet, both ways. +for (const mode of ["one isolate, N contexts", "N isolates"]) { + const before = rss(), t = Date.now(); + const held: any[] = []; + const shared = mode.startsWith("one") ? new ivm.Isolate({ memoryLimit: 512 }) : null; + for (let i = 0; i < 50; i++) { + const iso = shared ?? new ivm.Isolate({ memoryLimit: 32 }); + const ctx = iso.createContextSync(); + ctx.evalSync(`var c = { render: function () { return ["x"]; } };`); + held.push(iso); + } + console.log(`50 facets, ${mode.padEnd(24)}: ${(((rss() - before) / 50) * 1024).toFixed(0)} KB each, ${Date.now() - t} ms`); + if (shared) { try { shared.dispose(); } catch {} } else for (const i of held) { try { i.dispose(); } catch {} } +} diff --git a/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/leak.ts b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/leak.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6c5b42f7f9670f21d79c86e5abe0fe8943a02cc --- /dev/null +++ b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/leak.ts @@ -0,0 +1,27 @@ +import { createCompartment } from "./membrane.ts"; +const c = await createCompartment(); +let seen = 0; +await c.endow("__l", { drop: (_fn: unknown) => { seen++; } }); +c.load(`globalThis.churn = function (n) { for (var i = 0; i < n; i++) __l.drop(function () { return i; }); };`); + +const rss = () => process.memoryUsage().rss / 1024 / 1024; +const before = rss(); +c.load(`churn(20000);`, 60000); +const peak = c.debugRefCount(); +const afterChurn = rss(); + +globalThis.gc?.(); await new Promise((r) => setTimeout(r, 100)); +globalThis.gc?.(); await new Promise((r) => setTimeout(r, 100)); +const settled = c.debugRefCount(); + +console.log(`20000 crossings: host called ${seen}x`); +console.log(` guest refs: ${peak.guestRefs} -> ${settled.guestRefs}`); +console.log(` host table: ${peak.hostTable} -> ${settled.hostTable}`); +console.log(` rss: ${before.toFixed(0)} -> ${afterChurn.toFixed(0)} -> ${rss().toFixed(0)} MB`); + +// Cost of the release path: one evalSync crossing per finalized ref. +const t = Date.now(); +c.load(`churn(5000);`, 60000); +globalThis.gc?.(); await new Promise((r) => setTimeout(r, 200)); +console.log(` 5000 more + gc: ${Date.now() - t} ms, refs now ${c.debugRefCount().guestRefs}`); +c.dispose(); diff --git a/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/markdown-bundle.js b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/markdown-bundle.js new file mode 100644 index 0000000000000000000000000000000000000000..b43c46c82ed62f263803e3389b06352633545252 --- /dev/null +++ b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/markdown-bundle.js @@ -0,0 +1,3888 @@ +"use strict"; +var __m = (() => { + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; + var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + + // packages/tui/bundle-bench.ts + var bundle_bench_exports = {}; + __export(bundle_bench_exports, { + bench: () => bench + }); + + // node_modules/marked/lib/marked.esm.js + function M() { + return { async: false, breaks: false, extensions: null, gfm: true, hooks: null, pedantic: false, renderer: null, silent: false, tokenizer: null, walkTokens: null }; + } + var T = M(); + function N(l3) { + T = l3; + } + var _ = { exec: () => null }; + function E(l3) { + let e = []; + return (t) => { + let n = Math.max(0, Math.min(3, t - 1)), s = e[n]; + return s || (s = l3(n), e[n] = s), s; + }; + } + function d(l3, e = "") { + let t = typeof l3 == "string" ? l3 : l3.source, n = { replace: (s, r) => { + let i = typeof r == "string" ? r : r.source; + return i = i.replace(m.caret, "$1"), t = t.replace(s, i), n; + }, getRegex: () => new RegExp(t, e) }; + return n; + } + var Te = ((l3 = "") => { + try { + return !!new RegExp("(?<=1)(?/, blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, listIsTask: /^\[[ xX]\] +\S/, listReplaceTask: /^\[[ xX]\] +/, listTaskCheckbox: /\[[ xX]\]/, anyLine: /\n.*\n/, hrefBrackets: /^<(.*)>$/, tableDelimiter: /[:|]/, tableAlignChars: /^\||\| *$/g, tableRowBlankLine: /\n[ \t]*$/, tableAlignRight: /^ *-+: *$/, tableAlignCenter: /^ *:-+: *$/, tableAlignLeft: /^ *:-+ *$/, startATag: /^/i, startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, startAngleBracket: /^$/, pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, unicodeAlphaNumeric: /[\p{L}\p{N}]/u, escapeTest: /[&<>"']/, escapeReplace: /[&<>"']/g, escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, caret: /(^|[^\[])\^/g, percentDecode: /%25/g, findPipe: /\|/g, splitPipe: / \|/, slashPipe: /\\\|/g, carriageReturn: /\r\n|\r/g, spaceLine: /^ +$/gm, notSpaceStart: /^\S*/, endingNewline: /\n$/, listItemRegex: (l3) => new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`), nextBulletRegex: E((l3) => new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)), hrRegex: E((l3) => new RegExp(`^ {0,${l3}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)), fencesBeginRegex: E((l3) => new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)), headingBeginRegex: E((l3) => new RegExp(`^ {0,${l3}}#`)), htmlBeginRegex: E((l3) => new RegExp(`^ {0,${l3}}<(?:[a-z].*>|!--)`, "i")), blockquoteBeginRegex: E((l3) => new RegExp(`^ {0,${l3}}>`)) }; + var Oe = /^(?:[ \t]*(?:\n|$))+/; + var we = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/; + var ye = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; + var B = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; + var Pe = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; + var j = / {0,3}(?:[*+-]|\d{1,9}[.)])/; + var oe = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/; + var ae = d(oe).replace(/bull/g, j).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex(); + var Se = d(oe).replace(/bull/g, j).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(); + var F = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; + var $e = /^[^\n]+/; + var U = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/; + var Le = d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", U).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(); + var _e = d(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g, j).getRegex(); + var H = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul"; + var K = /|$))/; + var ze = d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))", "i").replace("comment", K).replace("tag", H).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(); + var le = d(F).replace("hr", B).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", H).getRegex(); + var Me = d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", le).getRegex(); + var W = { blockquote: Me, code: we, def: Le, fences: ye, heading: Pe, hr: B, html: ze, lheading: ae, list: _e, newline: Oe, paragraph: le, table: _, text: $e }; + var se = d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", B).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3} )[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", H).getRegex(); + var Ee = { ...W, lheading: Se, table: se, paragraph: d(F).replace("hr", B).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", se).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", H).getRegex() }; + var Ie = { ...W, html: d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", K).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^(#{1,6})(.*)(?:\n+|$)/, fences: _, lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, paragraph: d(F).replace("hr", B).replace("heading", ` *#{1,6} *[^ +]`).replace("lheading", ae).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex() }; + var Ae = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; + var Ce = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; + var ue = /^( {2,}|\\)\n(?!\s*$)/; + var Be = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-", Te ? "(?`+)[^`]+\k(?!`)/).replace("html", /<(?! )[^<>]*?>/).getRegex(); + var ce = /^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/; + var Ze = d(ce, "u").replace(/punct/g, I).getRegex(); + var Ge = d(ce, "u").replace(/punct/g, pe).getRegex(); + var he = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)"; + var Ne = d(he, "gu").replace(/notPunctSpace/g, X).replace(/punctSpace/g, Z).replace(/punct/g, I).getRegex(); + var Qe = d(he, "gu").replace(/notPunctSpace/g, ve).replace(/punctSpace/g, qe).replace(/punct/g, pe).getRegex(); + var je = d("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, X).replace(/punctSpace/g, Z).replace(/punct/g, I).getRegex(); + var Fe = d(/^~~?(?:((?!~)punct)|[^\s~])/, "u").replace(/punct/g, I).getRegex(); + var Ue = "^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)"; + var Ke = d(Ue, "gu").replace(/notPunctSpace/g, X).replace(/punctSpace/g, Z).replace(/punct/g, I).getRegex(); + var We = d(/\\(punct)/, "gu").replace(/punct/g, I).getRegex(); + var Xe = d(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(); + var Je = d(K).replace("(?:-->|$)", "-->").getRegex(); + var Ve = d("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment", Je).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(); + var v = /(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/; + var Ye = d(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label", v).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(); + var ke = d(/^!?\[(label)\]\[(ref)\]/).replace("label", v).replace("ref", U).getRegex(); + var de = d(/^!?\[(ref)\](?:\[\])?/).replace("ref", U).getRegex(); + var et = d("reflink|nolink(?!\\()", "g").replace("reflink", ke).replace("nolink", de).getRegex(); + var ie = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/; + var J = { _backpedal: _, anyPunctuation: We, autolink: Xe, blockSkip: He, br: ue, code: Ce, del: _, delLDelim: _, delRDelim: _, emStrongLDelim: Ze, emStrongRDelimAst: Ne, emStrongRDelimUnd: je, escape: Ae, link: Ye, nolink: de, punctuation: De, reflink: ke, reflinkSearch: et, tag: Ve, text: Be, url: _ }; + var tt = { ...J, link: d(/^!?\[(label)\]\((.*?)\)/).replace("label", v).getRegex(), reflink: d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", v).getRegex() }; + var Q = { ...J, emStrongRDelimAst: Qe, emStrongLDelim: Ge, delLDelim: Fe, delRDelim: Ke, url: d(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol", ie).replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(), _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, del: /^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/, text: d(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\": ">", '"': """, "'": "'" }; + var ge = (l3) => rt[l3]; + function O(l3, e) { + if (e) { + if (m.escapeTest.test(l3)) return l3.replace(m.escapeReplace, ge); + } else if (m.escapeTestNoEncode.test(l3)) return l3.replace(m.escapeReplaceNoEncode, ge); + return l3; + } + function V(l3) { + try { + l3 = encodeURI(l3).replace(m.percentDecode, "%"); + } catch { + return null; + } + return l3; + } + function Y(l3, e) { + let t = l3.replace(m.findPipe, (r, i, o) => { + let u = false, a = i; + for (; --a >= 0 && o[a] === "\\"; ) u = !u; + return u ? "|" : " |"; + }), n = t.split(m.splitPipe), s = 0; + if (n[0].trim() || n.shift(), n.length > 0 && !n.at(-1)?.trim() && n.pop(), e) if (n.length > e) n.splice(e); + else for (; n.length < e; ) n.push(""); + for (; s < n.length; s++) n[s] = n[s].trim().replace(m.slashPipe, "|"); + return n; + } + function $(l3, e, t) { + let n = l3.length; + if (n === 0) return ""; + let s = 0; + for (; s < n; ) { + let r = l3.charAt(n - s - 1); + if (r === e && !t) s++; + else if (r !== e && t) s++; + else break; + } + return l3.slice(0, n - s); + } + function ee(l3) { + let e = l3.split(` +`), t = e.length - 1; + for (; t >= 0 && m.blankLine.test(e[t]); ) t--; + return e.length - t <= 2 ? l3 : e.slice(0, t + 1).join(` +`); + } + function fe(l3, e) { + if (l3.indexOf(e[1]) === -1) return -1; + let t = 0; + for (let n = 0; n < l3.length; n++) if (l3[n] === "\\") n++; + else if (l3[n] === e[0]) t++; + else if (l3[n] === e[1] && (t--, t < 0)) return n; + return t > 0 ? -2 : -1; + } + function me(l3, e = 0) { + let t = e, n = ""; + for (let s of l3) if (s === " ") { + let r = 4 - t % 4; + n += " ".repeat(r), t += r; + } else n += s, t++; + return n; + } + function xe(l3, e, t, n, s) { + let r = e.href, i = e.title || null, o = l3[1].replace(s.other.outputLinkReplace, "$1"); + n.state.inLink = true; + let u = { type: l3[0].charAt(0) === "!" ? "image" : "link", raw: t, href: r, title: i, text: o, tokens: n.inlineTokens(o) }; + return n.state.inLink = false, u; + } + function st(l3, e, t) { + let n = l3.match(t.other.indentCodeCompensation); + if (n === null) return e; + let s = n[1]; + return e.split(` +`).map((r) => { + let i = r.match(t.other.beginningSpace); + if (i === null) return r; + let [o] = i; + return o.length >= s.length ? r.slice(s.length) : r; + }).join(` +`); + } + var w = class { + constructor(e) { + __publicField(this, "options"); + __publicField(this, "rules"); + __publicField(this, "lexer"); + this.options = e || T; + } + space(e) { + let t = this.rules.block.newline.exec(e); + if (t && t[0].length > 0) return { type: "space", raw: t[0] }; + } + code(e) { + let t = this.rules.block.code.exec(e); + if (t) { + let n = this.options.pedantic ? t[0] : ee(t[0]), s = n.replace(this.rules.other.codeRemoveIndent, ""); + return { type: "code", raw: n, codeBlockStyle: "indented", text: s }; + } + } + fences(e) { + let t = this.rules.block.fences.exec(e); + if (t) { + let n = t[0], s = st(n, t[3] || "", this.rules); + return { type: "code", raw: n, lang: t[2] ? t[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : t[2], text: s }; + } + } + heading(e) { + let t = this.rules.block.heading.exec(e); + if (t) { + let n = t[2].trim(); + if (this.rules.other.endingHash.test(n)) { + let s = $(n, "#"); + (this.options.pedantic || !s || this.rules.other.endingSpaceChar.test(s)) && (n = s.trim()); + } + return { type: "heading", raw: $(t[0], ` +`), depth: t[1].length, text: n, tokens: this.lexer.inline(n) }; + } + } + hr(e) { + let t = this.rules.block.hr.exec(e); + if (t) return { type: "hr", raw: $(t[0], ` +`) }; + } + blockquote(e) { + let t = this.rules.block.blockquote.exec(e); + if (t) { + let n = $(t[0], ` +`).split(` +`), s = "", r = "", i = []; + for (; n.length > 0; ) { + let o = false, u = [], a; + for (a = 0; a < n.length; a++) if (this.rules.other.blockquoteStart.test(n[a])) u.push(n[a]), o = true; + else if (!o) u.push(n[a]); + else break; + n = n.slice(a); + let c = u.join(` +`), p = c.replace(this.rules.other.blockquoteSetextReplace, ` + $1`).replace(this.rules.other.blockquoteSetextReplace2, ""); + s = s ? `${s} +${c}` : c, r = r ? `${r} +${p}` : p; + let k = this.lexer.state.top; + if (this.lexer.state.top = true, this.lexer.blockTokens(p, i, true), this.lexer.state.top = k, n.length === 0) break; + let h = i.at(-1); + if (h?.type === "code") break; + if (h?.type === "blockquote") { + let R = h, f = R.raw + ` +` + n.join(` +`), S = this.blockquote(f); + i[i.length - 1] = S, s = s.substring(0, s.length - R.raw.length) + S.raw, r = r.substring(0, r.length - R.text.length) + S.text; + break; + } else if (h?.type === "list") { + let R = h, f = R.raw + ` +` + n.join(` +`), S = this.list(f); + i[i.length - 1] = S, s = s.substring(0, s.length - h.raw.length) + S.raw, r = r.substring(0, r.length - R.raw.length) + S.raw, n = f.substring(i.at(-1).raw.length).split(` +`); + continue; + } + } + return { type: "blockquote", raw: s, tokens: i, text: r }; + } + } + list(e) { + let t = this.rules.block.list.exec(e); + if (t) { + let n = t[1].trim(), s = n.length > 1, r = { type: "list", raw: "", ordered: s, start: s ? +n.slice(0, -1) : "", loose: false, items: [] }; + n = s ? `\\d{1,9}\\${n.slice(-1)}` : `\\${n}`, this.options.pedantic && (n = s ? n : "[*+-]"); + let i = this.rules.other.listItemRegex(n), o = false; + for (; e; ) { + let a = false, c = "", p = ""; + if (!(t = i.exec(e)) || this.rules.block.hr.test(e)) break; + c = t[0], e = e.substring(c.length); + let k = me(t[2].split(` +`, 1)[0], t[1].length), h = e.split(` +`, 1)[0], R = !k.trim(), f = 0; + if (this.options.pedantic ? (f = 2, p = k.trimStart()) : R ? f = t[1].length + 1 : (f = k.search(this.rules.other.nonSpaceChar), f = f > 4 ? 1 : f, p = k.slice(f), f += t[1].length), R && this.rules.other.blankLine.test(h) && (c += h + ` +`, e = e.substring(h.length + 1), a = true), !a) { + let S = this.rules.other.nextBulletRegex(f), te = this.rules.other.hrRegex(f), ne = this.rules.other.fencesBeginRegex(f), re = this.rules.other.headingBeginRegex(f), be = this.rules.other.htmlBeginRegex(f), Re = this.rules.other.blockquoteBeginRegex(f); + for (; e; ) { + let G = e.split(` +`, 1)[0], C; + if (h = G, this.options.pedantic ? (h = h.replace(this.rules.other.listReplaceNesting, " "), C = h) : C = h.replace(this.rules.other.tabCharGlobal, " "), ne.test(h) || re.test(h) || be.test(h) || Re.test(h) || S.test(h) || te.test(h)) break; + if (C.search(this.rules.other.nonSpaceChar) >= f || !h.trim()) p += ` +` + C.slice(f); + else { + if (R || k.replace(this.rules.other.tabCharGlobal, " ").search(this.rules.other.nonSpaceChar) >= 4 || ne.test(k) || re.test(k) || te.test(k)) break; + p += ` +` + h; + } + R = !h.trim(), c += G + ` +`, e = e.substring(G.length + 1), k = C.slice(f); + } + } + r.loose || (o ? r.loose = true : this.rules.other.doubleBlankLine.test(c) && (o = true)), r.items.push({ type: "list_item", raw: c, task: !!this.options.gfm && this.rules.other.listIsTask.test(p), loose: false, text: p, tokens: [] }), r.raw += c; + } + let u = r.items.at(-1); + if (u) u.raw = u.raw.trimEnd(), u.text = u.text.trimEnd(); + else return; + r.raw = r.raw.trimEnd(); + for (let a of r.items) { + this.lexer.state.top = false, a.tokens = this.lexer.blockTokens(a.text, []); + let c = a.tokens[0]; + if (a.task && (c?.type === "text" || c?.type === "paragraph")) { + a.text = a.text.replace(this.rules.other.listReplaceTask, ""), c.raw = c.raw.replace(this.rules.other.listReplaceTask, ""), c.text = c.text.replace(this.rules.other.listReplaceTask, ""); + for (let k = this.lexer.inlineQueue.length - 1; k >= 0; k--) if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[k].src)) { + this.lexer.inlineQueue[k].src = this.lexer.inlineQueue[k].src.replace(this.rules.other.listReplaceTask, ""); + break; + } + let p = this.rules.other.listTaskCheckbox.exec(a.raw); + if (p) { + let k = { type: "checkbox", raw: p[0] + " ", checked: p[0] !== "[ ]" }; + a.checked = k.checked, r.loose ? a.tokens[0] && ["paragraph", "text"].includes(a.tokens[0].type) && "tokens" in a.tokens[0] && a.tokens[0].tokens ? (a.tokens[0].raw = k.raw + a.tokens[0].raw, a.tokens[0].text = k.raw + a.tokens[0].text, a.tokens[0].tokens.unshift(k)) : a.tokens.unshift({ type: "paragraph", raw: k.raw, text: k.raw, tokens: [k] }) : a.tokens.unshift(k); + } + } else a.task && (a.task = false); + if (!r.loose) { + let p = a.tokens.filter((h) => h.type === "space"), k = p.length > 0 && p.some((h) => this.rules.other.anyLine.test(h.raw)); + r.loose = k; + } + } + if (r.loose) for (let a of r.items) { + a.loose = true; + for (let c of a.tokens) c.type === "text" && (c.type = "paragraph"); + } + return r; + } + } + html(e) { + let t = this.rules.block.html.exec(e); + if (t) { + let n = ee(t[0]); + return { type: "html", block: true, raw: n, pre: t[1] === "pre" || t[1] === "script" || t[1] === "style", text: n }; + } + } + def(e) { + let t = this.rules.block.def.exec(e); + if (t) { + let n = t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " "), s = t[2] ? t[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "", r = t[3] ? t[3].substring(1, t[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : t[3]; + return { type: "def", tag: n, raw: $(t[0], ` +`), href: s, title: r }; + } + } + table(e) { + let t = this.rules.block.table.exec(e); + if (!t || !this.rules.other.tableDelimiter.test(t[2])) return; + let n = Y(t[1]), s = t[2].replace(this.rules.other.tableAlignChars, "").split("|"), r = t[3]?.trim() ? t[3].replace(this.rules.other.tableRowBlankLine, "").split(` +`) : [], i = { type: "table", raw: $(t[0], ` +`), header: [], align: [], rows: [] }; + if (n.length === s.length) { + for (let o of s) this.rules.other.tableAlignRight.test(o) ? i.align.push("right") : this.rules.other.tableAlignCenter.test(o) ? i.align.push("center") : this.rules.other.tableAlignLeft.test(o) ? i.align.push("left") : i.align.push(null); + for (let o = 0; o < n.length; o++) i.header.push({ text: n[o], tokens: this.lexer.inline(n[o]), header: true, align: i.align[o] }); + for (let o of r) i.rows.push(Y(o, i.header.length).map((u, a) => ({ text: u, tokens: this.lexer.inline(u), header: false, align: i.align[a] }))); + return i; + } + } + lheading(e) { + let t = this.rules.block.lheading.exec(e); + if (t) { + let n = t[1].trim(); + return { type: "heading", raw: $(t[0], ` +`), depth: t[2].charAt(0) === "=" ? 1 : 2, text: n, tokens: this.lexer.inline(n) }; + } + } + paragraph(e) { + let t = this.rules.block.paragraph.exec(e); + if (t) { + let n = t[1].charAt(t[1].length - 1) === ` +` ? t[1].slice(0, -1) : t[1]; + return { type: "paragraph", raw: t[0], text: n, tokens: this.lexer.inline(n) }; + } + } + text(e) { + let t = this.rules.block.text.exec(e); + if (t) return { type: "text", raw: t[0], text: t[0], tokens: this.lexer.inline(t[0]) }; + } + escape(e) { + let t = this.rules.inline.escape.exec(e); + if (t) return { type: "escape", raw: t[0], text: t[1] }; + } + tag(e) { + let t = this.rules.inline.tag.exec(e); + if (t) return !this.lexer.state.inLink && this.rules.other.startATag.test(t[0]) ? this.lexer.state.inLink = true : this.lexer.state.inLink && this.rules.other.endATag.test(t[0]) && (this.lexer.state.inLink = false), !this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(t[0]) ? this.lexer.state.inRawBlock = true : this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(t[0]) && (this.lexer.state.inRawBlock = false), { type: "html", raw: t[0], inLink: this.lexer.state.inLink, inRawBlock: this.lexer.state.inRawBlock, block: false, text: t[0] }; + } + link(e) { + let t = this.rules.inline.link.exec(e); + if (t) { + let n = t[2].trim(); + if (!this.options.pedantic && this.rules.other.startAngleBracket.test(n)) { + if (!this.rules.other.endAngleBracket.test(n)) return; + let i = $(n.slice(0, -1), "\\"); + if ((n.length - i.length) % 2 === 0) return; + } else { + let i = fe(t[2], "()"); + if (i === -2) return; + if (i > -1) { + let u = (t[0].indexOf("!") === 0 ? 5 : 4) + t[1].length + i; + t[2] = t[2].substring(0, i), t[0] = t[0].substring(0, u).trim(), t[3] = ""; + } + } + let s = t[2], r = ""; + if (this.options.pedantic) { + let i = this.rules.other.pedanticHrefTitle.exec(s); + i && (s = i[1], r = i[3]); + } else r = t[3] ? t[3].slice(1, -1) : ""; + return s = s.trim(), this.rules.other.startAngleBracket.test(s) && (this.options.pedantic && !this.rules.other.endAngleBracket.test(n) ? s = s.slice(1) : s = s.slice(1, -1)), xe(t, { href: s && s.replace(this.rules.inline.anyPunctuation, "$1"), title: r && r.replace(this.rules.inline.anyPunctuation, "$1") }, t[0], this.lexer, this.rules); + } + } + reflink(e, t) { + let n; + if ((n = this.rules.inline.reflink.exec(e)) || (n = this.rules.inline.nolink.exec(e))) { + let s = (n[2] || n[1]).replace(this.rules.other.multipleSpaceGlobal, " "), r = t[s.toLowerCase()]; + if (!r) { + let i = n[0].charAt(0); + return { type: "text", raw: i, text: i }; + } + return xe(n, r, n[0], this.lexer, this.rules); + } + } + emStrong(e, t, n = "") { + let s = this.rules.inline.emStrongLDelim.exec(e); + if (!s || !s[1] && !s[2] && !s[3] && !s[4] || s[4] && n.match(this.rules.other.unicodeAlphaNumeric)) return; + if (!(s[1] || s[3] || "") || !n || this.rules.inline.punctuation.exec(n)) { + let i = [...s[0]].length - 1, o, u, a = i, c = 0, p = s[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; + for (p.lastIndex = 0, t = t.slice(-1 * e.length + i); (s = p.exec(t)) !== null; ) { + if (o = s[1] || s[2] || s[3] || s[4] || s[5] || s[6], !o) continue; + if (u = [...o].length, s[3] || s[4]) { + a += u; + continue; + } else if ((s[5] || s[6]) && i % 3 && !((i + u) % 3)) { + c += u; + continue; + } + if (a -= u, a > 0) continue; + u = Math.min(u, u + a + c); + let k = [...s[0]][0].length, h = e.slice(0, i + s.index + k + u); + if (Math.min(i, u) % 2) { + let f = h.slice(1, -1); + return { type: "em", raw: h, text: f, tokens: this.lexer.inlineTokens(f) }; + } + let R = h.slice(2, -2); + return { type: "strong", raw: h, text: R, tokens: this.lexer.inlineTokens(R) }; + } + } + } + codespan(e) { + let t = this.rules.inline.code.exec(e); + if (t) { + let n = t[2].replace(this.rules.other.newLineCharGlobal, " "), s = this.rules.other.nonSpaceChar.test(n), r = this.rules.other.startingSpaceChar.test(n) && this.rules.other.endingSpaceChar.test(n); + return s && r && (n = n.substring(1, n.length - 1)), { type: "codespan", raw: t[0], text: n }; + } + } + br(e) { + let t = this.rules.inline.br.exec(e); + if (t) return { type: "br", raw: t[0] }; + } + del(e, t, n = "") { + let s = this.rules.inline.delLDelim.exec(e); + if (!s) return; + if (!(s[1] || "") || !n || this.rules.inline.punctuation.exec(n)) { + let i = [...s[0]].length - 1, o, u, a = i, c = this.rules.inline.delRDelim; + for (c.lastIndex = 0, t = t.slice(-1 * e.length + i); (s = c.exec(t)) !== null; ) { + if (o = s[1] || s[2] || s[3] || s[4] || s[5] || s[6], !o || (u = [...o].length, u !== i)) continue; + if (s[3] || s[4]) { + a += u; + continue; + } + if (a -= u, a > 0) continue; + u = Math.min(u, u + a); + let p = [...s[0]][0].length, k = e.slice(0, i + s.index + p + u), h = k.slice(i, -i); + return { type: "del", raw: k, text: h, tokens: this.lexer.inlineTokens(h) }; + } + } + } + autolink(e) { + let t = this.rules.inline.autolink.exec(e); + if (t) { + let n, s; + return t[2] === "@" ? (n = t[1], s = "mailto:" + n) : (n = t[1], s = n), { type: "link", raw: t[0], text: n, href: s, tokens: [{ type: "text", raw: n, text: n }] }; + } + } + url(e) { + let t; + if (t = this.rules.inline.url.exec(e)) { + let n, s; + if (t[2] === "@") n = t[0], s = "mailto:" + n; + else { + let r; + do + r = t[0], t[0] = this.rules.inline._backpedal.exec(t[0])?.[0] ?? ""; + while (r !== t[0]); + n = t[0], t[1] === "www." ? s = "http://" + t[0] : s = t[0]; + } + return { type: "link", raw: t[0], text: n, href: s, tokens: [{ type: "text", raw: n, text: n }] }; + } + } + inlineText(e) { + let t = this.rules.inline.text.exec(e); + if (t) { + let n = this.lexer.state.inRawBlock; + return { type: "text", raw: t[0], text: t[0], escaped: n }; + } + } + }; + var x = class l { + constructor(e) { + __publicField(this, "tokens"); + __publicField(this, "options"); + __publicField(this, "state"); + __publicField(this, "inlineQueue"); + __publicField(this, "tokenizer"); + this.tokens = [], this.tokens.links = /* @__PURE__ */ Object.create(null), this.options = e || T, this.options.tokenizer = this.options.tokenizer || new w(), this.tokenizer = this.options.tokenizer, this.tokenizer.options = this.options, this.tokenizer.lexer = this, this.inlineQueue = [], this.state = { inLink: false, inRawBlock: false, top: true }; + let t = { other: m, block: D.normal, inline: A.normal }; + this.options.pedantic ? (t.block = D.pedantic, t.inline = A.pedantic) : this.options.gfm && (t.block = D.gfm, this.options.breaks ? t.inline = A.breaks : t.inline = A.gfm), this.tokenizer.rules = t; + } + static get rules() { + return { block: D, inline: A }; + } + static lex(e, t) { + return new l(t).lex(e); + } + static lexInline(e, t) { + return new l(t).inlineTokens(e); + } + lex(e) { + e = e.replace(m.carriageReturn, ` +`), this.blockTokens(e, this.tokens); + for (let t = 0; t < this.inlineQueue.length; t++) { + let n = this.inlineQueue[t]; + this.inlineTokens(n.src, n.tokens); + } + return this.inlineQueue = [], this.tokens; + } + blockTokens(e, t = [], n = false) { + this.tokenizer.lexer = this, this.options.pedantic && (e = e.replace(m.tabCharGlobal, " ").replace(m.spaceLine, "")); + let s = 1 / 0; + for (; e; ) { + if (e.length < s) s = e.length; + else { + this.infiniteLoopError(e.charCodeAt(0)); + break; + } + let r; + if (this.options.extensions?.block?.some((o) => (r = o.call({ lexer: this }, e, t)) ? (e = e.substring(r.raw.length), t.push(r), true) : false)) continue; + if (r = this.tokenizer.space(e)) { + e = e.substring(r.raw.length); + let o = t.at(-1); + r.raw.length === 1 && o !== void 0 ? o.raw += ` +` : t.push(r); + continue; + } + if (r = this.tokenizer.code(e)) { + e = e.substring(r.raw.length); + let o = t.at(-1); + o?.type === "paragraph" || o?.type === "text" ? (o.raw += (o.raw.endsWith(` +`) ? "" : ` +`) + r.raw, o.text += ` +` + r.text, this.inlineQueue.at(-1).src = o.text) : t.push(r); + continue; + } + if (r = this.tokenizer.fences(e)) { + e = e.substring(r.raw.length), t.push(r); + continue; + } + if (r = this.tokenizer.heading(e)) { + e = e.substring(r.raw.length), t.push(r); + continue; + } + if (r = this.tokenizer.hr(e)) { + e = e.substring(r.raw.length), t.push(r); + continue; + } + if (r = this.tokenizer.blockquote(e)) { + e = e.substring(r.raw.length), t.push(r); + continue; + } + if (r = this.tokenizer.list(e)) { + e = e.substring(r.raw.length), t.push(r); + continue; + } + if (r = this.tokenizer.html(e)) { + e = e.substring(r.raw.length), t.push(r); + continue; + } + if (r = this.tokenizer.def(e)) { + e = e.substring(r.raw.length); + let o = t.at(-1); + o?.type === "paragraph" || o?.type === "text" ? (o.raw += (o.raw.endsWith(` +`) ? "" : ` +`) + r.raw, o.text += ` +` + r.raw, this.inlineQueue.at(-1).src = o.text) : this.tokens.links[r.tag] || (this.tokens.links[r.tag] = { href: r.href, title: r.title }, t.push(r)); + continue; + } + if (r = this.tokenizer.table(e)) { + e = e.substring(r.raw.length), t.push(r); + continue; + } + if (r = this.tokenizer.lheading(e)) { + e = e.substring(r.raw.length), t.push(r); + continue; + } + let i = e; + if (this.options.extensions?.startBlock) { + let o = 1 / 0, u = e.slice(1), a; + this.options.extensions.startBlock.forEach((c) => { + a = c.call({ lexer: this }, u), typeof a == "number" && a >= 0 && (o = Math.min(o, a)); + }), o < 1 / 0 && o >= 0 && (i = e.substring(0, o + 1)); + } + if (this.state.top && (r = this.tokenizer.paragraph(i))) { + let o = t.at(-1); + n && o?.type === "paragraph" ? (o.raw += (o.raw.endsWith(` +`) ? "" : ` +`) + r.raw, o.text += ` +` + r.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = o.text) : t.push(r), n = i.length !== e.length, e = e.substring(r.raw.length); + continue; + } + if (r = this.tokenizer.text(e)) { + e = e.substring(r.raw.length); + let o = t.at(-1); + o?.type === "text" ? (o.raw += (o.raw.endsWith(` +`) ? "" : ` +`) + r.raw, o.text += ` +` + r.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = o.text) : t.push(r); + continue; + } + if (e) { + this.infiniteLoopError(e.charCodeAt(0)); + break; + } + } + return this.state.top = true, t; + } + inline(e, t = []) { + return this.inlineQueue.push({ src: e, tokens: t }), t; + } + inlineTokens(e, t = []) { + this.tokenizer.lexer = this; + let n = e, s = null; + if (this.tokens.links) { + let a = Object.keys(this.tokens.links); + if (a.length > 0) for (; (s = this.tokenizer.rules.inline.reflinkSearch.exec(n)) !== null; ) a.includes(s[0].slice(s[0].lastIndexOf("[") + 1, -1)) && (n = n.slice(0, s.index) + "[" + "a".repeat(s[0].length - 2) + "]" + n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex)); + } + for (; (s = this.tokenizer.rules.inline.anyPunctuation.exec(n)) !== null; ) n = n.slice(0, s.index) + "++" + n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex); + let r; + for (; (s = this.tokenizer.rules.inline.blockSkip.exec(n)) !== null; ) r = s[2] ? s[2].length : 0, n = n.slice(0, s.index + r) + "[" + "a".repeat(s[0].length - r - 2) + "]" + n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); + n = this.options.hooks?.emStrongMask?.call({ lexer: this }, n) ?? n; + let i = false, o = "", u = 1 / 0; + for (; e; ) { + if (e.length < u) u = e.length; + else { + this.infiniteLoopError(e.charCodeAt(0)); + break; + } + i || (o = ""), i = false; + let a; + if (this.options.extensions?.inline?.some((p) => (a = p.call({ lexer: this }, e, t)) ? (e = e.substring(a.raw.length), t.push(a), true) : false)) continue; + if (a = this.tokenizer.escape(e)) { + e = e.substring(a.raw.length), t.push(a); + continue; + } + if (a = this.tokenizer.tag(e)) { + e = e.substring(a.raw.length), t.push(a); + continue; + } + if (a = this.tokenizer.link(e)) { + e = e.substring(a.raw.length), t.push(a); + continue; + } + if (a = this.tokenizer.reflink(e, this.tokens.links)) { + e = e.substring(a.raw.length); + let p = t.at(-1); + a.type === "text" && p?.type === "text" ? (p.raw += a.raw, p.text += a.text) : t.push(a); + continue; + } + if (a = this.tokenizer.emStrong(e, n, o)) { + e = e.substring(a.raw.length), t.push(a); + continue; + } + if (a = this.tokenizer.codespan(e)) { + e = e.substring(a.raw.length), t.push(a); + continue; + } + if (a = this.tokenizer.br(e)) { + e = e.substring(a.raw.length), t.push(a); + continue; + } + if (a = this.tokenizer.del(e, n, o)) { + e = e.substring(a.raw.length), t.push(a); + continue; + } + if (a = this.tokenizer.autolink(e)) { + e = e.substring(a.raw.length), t.push(a); + continue; + } + if (!this.state.inLink && (a = this.tokenizer.url(e))) { + e = e.substring(a.raw.length), t.push(a); + continue; + } + let c = e; + if (this.options.extensions?.startInline) { + let p = 1 / 0, k = e.slice(1), h; + this.options.extensions.startInline.forEach((R) => { + h = R.call({ lexer: this }, k), typeof h == "number" && h >= 0 && (p = Math.min(p, h)); + }), p < 1 / 0 && p >= 0 && (c = e.substring(0, p + 1)); + } + if (a = this.tokenizer.inlineText(c)) { + e = e.substring(a.raw.length), a.raw.slice(-1) !== "_" && (o = a.raw.slice(-1)), i = true; + let p = t.at(-1); + p?.type === "text" ? (p.raw += a.raw, p.text += a.text) : t.push(a); + continue; + } + if (e) { + this.infiniteLoopError(e.charCodeAt(0)); + break; + } + } + return t; + } + infiniteLoopError(e) { + let t = "Infinite loop on byte: " + e; + if (this.options.silent) console.error(t); + else throw new Error(t); + } + }; + var y = class { + constructor(e) { + __publicField(this, "options"); + __publicField(this, "parser"); + this.options = e || T; + } + space(e) { + return ""; + } + code({ text: e, lang: t, escaped: n }) { + let s = (t || "").match(m.notSpaceStart)?.[0], r = e.replace(m.endingNewline, "") + ` +`; + return s ? '
' + (n ? r : O(r, true)) + `
+` : "
" + (n ? r : O(r, true)) + `
+`; + } + blockquote({ tokens: e }) { + return `
+${this.parser.parse(e)}
+`; + } + html({ text: e }) { + return e; + } + def(e) { + return ""; + } + heading({ tokens: e, depth: t }) { + return `${this.parser.parseInline(e)} +`; + } + hr(e) { + return `
+`; + } + list(e) { + let t = e.ordered, n = e.start, s = ""; + for (let o = 0; o < e.items.length; o++) { + let u = e.items[o]; + s += this.listitem(u); + } + let r = t ? "ol" : "ul", i = t && n !== 1 ? ' start="' + n + '"' : ""; + return "<" + r + i + `> +` + s + " +`; + } + listitem(e) { + return `
  • ${this.parser.parse(e.tokens)}
  • +`; + } + checkbox({ checked: e }) { + return " '; + } + paragraph({ tokens: e }) { + return `

    ${this.parser.parseInline(e)}

    +`; + } + table(e) { + let t = "", n = ""; + for (let r = 0; r < e.header.length; r++) n += this.tablecell(e.header[r]); + t += this.tablerow({ text: n }); + let s = ""; + for (let r = 0; r < e.rows.length; r++) { + let i = e.rows[r]; + n = ""; + for (let o = 0; o < i.length; o++) n += this.tablecell(i[o]); + s += this.tablerow({ text: n }); + } + return s && (s = `${s}`), ` + +` + t + ` +` + s + `
    +`; + } + tablerow({ text: e }) { + return ` +${e} +`; + } + tablecell(e) { + let t = this.parser.parseInline(e.tokens), n = e.header ? "th" : "td"; + return (e.align ? `<${n} align="${e.align}">` : `<${n}>`) + t + ` +`; + } + strong({ tokens: e }) { + return `${this.parser.parseInline(e)}`; + } + em({ tokens: e }) { + return `${this.parser.parseInline(e)}`; + } + codespan({ text: e }) { + return `${O(e, true)}`; + } + br(e) { + return "
    "; + } + del({ tokens: e }) { + return `${this.parser.parseInline(e)}`; + } + link({ href: e, title: t, tokens: n }) { + let s = this.parser.parseInline(n), r = V(e); + if (r === null) return s; + e = r; + let i = '
    ", i; + } + image({ href: e, title: t, text: n, tokens: s }) { + s && (n = this.parser.parseInline(s, this.parser.textRenderer)); + let r = V(e); + if (r === null) return O(n); + e = r; + let i = `${O(n)} { + let o = r[i].flat(1 / 0); + n = n.concat(this.walkTokens(o, t)); + }) : r.tokens && (n = n.concat(this.walkTokens(r.tokens, t))); + } + } + return n; + } + use(...e) { + let t = this.defaults.extensions || { renderers: {}, childTokens: {} }; + return e.forEach((n) => { + let s = { ...n }; + if (s.async = this.defaults.async || s.async || false, n.extensions && (n.extensions.forEach((r) => { + if (!r.name) throw new Error("extension name required"); + if ("renderer" in r) { + let i = t.renderers[r.name]; + i ? t.renderers[r.name] = function(...o) { + let u = r.renderer.apply(this, o); + return u === false && (u = i.apply(this, o)), u; + } : t.renderers[r.name] = r.renderer; + } + if ("tokenizer" in r) { + if (!r.level || r.level !== "block" && r.level !== "inline") throw new Error("extension level must be 'block' or 'inline'"); + let i = t[r.level]; + i ? i.unshift(r.tokenizer) : t[r.level] = [r.tokenizer], r.start && (r.level === "block" ? t.startBlock ? t.startBlock.push(r.start) : t.startBlock = [r.start] : r.level === "inline" && (t.startInline ? t.startInline.push(r.start) : t.startInline = [r.start])); + } + "childTokens" in r && r.childTokens && (t.childTokens[r.name] = r.childTokens); + }), s.extensions = t), n.renderer) { + let r = this.defaults.renderer || new y(this.defaults); + for (let i in n.renderer) { + if (!(i in r)) throw new Error(`renderer '${i}' does not exist`); + if (["options", "parser"].includes(i)) continue; + let o = i, u = n.renderer[o], a = r[o]; + r[o] = (...c) => { + let p = u.apply(r, c); + return p === false && (p = a.apply(r, c)), p || ""; + }; + } + s.renderer = r; + } + if (n.tokenizer) { + let r = this.defaults.tokenizer || new w(this.defaults); + for (let i in n.tokenizer) { + if (!(i in r)) throw new Error(`tokenizer '${i}' does not exist`); + if (["options", "rules", "lexer"].includes(i)) continue; + let o = i, u = n.tokenizer[o], a = r[o]; + r[o] = (...c) => { + let p = u.apply(r, c); + return p === false && (p = a.apply(r, c)), p; + }; + } + s.tokenizer = r; + } + if (n.hooks) { + let r = this.defaults.hooks || new P(); + for (let i in n.hooks) { + if (!(i in r)) throw new Error(`hook '${i}' does not exist`); + if (["options", "block"].includes(i)) continue; + let o = i, u = n.hooks[o], a = r[o]; + P.passThroughHooks.has(i) ? r[o] = (c) => { + if (this.defaults.async && P.passThroughHooksRespectAsync.has(i)) return (async () => { + let k = await u.call(r, c); + return a.call(r, k); + })(); + let p = u.call(r, c); + return a.call(r, p); + } : r[o] = (...c) => { + if (this.defaults.async) return (async () => { + let k = await u.apply(r, c); + return k === false && (k = await a.apply(r, c)), k; + })(); + let p = u.apply(r, c); + return p === false && (p = a.apply(r, c)), p; + }; + } + s.hooks = r; + } + if (n.walkTokens) { + let r = this.defaults.walkTokens, i = n.walkTokens; + s.walkTokens = function(o) { + let u = []; + return u.push(i.call(this, o)), r && (u = u.concat(r.call(this, o))), u; + }; + } + this.defaults = { ...this.defaults, ...s }; + }), this; + } + setOptions(e) { + return this.defaults = { ...this.defaults, ...e }, this; + } + lexer(e, t) { + return x.lex(e, t ?? this.defaults); + } + parser(e, t) { + return b.parse(e, t ?? this.defaults); + } + parseMarkdown(e) { + return (n, s) => { + let r = { ...s }, i = { ...this.defaults, ...r }, o = this.onError(!!i.silent, !!i.async); + if (this.defaults.async === true && r.async === false) return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.")); + if (typeof n > "u" || n === null) return o(new Error("marked(): input parameter is undefined or null")); + if (typeof n != "string") return o(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(n) + ", string expected")); + if (i.hooks && (i.hooks.options = i, i.hooks.block = e), i.async) return (async () => { + let u = i.hooks ? await i.hooks.preprocess(n) : n, c = await (i.hooks ? await i.hooks.provideLexer(e) : e ? x.lex : x.lexInline)(u, i), p = i.hooks ? await i.hooks.processAllTokens(c) : c; + i.walkTokens && await Promise.all(this.walkTokens(p, i.walkTokens)); + let h = await (i.hooks ? await i.hooks.provideParser(e) : e ? b.parse : b.parseInline)(p, i); + return i.hooks ? await i.hooks.postprocess(h) : h; + })().catch(o); + try { + i.hooks && (n = i.hooks.preprocess(n)); + let a = (i.hooks ? i.hooks.provideLexer(e) : e ? x.lex : x.lexInline)(n, i); + i.hooks && (a = i.hooks.processAllTokens(a)), i.walkTokens && this.walkTokens(a, i.walkTokens); + let p = (i.hooks ? i.hooks.provideParser(e) : e ? b.parse : b.parseInline)(a, i); + return i.hooks && (p = i.hooks.postprocess(p)), p; + } catch (u) { + return o(u); + } + }; + } + onError(e, t) { + return (n) => { + if (n.message += ` +Please report this to https://github.com/markedjs/marked.`, e) { + let s = "

    An error occurred:

    " + O(n.message + "", true) + "
    "; + return t ? Promise.resolve(s) : s; + } + if (t) return Promise.reject(n); + throw n; + }; + } + }; + var z = new q(); + function g(l3, e) { + return z.parse(l3, e); + } + g.options = g.setOptions = function(l3) { + return z.setOptions(l3), g.defaults = z.defaults, N(g.defaults), g; + }; + g.getDefaults = M; + g.defaults = T; + g.use = function(...l3) { + return z.use(...l3), g.defaults = z.defaults, N(g.defaults), g; + }; + g.walkTokens = function(l3, e) { + return z.walkTokens(l3, e); + }; + g.parseInline = z.parseInline; + g.Parser = b; + g.parser = b.parse; + g.Renderer = y; + g.TextRenderer = L; + g.Lexer = x; + g.lexer = x.lex; + g.Tokenizer = w; + g.Hooks = P; + g.parse = g; + var Ft = g.options; + var Ut = g.setOptions; + var Kt = g.use; + var Wt = g.walkTokens; + var Xt = g.parseInline; + var Vt = b.parse; + var Yt = x.lex; + + // node_modules/get-east-asian-width/lookup-data.js + var ambiguousMinimalCodePoint = 161; + var ambiguousMaximumCodePoint = 1114109; + var ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109]; + var fullwidthMinimalCodePoint = 12288; + var fullwidthMaximumCodePoint = 65510; + var fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510]; + var wideMinimalCodePoint = 4352; + var wideMaximumCodePoint = 262141; + var wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101589, 101631, 101662, 101760, 101874, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128728, 128732, 128735, 128747, 128748, 128756, 128764, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129674, 129678, 129734, 129736, 129736, 129741, 129756, 129759, 129770, 129775, 129784, 131072, 196605, 196608, 262141]; + + // node_modules/get-east-asian-width/utilities.js + var isInRange = (ranges, codePoint) => { + let low = 0; + let high = Math.floor(ranges.length / 2) - 1; + while (low <= high) { + const mid = Math.floor((low + high) / 2); + const i = mid * 2; + if (codePoint < ranges[i]) { + high = mid - 1; + } else if (codePoint > ranges[i + 1]) { + low = mid + 1; + } else { + return true; + } + } + return false; + }; + + // node_modules/get-east-asian-width/lookup.js + var commonCjkCodePoint = 19968; + var [wideFastPathStart, wideFastPathEnd] = /* @__PURE__ */ findWideFastPathRange(wideRanges); + function findWideFastPathRange(ranges) { + let fastPathStart = ranges[0]; + let fastPathEnd = ranges[1]; + for (let index = 0; index < ranges.length; index += 2) { + const start = ranges[index]; + const end = ranges[index + 1]; + if (commonCjkCodePoint >= start && commonCjkCodePoint <= end) { + return [start, end]; + } + if (end - start > fastPathEnd - fastPathStart) { + fastPathStart = start; + fastPathEnd = end; + } + } + return [fastPathStart, fastPathEnd]; + } + var isAmbiguous = (codePoint) => { + if (codePoint < ambiguousMinimalCodePoint || codePoint > ambiguousMaximumCodePoint) { + return false; + } + return isInRange(ambiguousRanges, codePoint); + }; + var isFullWidth = (codePoint) => { + if (codePoint < fullwidthMinimalCodePoint || codePoint > fullwidthMaximumCodePoint) { + return false; + } + return isInRange(fullwidthRanges, codePoint); + }; + var isWide = (codePoint) => { + if (codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd) { + return true; + } + if (codePoint < wideMinimalCodePoint || codePoint > wideMaximumCodePoint) { + return false; + } + return isInRange(wideRanges, codePoint); + }; + + // node_modules/get-east-asian-width/index.js + function validate(codePoint) { + if (!Number.isSafeInteger(codePoint)) { + throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`); + } + } + function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) { + validate(codePoint); + if (isFullWidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) { + return 2; + } + return 1; + } + + // packages/tui/src/utils.ts + var graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" }); + var wordSegmenter = new Intl.Segmenter(void 0, { granularity: "word" }); + function couldBeEmoji(segment) { + const cp = segment.codePointAt(0); + return cp >= 126976 && cp <= 130047 || // Emoji and Pictograph + cp >= 8960 && cp <= 9215 || // Misc technical + cp >= 9728 && cp <= 10175 || // Misc symbols, dingbats + cp >= 11088 && cp <= 11093 || // Specific stars/circles + segment.includes("\uFE0F") || // Contains VS16 (emoji presentation selector) + segment.length > 2; + } + var zeroWidthRegex = new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$", "v"); + var leadingNonPrintingRegex = new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+", "v"); + var nonPrintingCharRegex = new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$", "v"); + var markCharRegex = new RegExp("^\\p{Mark}$", "v"); + var terminalSpacingMarkRegex = new RegExp("^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103E])+$", "v"); + var rgiEmojiRegex = new RegExp("^\\p{RGI_Emoji}$", "v"); + var WIDTH_CACHE_SIZE = 512; + var widthCache = /* @__PURE__ */ new Map(); + var cjkBreakRegex = /[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u; + function isPrintableAscii(str) { + for (let i = 0; i < str.length; i++) { + const code = str.charCodeAt(i); + if (code < 32 || code > 126) { + return false; + } + } + return true; + } + function graphemeWidth(segment) { + if (segment === " ") { + return 3; + } + if (terminalSpacingMarkRegex.test(segment)) { + return [...segment].length; + } + if (zeroWidthRegex.test(segment)) { + return 0; + } + if (couldBeEmoji(segment) && rgiEmojiRegex.test(segment)) { + return 2; + } + const base = segment.replace(leadingNonPrintingRegex, ""); + const cp = base.codePointAt(0); + if (cp === void 0) { + return 0; + } + if (cp >= 127462 && cp <= 127487) { + return 2; + } + let width = eastAsianWidth(cp); + let followsMark = false; + const chars = [...base]; + for (const char of chars.slice(1)) { + if (terminalSpacingMarkRegex.test(char)) { + width += 1; + followsMark = false; + } else if (markCharRegex.test(char)) { + followsMark = true; + } else if (!nonPrintingCharRegex.test(char)) { + const c = char.codePointAt(0); + if (followsMark || c >= 65280 && c <= 65519) { + width += eastAsianWidth(c); + } else if (c === 3635 || c === 3763) { + width += 1; + } + followsMark = false; + } + } + return width; + } + function visibleWidth(str) { + if (str.length === 0) { + return 0; + } + if (isPrintableAscii(str)) { + return str.length; + } + const cached = widthCache.get(str); + if (cached !== void 0) { + return cached; + } + let clean = str; + if (str.includes(" ")) { + clean = clean.replace(/\t/g, " "); + } + if (clean.includes("\x1B")) { + let stripped = ""; + let i = 0; + while (i < clean.length) { + const ansi = extractAnsiCode(clean, i); + if (ansi) { + i += ansi.length; + continue; + } + stripped += clean[i]; + i++; + } + clean = stripped; + } + let width = 0; + for (const { segment } of graphemeSegmenter.segment(clean)) { + width += graphemeWidth(segment); + } + if (widthCache.size >= WIDTH_CACHE_SIZE) { + const firstKey = widthCache.keys().next().value; + if (firstKey !== void 0) { + widthCache.delete(firstKey); + } + } + widthCache.set(str, width); + return width; + } + function extractAnsiCode(str, pos) { + if (pos >= str.length || str[pos] !== "\x1B") return null; + const next = str[pos + 1]; + if (next === "[") { + let j2 = pos + 2; + while (j2 < str.length && !/[mGKHJ]/.test(str[j2])) j2++; + if (j2 < str.length) return { code: str.substring(pos, j2 + 1), length: j2 + 1 - pos }; + return null; + } + if (next === "]") { + let j2 = pos + 2; + while (j2 < str.length) { + if (str[j2] === "\x07") return { code: str.substring(pos, j2 + 1), length: j2 + 1 - pos }; + if (str[j2] === "\x1B" && str[j2 + 1] === "\\") return { code: str.substring(pos, j2 + 2), length: j2 + 2 - pos }; + j2++; + } + return null; + } + if (next === "_") { + let j2 = pos + 2; + while (j2 < str.length) { + if (str[j2] === "\x07") return { code: str.substring(pos, j2 + 1), length: j2 + 1 - pos }; + if (str[j2] === "\x1B" && str[j2 + 1] === "\\") return { code: str.substring(pos, j2 + 2), length: j2 + 2 - pos }; + j2++; + } + return null; + } + return null; + } + function parseOsc8Hyperlink(ansiCode) { + if (!ansiCode.startsWith("\x1B]8;")) { + return void 0; + } + const terminator = ansiCode.endsWith("\x07") ? "\x07" : "\x1B\\"; + const body = ansiCode.slice(4, terminator === "\x07" ? -1 : -2); + const separatorIndex = body.indexOf(";"); + if (separatorIndex === -1) { + return void 0; + } + const params = body.slice(0, separatorIndex); + const url = body.slice(separatorIndex + 1); + if (!url) { + return null; + } + return { params, url, terminator }; + } + function formatOsc8Hyperlink(hyperlink2) { + return `\x1B]8;${hyperlink2.params};${hyperlink2.url}${hyperlink2.terminator}`; + } + function formatOsc8Close(terminator) { + return `\x1B]8;;${terminator}`; + } + var AnsiCodeTracker = class { + constructor() { + // Track individual attributes separately so we can reset them specifically + this.bold = false; + this.dim = false; + this.italic = false; + this.underline = false; + this.blink = false; + this.inverse = false; + this.hidden = false; + this.strikethrough = false; + this.fgColor = null; + // Stores the full code like "31" or "38;5;240" + this.bgColor = null; + // Stores the full code like "41" or "48;5;240" + this.activeHyperlink = null; + } + process(ansiCode) { + const hyperlink2 = parseOsc8Hyperlink(ansiCode); + if (hyperlink2 !== void 0) { + this.activeHyperlink = hyperlink2; + return; + } + if (!ansiCode.endsWith("m")) { + return; + } + const match = ansiCode.match(/\x1b\[([\d;]*)m/); + if (!match) return; + const params = match[1]; + if (params === "" || params === "0") { + this.reset(); + return; + } + const parts = params.split(";"); + let i = 0; + while (i < parts.length) { + const code = Number.parseInt(parts[i], 10); + if (code === 38 || code === 48) { + if (parts[i + 1] === "5" && parts[i + 2] !== void 0) { + const colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]}`; + if (code === 38) { + this.fgColor = colorCode; + } else { + this.bgColor = colorCode; + } + i += 3; + continue; + } else if (parts[i + 1] === "2" && parts[i + 4] !== void 0) { + const colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]};${parts[i + 3]};${parts[i + 4]}`; + if (code === 38) { + this.fgColor = colorCode; + } else { + this.bgColor = colorCode; + } + i += 5; + continue; + } + } + switch (code) { + case 0: + this.reset(); + break; + case 1: + this.bold = true; + break; + case 2: + this.dim = true; + break; + case 3: + this.italic = true; + break; + case 4: + this.underline = true; + break; + case 5: + this.blink = true; + break; + case 7: + this.inverse = true; + break; + case 8: + this.hidden = true; + break; + case 9: + this.strikethrough = true; + break; + case 21: + this.bold = false; + break; + case 22: + this.bold = false; + this.dim = false; + break; + case 23: + this.italic = false; + break; + case 24: + this.underline = false; + break; + case 25: + this.blink = false; + break; + case 27: + this.inverse = false; + break; + case 28: + this.hidden = false; + break; + case 29: + this.strikethrough = false; + break; + case 39: + this.fgColor = null; + break; + case 49: + this.bgColor = null; + break; + default: + if (code >= 30 && code <= 37 || code >= 90 && code <= 97) { + this.fgColor = String(code); + } else if (code >= 40 && code <= 47 || code >= 100 && code <= 107) { + this.bgColor = String(code); + } + break; + } + i++; + } + } + reset() { + this.bold = false; + this.dim = false; + this.italic = false; + this.underline = false; + this.blink = false; + this.inverse = false; + this.hidden = false; + this.strikethrough = false; + this.fgColor = null; + this.bgColor = null; + } + /** Clear all state for reuse. */ + clear() { + this.reset(); + this.activeHyperlink = null; + } + getActiveCodes() { + const codes = []; + if (this.bold) codes.push("1"); + if (this.dim) codes.push("2"); + if (this.italic) codes.push("3"); + if (this.underline) codes.push("4"); + if (this.blink) codes.push("5"); + if (this.inverse) codes.push("7"); + if (this.hidden) codes.push("8"); + if (this.strikethrough) codes.push("9"); + if (this.fgColor) codes.push(this.fgColor); + if (this.bgColor) codes.push(this.bgColor); + let result = codes.length > 0 ? `\x1B[${codes.join(";")}m` : ""; + if (this.activeHyperlink) { + result += formatOsc8Hyperlink(this.activeHyperlink); + } + return result; + } + hasActiveCodes() { + return this.bold || this.dim || this.italic || this.underline || this.blink || this.inverse || this.hidden || this.strikethrough || this.fgColor !== null || this.bgColor !== null || this.activeHyperlink !== null; + } + /** + * Get reset codes for attributes that need to be turned off at line end. + * Underline must be closed to prevent bleeding into padding. + * Active OSC 8 hyperlinks must be closed and re-opened on the next line. + * Returns empty string if no attributes need closing. + */ + getLineEndReset() { + let result = ""; + if (this.underline) { + result += "\x1B[24m"; + } + if (this.activeHyperlink) { + result += formatOsc8Close(this.activeHyperlink.terminator); + } + return result; + } + }; + function updateTrackerFromText(text, tracker) { + let i = 0; + while (i < text.length) { + const ansiResult = extractAnsiCode(text, i); + if (ansiResult) { + tracker.process(ansiResult.code); + i += ansiResult.length; + } else { + i++; + } + } + } + function splitIntoTokensWithAnsi(text) { + const tokens = []; + let current = ""; + let pendingAnsi = ""; + let currentKind = null; + let i = 0; + const flushCurrent = () => { + if (!current) { + return; + } + tokens.push(current); + current = ""; + currentKind = null; + }; + while (i < text.length) { + const ansiResult = extractAnsiCode(text, i); + if (ansiResult) { + pendingAnsi += ansiResult.code; + i += ansiResult.length; + continue; + } + let end = i; + while (end < text.length && !extractAnsiCode(text, end)) { + end++; + } + for (const { segment } of graphemeSegmenter.segment(text.slice(i, end))) { + const segmentIsSpace = segment === " "; + if (!segmentIsSpace && cjkBreakRegex.test(segment)) { + flushCurrent(); + const token = pendingAnsi + segment; + pendingAnsi = ""; + tokens.push(token); + continue; + } + const segmentKind = segmentIsSpace ? "space" : "word"; + if (current && currentKind !== segmentKind) { + flushCurrent(); + } + if (pendingAnsi) { + current += pendingAnsi; + pendingAnsi = ""; + } + currentKind = segmentKind; + current += segment; + } + i = end; + } + if (pendingAnsi) { + if (current) { + current += pendingAnsi; + } else if (tokens.length > 0) { + tokens[tokens.length - 1] += pendingAnsi; + } else { + current = pendingAnsi; + } + } + if (current) { + tokens.push(current); + } + return tokens; + } + function wrapTextWithAnsi(text, width) { + if (!text) { + return [""]; + } + const inputLines = text.split(/\r\n|\r|\n/); + const result = []; + const tracker = new AnsiCodeTracker(); + for (const inputLine of inputLines) { + const prefix = result.length > 0 ? tracker.getActiveCodes() : ""; + const wrappedLines = wrapSingleLine(prefix + inputLine, width); + for (const wrappedLine of wrappedLines) { + result.push(wrappedLine); + } + updateTrackerFromText(inputLine, tracker); + } + return result.length > 0 ? result : [""]; + } + function wrapSingleLine(line, width) { + if (!line) { + return [""]; + } + const visibleLength = visibleWidth(line); + if (visibleLength <= width) { + return [line]; + } + const wrapped = []; + const tracker = new AnsiCodeTracker(); + const tokens = splitIntoTokensWithAnsi(line); + let currentLine = ""; + let currentVisibleLength = 0; + for (const token of tokens) { + const tokenVisibleLength = visibleWidth(token); + const isWhitespace = token.trim() === ""; + if (tokenVisibleLength > width && !isWhitespace) { + if (currentLine) { + const lineEndReset = tracker.getLineEndReset(); + if (lineEndReset) { + currentLine += lineEndReset; + } + wrapped.push(currentLine); + currentLine = ""; + currentVisibleLength = 0; + } + const broken = breakLongWord(token, width, tracker); + for (let i = 0; i < broken.length - 1; i++) { + wrapped.push(broken[i]); + } + currentLine = broken[broken.length - 1]; + currentVisibleLength = visibleWidth(currentLine); + continue; + } + const totalNeeded = currentVisibleLength + tokenVisibleLength; + if (totalNeeded > width && currentVisibleLength > 0) { + let lineToWrap = currentLine.trimEnd(); + const lineEndReset = tracker.getLineEndReset(); + if (lineEndReset) { + lineToWrap += lineEndReset; + } + wrapped.push(lineToWrap); + if (isWhitespace) { + currentLine = tracker.getActiveCodes(); + currentVisibleLength = 0; + } else { + currentLine = tracker.getActiveCodes() + token; + currentVisibleLength = tokenVisibleLength; + } + } else { + currentLine += token; + currentVisibleLength += tokenVisibleLength; + } + updateTrackerFromText(token, tracker); + } + if (currentLine) { + wrapped.push(currentLine); + } + return wrapped.length > 0 ? wrapped.map((line2) => line2.trimEnd()) : [""]; + } + function breakLongWord(word, width, tracker) { + const lines = []; + let currentLine = tracker.getActiveCodes(); + let currentWidth = 0; + let i = 0; + const segments = []; + while (i < word.length) { + const ansiResult = extractAnsiCode(word, i); + if (ansiResult) { + segments.push({ type: "ansi", value: ansiResult.code }); + i += ansiResult.length; + } else { + let end = i; + while (end < word.length) { + const nextAnsi = extractAnsiCode(word, end); + if (nextAnsi) break; + end++; + } + const textPortion = word.slice(i, end); + for (const seg of graphemeSegmenter.segment(textPortion)) { + segments.push({ type: "grapheme", value: seg.segment }); + } + i = end; + } + } + for (const seg of segments) { + if (seg.type === "ansi") { + currentLine += seg.value; + tracker.process(seg.value); + continue; + } + const grapheme = seg.value; + if (!grapheme) continue; + const graphemeWidth2 = visibleWidth(grapheme); + if (currentWidth + graphemeWidth2 > width) { + const lineEndReset = tracker.getLineEndReset(); + if (lineEndReset) { + currentLine += lineEndReset; + } + lines.push(currentLine); + currentLine = tracker.getActiveCodes(); + currentWidth = 0; + } + currentLine += grapheme; + currentWidth += graphemeWidth2; + } + if (currentLine) { + lines.push(currentLine); + } + return lines.length > 0 ? lines : [""]; + } + function applyBackgroundToLine(line, width, bgFn) { + const visibleLen = visibleWidth(line); + const paddingNeeded = Math.max(0, width - visibleLen); + const padding = " ".repeat(paddingNeeded); + const withPadding = line + padding; + return bgFn(withPadding); + } + var pooledStyleTracker = new AnsiCodeTracker(); + + // packages/tui/src/latex.ts + var SYMBOLS = { + alpha: "\u03B1", + beta: "\u03B2", + gamma: "\u03B3", + delta: "\u03B4", + epsilon: "\u03F5", + varepsilon: "\u03B5", + zeta: "\u03B6", + eta: "\u03B7", + theta: "\u03B8", + vartheta: "\u03D1", + iota: "\u03B9", + kappa: "\u03BA", + varkappa: "\u03F0", + lambda: "\u03BB", + mu: "\u03BC", + nu: "\u03BD", + xi: "\u03BE", + pi: "\u03C0", + varpi: "\u03D6", + rho: "\u03C1", + varrho: "\u03F1", + sigma: "\u03C3", + varsigma: "\u03C2", + tau: "\u03C4", + upsilon: "\u03C5", + phi: "\u03D5", + varphi: "\u03C6", + chi: "\u03C7", + psi: "\u03C8", + omega: "\u03C9", + Gamma: "\u0393", + Delta: "\u0394", + Theta: "\u0398", + Lambda: "\u039B", + Xi: "\u039E", + Pi: "\u03A0", + Sigma: "\u03A3", + Upsilon: "\u03A5", + Phi: "\u03A6", + Psi: "\u03A8", + Omega: "\u03A9", + pm: "\xB1", + mp: "\u2213", + times: "\xD7", + div: "\xF7", + cdot: "\xB7", + ast: "\u2217", + star: "\u22C6", + circ: "\u2218", + bullet: "\u2022", + oplus: "\u2295", + ominus: "\u2296", + otimes: "\u2297", + oslash: "\u2298", + odot: "\u2299", + bigcirc: "\u25CB", + dagger: "\u2020", + ddagger: "\u2021", + amalg: "\u2A3F", + uplus: "\u228E", + sqcap: "\u2293", + sqcup: "\u2294", + triangleleft: "\u25C1", + triangleright: "\u25B7", + wr: "\u2240", + cap: "\u2229", + cup: "\u222A", + bigcap: "\u22C2", + bigcup: "\u22C3", + bigwedge: "\u22C0", + bigvee: "\u22C1", + bigsqcup: "\u2A06", + biguplus: "\u2A04", + bigoplus: "\u2A01", + bigotimes: "\u2A02", + bigodot: "\u2A00", + setminus: "\u2216", + in: "\u2208", + notin: "\u2209", + ni: "\u220B", + subset: "\u2282", + supset: "\u2283", + subseteq: "\u2286", + supseteq: "\u2287", + sqsubset: "\u228F", + sqsupset: "\u2290", + sqsubseteq: "\u2291", + sqsupseteq: "\u2292", + prec: "\u227A", + preceq: "\u227C", + succ: "\u227B", + succeq: "\u227D", + ll: "\u226A", + gg: "\u226B", + le: "\u2264", + leq: "\u2264", + leqslant: "\u2264", + ge: "\u2265", + geq: "\u2265", + geqslant: "\u2265", + ne: "\u2260", + neq: "\u2260", + equiv: "\u2261", + approx: "\u2248", + sim: "\u223C", + simeq: "\u2243", + cong: "\u2245", + asymp: "\u224D", + doteq: "\u2250", + propto: "\u221D", + parallel: "\u2225", + perp: "\u22A5", + mid: "\u2223", + vdash: "\u22A2", + dashv: "\u22A3", + models: "\u22A8", + Vdash: "\u22A9", + Vvdash: "\u22AA", + nvdash: "\u22AC", + nvDash: "\u22AD", + forall: "\u2200", + exists: "\u2203", + nexists: "\u2204", + neg: "\xAC", + land: "\u2227", + wedge: "\u2227", + lor: "\u2228", + vee: "\u2228", + to: "\u2192", + rightarrow: "\u2192", + longrightarrow: "\u2192", + leftarrow: "\u2190", + longleftarrow: "\u2190", + gets: "\u2190", + leftrightarrow: "\u2194", + longleftrightarrow: "\u2194", + hookleftarrow: "\u21A9", + hookrightarrow: "\u21AA", + twoheadleftarrow: "\u219E", + twoheadrightarrow: "\u21A0", + leftharpoonup: "\u21BC", + leftharpoondown: "\u21BD", + rightharpoonup: "\u21C0", + rightharpoondown: "\u21C1", + rightleftharpoons: "\u21CC", + leftrightharpoons: "\u21CB", + nearrow: "\u2197", + searrow: "\u2198", + swarrow: "\u2199", + nwarrow: "\u2196", + rightsquigarrow: "\u21DD", + leadsto: "\u21DD", + Rightarrow: "\u21D2", + Longrightarrow: "\u21D2", + Leftarrow: "\u21D0", + Longleftarrow: "\u21D0", + Leftrightarrow: "\u21D4", + Longleftrightarrow: "\u21D4", + implies: "\u21D2", + iff: "\u21D4", + mapsto: "\u21A6", + longmapsto: "\u21A6", + uparrow: "\u2191", + downarrow: "\u2193", + partial: "\u2202", + nabla: "\u2207", + int: "\u222B", + iint: "\u222C", + iiint: "\u222D", + oint: "\u222E", + sum: "\u2211", + prod: "\u220F", + coprod: "\u2210", + infty: "\u221E", + emptyset: "\u2205", + varnothing: "\u2205", + angle: "\u2220", + therefore: "\u2234", + because: "\u2235", + aleph: "\u2135", + beth: "\u2136", + gimel: "\u2137", + daleth: "\u2138", + top: "\u22A4", + bot: "\u22A5", + triangle: "\u25B3", + square: "\u25A1", + lozenge: "\u25CA", + checkmark: "\u2713", + complement: "\u2201", + wp: "\u2118", + prime: "\u2032", + ldots: "\u2026", + dots: "\u2026", + cdots: "\u22EF", + vdots: "\u22EE", + ddots: "\u22F1", + ell: "\u2113", + hbar: "\u210F", + Im: "\u2111", + Re: "\u211C", + langle: "\u27E8", + rangle: "\u27E9", + vert: "|", + lvert: "|", + rvert: "|", + Vert: "\u2016", + lVert: "\u2016", + rVert: "\u2016", + lbrace: "{", + rbrace: "}", + backslash: "\\", + lfloor: "\u230A", + rfloor: "\u230B", + lceil: "\u2308", + rceil: "\u2309", + colon: ":" + }; + var NAMED_OPERATORS = /* @__PURE__ */ new Set([ + "arccos", + "arcsin", + "arctan", + "arg", + "cos", + "cosh", + "cot", + "coth", + "csc", + "deg", + "det", + "dim", + "exp", + "gcd", + "hom", + "inf", + "ker", + "lg", + "lim", + "liminf", + "limsup", + "ln", + "log", + "max", + "min", + "Pr", + "sec", + "sin", + "sinh", + "sup", + "tan", + "tanh" + ]); + var LIMIT_OPERATORS = /* @__PURE__ */ new Set([ + "argmax", + "argmin", + "inf", + "injlim", + "lim", + "liminf", + "limsup", + "max", + "min", + "projlim", + "sup" + ]); + var DISPLAY_LIMIT_SYMBOLS = /* @__PURE__ */ new Set([ + "bigcap", + "bigcup", + "bigodot", + "bigoplus", + "bigotimes", + "bigsqcup", + "biguplus", + "bigvee", + "bigwedge", + "coprod", + "int", + "iint", + "iiint", + "oint", + "prod", + "sum" + ]); + var RELATION_COMMANDS = /* @__PURE__ */ new Set([ + "Leftarrow", + "Leftrightarrow", + "Longleftarrow", + "Longleftrightarrow", + "Longrightarrow", + "Rightarrow", + "Vdash", + "Vvdash", + "approx", + "asymp", + "cong", + "dashv", + "doteq", + "downarrow", + "equiv", + "ge", + "geq", + "geqslant", + "gets", + "gg", + "hookleftarrow", + "hookrightarrow", + "iff", + "implies", + "in", + "leadsto", + "le", + "leftarrow", + "leftharpoondown", + "leftharpoonup", + "leftrightarrow", + "leftrightharpoons", + "leq", + "leqslant", + "ll", + "longleftarrow", + "longleftrightarrow", + "longmapsto", + "longrightarrow", + "mapsto", + "mid", + "models", + "ne", + "nearrow", + "neq", + "ni", + "notin", + "nvdash", + "nvDash", + "nwarrow", + "parallel", + "perp", + "prec", + "preceq", + "propto", + "rightharpoondown", + "rightharpoonup", + "rightleftharpoons", + "rightarrow", + "rightsquigarrow", + "searrow", + "sim", + "simeq", + "sqsubset", + "sqsubseteq", + "sqsupset", + "sqsupseteq", + "subset", + "subseteq", + "succ", + "succeq", + "supset", + "supseteq", + "swarrow", + "to", + "triangleleft", + "triangleright", + "twoheadleftarrow", + "twoheadrightarrow", + "uparrow", + "vdash" + ]); + var NEGATED_SYMBOLS = { + "<": "\u226E", + ">": "\u226F", + "=": "\u2260", + "\u2208": "\u2209", + "\u220B": "\u220C", + "\u2223": "\u2224", + "\u2225": "\u2226", + "\u223C": "\u2241", + "\u2243": "\u2244", + "\u2245": "\u2247", + "\u2248": "\u2249", + "\u2261": "\u2262", + "\u2264": "\u2270", + "\u2265": "\u2271", + "\u227A": "\u2280", + "\u227B": "\u2281", + "\u2282": "\u2284", + "\u2283": "\u2285", + "\u2286": "\u2288", + "\u2287": "\u2289", + "\u22A2": "\u22AC", + "\u22A8": "\u22AD", + "\u2194": "\u21AE", + "\u2190": "\u219A", + "\u2192": "\u219B", + "\u21D2": "\u21CF", + "\u21D0": "\u21CD", + "\u21D4": "\u21CE", + "\u227C": "\u22E0", + "\u227D": "\u22E1" + }; + var BLACKBOARD = { + C: "\u2102", + H: "\u210D", + N: "\u2115", + P: "\u2119", + Q: "\u211A", + R: "\u211D", + Z: "\u2124" + }; + var SUPERSCRIPTS = { + "0": "\u2070", + "1": "\xB9", + "2": "\xB2", + "3": "\xB3", + "4": "\u2074", + "5": "\u2075", + "6": "\u2076", + "7": "\u2077", + "8": "\u2078", + "9": "\u2079", + "+": "\u207A", + "-": "\u207B", + "=": "\u207C", + "(": "\u207D", + ")": "\u207E", + a: "\u1D43", + b: "\u1D47", + c: "\u1D9C", + d: "\u1D48", + e: "\u1D49", + f: "\u1DA0", + g: "\u1D4D", + h: "\u02B0", + i: "\u2071", + j: "\u02B2", + k: "\u1D4F", + l: "\u02E1", + m: "\u1D50", + n: "\u207F", + o: "\u1D52", + p: "\u1D56", + r: "\u02B3", + s: "\u02E2", + t: "\u1D57", + u: "\u1D58", + v: "\u1D5B", + w: "\u02B7", + x: "\u02E3", + y: "\u02B8", + z: "\u1DBB" + }; + var SUBSCRIPTS = { + "0": "\u2080", + "1": "\u2081", + "2": "\u2082", + "3": "\u2083", + "4": "\u2084", + "5": "\u2085", + "6": "\u2086", + "7": "\u2087", + "8": "\u2088", + "9": "\u2089", + "+": "\u208A", + "-": "\u208B", + "=": "\u208C", + "(": "\u208D", + ")": "\u208E", + a: "\u2090", + e: "\u2091", + h: "\u2095", + i: "\u1D62", + j: "\u2C7C", + k: "\u2096", + l: "\u2097", + m: "\u2098", + n: "\u2099", + o: "\u2092", + p: "\u209A", + r: "\u1D63", + s: "\u209B", + t: "\u209C", + u: "\u1D64", + v: "\u1D65", + x: "\u2093" + }; + var SPACING_COMMANDS = /* @__PURE__ */ new Set([ + ",", + ":", + ";", + " ", + ">", + "enspace", + "enskip", + "medspace", + "quad", + "qquad", + "thickspace", + "thinspace" + ]); + var NEGATIVE_SPACING_COMMANDS = /* @__PURE__ */ new Set(["!", "negmedspace", "negthickspace", "negthinspace"]); + var NEGATIVE_SPACE = "\0"; + var IGNORED_COMMANDS = /* @__PURE__ */ new Set([ + "displaystyle", + "limits", + "nolimits", + "scriptstyle", + "scriptscriptstyle", + "textstyle" + ]); + var SIZE_COMMANDS = /* @__PURE__ */ new Set([ + "big", + "Big", + "bigg", + "Bigg", + "bigl", + "Bigl", + "biggl", + "Biggl", + "bigr", + "Bigr", + "biggr", + "Biggr" + ]); + var PLAIN_WRAPPERS = /* @__PURE__ */ new Set([ + "emph", + "mathcal", + "mathbf", + "mathfrak", + "mathit", + "mathrm", + "mathnormal", + "mathscr", + "mathsf", + "mathtt", + "mathup", + "mbox", + "overbrace", + "pmb", + "smash", + "substack", + "text", + "textbf", + "textit", + "textmd", + "textnormal", + "textrm", + "textsc", + "textsf", + "textsl", + "texttt", + "textup", + "underbrace", + "bm", + "boldsymbol" + ]); + var ACCENTS = { + acute: "\u0301", + bar: "\u0305", + breve: "\u0306", + check: "\u030C", + ddot: "\u0308", + dot: "\u0307", + grave: "\u0300", + hat: "\u0302", + mathring: "\u030A", + overleftarrow: "\u20D6", + overleftrightarrow: "\u20E1", + overline: "\u0305", + overrightarrow: "\u20D7", + tilde: "\u0303", + underline: "\u0332", + vec: "\u20D7", + widehat: "\u0302", + widetilde: "\u0303" + }; + function replaceCharacters(value, replacements) { + let result = ""; + for (const character of value) { + const replacement = replacements[character]; + if (replacement === void 0) { + return void 0; + } + result += replacement; + } + return result; + } + function formatScript(value, kind) { + value = value.trim(); + const replacements = kind === "sub" ? SUBSCRIPTS : SUPERSCRIPTS; + const unicode = replaceCharacters(value.replace(/\s*([=+-])\s*/g, "$1"), replacements); + if (unicode !== void 0) { + return unicode; + } + const prefix = kind === "sub" ? "_" : "^"; + if (Array.from(value).length === 1 || kind === "sub" && /^[A-Za-z]+$/.test(value)) { + return `${prefix}${value}`; + } + return `${prefix}(${value})`; + } + function formatFraction(numerator, denominator) { + numerator = numerator.trim(); + denominator = denominator.trim(); + const simpleNumerator = /^[\p{L}\p{N}.]+$/u.test(numerator); + const simpleDenominator = /^[\p{N}.]+$/u.test(denominator) || Array.from(denominator).length === 1; + return `${simpleNumerator ? numerator : `(${numerator})`}/${simpleDenominator ? denominator : `(${denominator})`}`; + } + function formatRoot(value, symbol = "\u221A") { + value = value.trim(); + return /^[\p{L}\p{N}.]+$/u.test(value) ? `${symbol}${value}` : `${symbol}(${value})`; + } + var NAMED_OPERATOR_START = "\u{F0004}"; + var NAMED_OPERATOR_END = "\u{F0005}"; + var NAMED_OPERATOR_LEFT_SPACING_PATTERN = /(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu; + var NAMED_OPERATOR_RIGHT_SPACING_PATTERN = /\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu; + function normalizeOutput(value) { + return value.replace(NAMED_OPERATOR_LEFT_SPACING_PATTERN, " ").replaceAll(NAMED_OPERATOR_START, "").replace(NAMED_OPERATOR_RIGHT_SPACING_PATTERN, " ").replaceAll(NAMED_OPERATOR_END, "").split("\n").map((line) => line.replace(/[ \t]+/g, " ").trim()).filter((line, index, lines) => line.length > 0 || index > 0 && index < lines.length - 1).join("\n").trim(); + } + var LAYOUT_MARKER_START = "\u{F0000}"; + var LAYOUT_MARKER_END = "\u{F0001}"; + var LAYOUT_MARKER_PATTERN = /\u{f0000}(\d+)\u{f0001}/gu; + var TRAILING_LAYOUT_MARKER_PATTERN = /\u{f0000}(\d+)\u{f0001}$/u; + var PROTECTED_SPACE = "\u{F0002}"; + function padLayoutLine(line, width, centered = false) { + const padding = Math.max(0, width - visibleWidth(line)); + const left = centered ? Math.floor(padding / 2) : 0; + return `${" ".repeat(left)}${line}${" ".repeat(padding - left)}`; + } + function joinLayouts(layouts) { + if (layouts.length === 0) { + return { lines: [""], width: 0, baseline: 0 }; + } + const baseline = Math.max(...layouts.map((layout) => layout.baseline)); + const below = Math.max(...layouts.map((layout) => layout.lines.length - layout.baseline - 1)); + const lines = []; + for (let row = 0; row <= baseline + below; row++) { + let line = ""; + for (const layout of layouts) { + const sourceRow = row - baseline + layout.baseline; + line += sourceRow >= 0 && sourceRow < layout.lines.length ? padLayoutLine(layout.lines[sourceRow] ?? "", layout.width) : " ".repeat(layout.width); + } + lines.push(line.trimEnd()); + } + return { + lines, + width: layouts.reduce((width, layout) => width + layout.width, 0), + baseline + }; + } + function renderLayout(source, nodes) { + const renderedLines = []; + let firstBaseline = 0; + for (const sourceLine of source.split("\n")) { + const layouts = []; + let position = 0; + let previousNode; + for (const match of sourceLine.matchAll(LAYOUT_MARKER_PATTERN)) { + const index = match.index; + const node = nodes[Number(match[1])]; + if (!node) { + continue; + } + if (index > position) { + const sliced = sourceLine.slice(position, index); + const trimmed = (previousNode ? sliced.trimStart() : sliced).trimEnd(); + const preserveLeadingSpace = previousNode?.type === "matrix" && /^\s/.test(sliced); + const preserveTrailingSpace = node.type === "matrix" && /\s$/.test(sliced); + const text = trimmed ? `${preserveLeadingSpace ? " " : ""}${trimmed}${preserveTrailingSpace ? " " : ""}` : preserveLeadingSpace || preserveTrailingSpace ? " " : ""; + layouts.push({ lines: [text], width: visibleWidth(text), baseline: 0 }); + } + if (node.type === "fraction") { + const numerator = renderLayout(node.numerator, nodes); + const denominator = renderLayout(node.denominator, nodes); + const contentWidth = Math.max(numerator.width, denominator.width, 1); + const width = contentWidth + 2; + layouts.push({ + lines: [ + ...numerator.lines.map((line) => padLayoutLine(line, width, true)), + ` ${"\u2500".repeat(contentWidth)} `, + ...denominator.lines.map((line) => padLayoutLine(line, width, true)) + ], + width, + baseline: numerator.lines.length + }); + } else if (node.type === "operator") { + const contentWidth = Math.max( + visibleWidth(node.operator), + node.lower === void 0 ? 0 : visibleWidth(node.lower), + node.upper === void 0 ? 0 : visibleWidth(node.upper) + ); + const lines = []; + if (node.upper !== void 0) { + lines.push(`${padLayoutLine(node.upper, contentWidth, true)} `); + } + lines.push(`${padLayoutLine(node.operator, contentWidth, true)} `); + if (node.lower !== void 0) { + lines.push(`${padLayoutLine(node.lower, contentWidth, true)} `); + } + layouts.push({ + lines, + width: contentWidth + 1, + baseline: node.upper === void 0 ? 0 : 1 + }); + } else { + const width = Math.max(0, ...node.lines.map((line) => visibleWidth(line))); + layouts.push({ + lines: node.lines.map((line) => padLayoutLine(line, width)), + width, + baseline: node.baseline + }); + } + position = index + match[0].length; + previousNode = node; + } + if (position < sourceLine.length) { + const sliced = sourceLine.slice(position); + const trimmed = previousNode ? sliced.trimStart() : sliced; + const text = previousNode?.type === "matrix" && /^\s/.test(sliced) ? ` ${trimmed}` : trimmed; + layouts.push({ lines: [text], width: visibleWidth(text), baseline: 0 }); + } + const lineLayout = joinLayouts(layouts); + if (renderedLines.length === 0) { + firstBaseline = lineLayout.baseline; + } + renderedLines.push(...lineLayout.lines); + } + return { + lines: renderedLines, + width: Math.max(0, ...renderedLines.map((line) => visibleWidth(line))), + baseline: firstBaseline + }; + } + var LatexParser = class _LatexParser { + constructor(source, layoutNodes, display) { + this.position = 0; + this.supported = true; + this.stackFractions = true; + this.source = source; + this.layoutNodes = layoutNodes; + this.display = display; + } + render() { + const rendered = this.parseSequence(); + if (!this.supported || this.position !== this.source.length) { + return void 0; + } + return normalizeOutput(rendered); + } + parseSequence(endCharacter) { + let result = ""; + while (this.position < this.source.length) { + const character = this.source[this.position]; + if (endCharacter && character === endCharacter) { + this.position++; + return result; + } + if (character === "}") { + this.supported = false; + return result; + } + if (character === "{") { + this.position++; + result += this.parseSequence("}"); + continue; + } + if (character === "\\") { + const command = this.parseCommand(); + if (command === NEGATIVE_SPACE) { + result = result.trimEnd(); + if (result.endsWith(NAMED_OPERATOR_END)) { + result = result.slice(0, -NAMED_OPERATOR_END.length); + } + } else { + result += command; + } + continue; + } + if (character === "^" || character === "_") { + this.position++; + result = result.trimEnd(); + const script = formatScript(this.parseRequiredArgument(false), character === "_" ? "sub" : "sup"); + if (result.endsWith(NAMED_OPERATOR_END)) { + result = `${result.slice(0, -NAMED_OPERATOR_END.length)}${script}${NAMED_OPERATOR_END}`; + } else { + result += script; + } + continue; + } + if (/\s/.test(character)) { + result += this.parseWhitespace(); + continue; + } + if (character === "=" || character === "<" || character === ">") { + result = `${result.trimEnd()} ${character} `; + this.position++; + continue; + } + if (character === "&") { + this.position++; + continue; + } + if (character === "~") { + this.position++; + result += " "; + continue; + } + if (character === ".") { + const marker = TRAILING_LAYOUT_MARKER_PATTERN.exec(result); + const node = marker ? this.layoutNodes[Number(marker[1])] : void 0; + if (node?.type === "matrix") { + const lastLine = node.lines.length - 1; + node.lines[lastLine] = `${node.lines[lastLine] ?? ""}${character}`; + this.position++; + continue; + } + } + result += character; + this.position++; + } + if (endCharacter) { + this.supported = false; + } + return result; + } + parseWhitespace() { + while (this.position < this.source.length && /\s/.test(this.source[this.position] ?? "")) { + this.position++; + } + return " "; + } + parseCommand() { + this.position++; + if (this.position >= this.source.length) { + this.supported = false; + return ""; + } + let command = ""; + const first = this.source[this.position] ?? ""; + if (first === "\n" || first === "\r") { + this.position++; + if (first === "\r" && this.source[this.position] === "\n") { + this.position++; + } + return " "; + } + if (/[A-Za-z]/.test(first)) { + const start = this.position; + while (this.position < this.source.length && /[A-Za-z]/.test(this.source[this.position] ?? "")) { + this.position++; + } + command = this.source.slice(start, this.position); + } else { + command = first; + this.position++; + } + if (command === "\\") { + return "\n"; + } + if (SPACING_COMMANDS.has(command)) { + return " "; + } + if (NEGATIVE_SPACING_COMMANDS.has(command)) { + return NEGATIVE_SPACE; + } + if (IGNORED_COMMANDS.has(command)) { + return ""; + } + if (command === "{" || command === "}" || command === "$" || command === "%" || command === "#" || command === "_" || command === "&") { + return command; + } + if (command === "|") { + return "\u2016"; + } + if (command === "not") { + const value = this.parseRequiredArgument(false).trim(); + const negated = NEGATED_SYMBOLS[value]; + if (negated !== void 0) { + return ` ${negated} `; + } + const characters = Array.from(value); + if (characters.length === 0) { + this.supported = false; + return ""; + } + return ` ${characters[0]}\u0338${characters.slice(1).join("")} `; + } + if (LIMIT_OPERATORS.has(command)) { + return this.parseOperator(command, "bracket", true, true); + } + const symbol = SYMBOLS[command]; + if (symbol !== void 0) { + if (DISPLAY_LIMIT_SYMBOLS.has(command)) { + return this.parseOperator(symbol, "script", true); + } + return command === "cdot" || command === "times" || RELATION_COMMANDS.has(command) ? ` ${symbol} ` : symbol; + } + if (NAMED_OPERATORS.has(command)) { + return `${NAMED_OPERATOR_START}${command}${NAMED_OPERATOR_END}`; + } + if (SIZE_COMMANDS.has(command)) { + return ""; + } + if (command === "left" || command === "middle" || command === "right") { + if (this.source[this.position] === ".") { + this.position++; + } + return ""; + } + if (command === "frac" || command === "dfrac" || command === "tfrac") { + const shouldStack = this.display && this.stackFractions && command !== "tfrac"; + const numerator = this.parseRequiredArgument(!shouldStack); + const denominator = this.parseRequiredArgument(!shouldStack); + if (shouldStack) { + const index = this.layoutNodes.push({ + type: "fraction", + numerator: normalizeOutput(numerator), + denominator: normalizeOutput(denominator) + }) - 1; + return `${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`; + } + return formatFraction(numerator, denominator); + } + if (command === "sqrt") { + const degree = this.parseOptionalArgument()?.trim(); + const value = this.parseRequiredArgument(); + if (degree === void 0 || degree === "2") { + return formatRoot(value); + } + if (degree === "3") { + return formatRoot(value, "\u221B"); + } + if (degree === "4") { + return formatRoot(value, "\u221C"); + } + return `${formatScript(degree, "sup")}${formatRoot(value)}`; + } + if (command === "boxed" || command === "fbox") { + return `[${this.parseRequiredArgument().trim()}]`; + } + if (command === "binom" || command === "dbinom" || command === "tbinom") { + return `(${this.parseRequiredArgument()} choose ${this.parseRequiredArgument()})`; + } + const accent = ACCENTS[command]; + if (accent !== void 0) { + const value = this.parseRequiredArgument(); + return Array.from(value).length === 1 ? `${value}${accent}` : `${command}(${value})`; + } + if (command === "mathbb") { + const value = this.parseRequiredArgument(); + return Array.from(value, (character) => BLACKBOARD[character] ?? character).join(""); + } + if (command === "operatorname") { + const starred = this.source[this.position] === "*"; + if (starred) { + this.position++; + } + const operator = normalizeOutput(this.parseRequiredArgument()).trim(); + return this.parseOperator(operator, "bracket", starred, true); + } + if (command === "mod" || command === "bmod") { + return " mod "; + } + if (command === "pmod" || command === "pod") { + const value = this.parseRequiredArgument().trim(); + return command === "pmod" ? ` (mod ${value})` : ` (${value})`; + } + if (command === "overset" || command === "stackrel") { + const upper = this.parseRequiredArgument(); + const value = this.parseRequiredArgument().trim(); + return `${value}${formatScript(upper, "sup")}`; + } + if (command === "underset") { + const lower = this.parseRequiredArgument(); + const value = this.parseRequiredArgument().trim(); + return `${value}${formatScript(lower, "sub")}`; + } + if (PLAIN_WRAPPERS.has(command)) { + const value = this.parseRequiredArgument(); + return command.startsWith("text") || command === "mbox" ? value : value.trim(); + } + if (command === "begin") { + return this.parseEnvironment(); + } + if (command === "end") { + this.supported = false; + return ""; + } + this.supported = false; + return `\\${command}`; + } + parseOperator(operator, inlineLowerStyle, displayLimits, spaced = false) { + let useDisplayLimits = displayLimits; + let modifierPosition = this.position; + while (modifierPosition < this.source.length && /[ \t]/.test(this.source[modifierPosition] ?? "")) { + modifierPosition++; + } + const modifier = /^\\(limits|nolimits)(?![A-Za-z])/.exec(this.source.slice(modifierPosition)); + if (modifier) { + useDisplayLimits = modifier[1] === "limits"; + this.position = modifierPosition + modifier[0].length; + } + let lower; + let upper; + while (true) { + let scriptPosition = this.position; + while (scriptPosition < this.source.length && /[ \t]/.test(this.source[scriptPosition] ?? "")) { + scriptPosition++; + } + const kind = this.source[scriptPosition]; + if (kind !== "_" && kind !== "^") { + break; + } + this.position = scriptPosition + 1; + const value = normalizeOutput(this.parseRequiredArgument(false)).replaceAll(" ", ""); + if (kind === "_") { + if (lower !== void 0) { + this.supported = false; + } + lower = value; + } else { + if (upper !== void 0) { + this.supported = false; + } + upper = value; + } + } + if (this.display && useDisplayLimits && (lower !== void 0 || upper !== void 0)) { + const index = this.layoutNodes.push({ type: "operator", operator, lower, upper }) - 1; + return `${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`; + } + let rendered = operator; + if (lower !== void 0) { + rendered += inlineLowerStyle === "bracket" ? `[${lower}]` : formatScript(lower, "sub"); + } + if (upper !== void 0) { + rendered += formatScript(upper, "sup"); + } + return spaced ? ` ${rendered} ` : rendered; + } + parseRequiredArgument(stackFractions = true) { + const previousStackFractions = this.stackFractions; + this.stackFractions = previousStackFractions && stackFractions; + const value = this.parseRequiredArgumentValue(); + this.stackFractions = previousStackFractions; + return value; + } + parseRequiredArgumentValue() { + while (this.position < this.source.length && /\s/.test(this.source[this.position] ?? "")) { + this.position++; + } + if (this.position >= this.source.length) { + this.supported = false; + return ""; + } + if (this.source[this.position] === "{") { + this.position++; + return this.parseSequence("}"); + } + if (this.source[this.position] === "\\") { + return this.parseCommand(); + } + const value = this.source[this.position] ?? ""; + this.position++; + return value; + } + parseOptionalArgument() { + while (this.position < this.source.length && /[ \t]/.test(this.source[this.position] ?? "")) { + this.position++; + } + if (this.source[this.position] !== "[") { + return void 0; + } + const end = this.source.indexOf("]", this.position + 1); + if (end < 0) { + this.supported = false; + return void 0; + } + const value = this.source.slice(this.position + 1, end); + this.position = end + 1; + return this.renderNested(value); + } + readRawGroup() { + while (this.position < this.source.length && /[ \t]/.test(this.source[this.position] ?? "")) { + this.position++; + } + if (this.source[this.position] !== "{") { + this.supported = false; + return void 0; + } + const start = ++this.position; + let depth = 1; + while (this.position < this.source.length) { + const character = this.source[this.position]; + if (character === "\\") { + this.position += 2; + continue; + } + if (character === "{") depth++; + if (character === "}") depth--; + if (depth === 0) { + const value = this.source.slice(start, this.position); + this.position++; + return value; + } + this.position++; + } + this.supported = false; + return void 0; + } + splitEnvironmentRows(body) { + return body.split(/\\\\(?:\[[^\]\n]*\])?/); + } + parseEnvironment() { + const environment = this.readRawGroup(); + if (!environment) { + return ""; + } + const endMarker = `\\end{${environment}}`; + const end = this.source.indexOf(endMarker, this.position); + if (end < 0) { + this.supported = false; + return ""; + } + const body = this.source.slice(this.position, end); + this.position = end + endMarker.length; + if (environment === "equation" || environment === "equation*" || environment === "displaymath") { + return this.renderNested(body).trim(); + } + if (environment === "aligned" || environment === "align" || environment === "align*" || environment === "alignedat" || environment === "alignat" || environment === "alignat*" || environment === "gather" || environment === "gathered" || environment === "multline" || environment === "multline*" || environment === "split") { + const alignedAt = ["alignedat", "alignat", "alignat*"].includes(environment); + const alignedBody = alignedAt ? body.replace(/^\s*\{[^}]*\}/, "") : body; + return this.splitEnvironmentRows(alignedBody).map((row) => { + const cells = row.split("&"); + const source = alignedAt ? Array.from( + { length: Math.ceil(cells.length / 2) }, + (_2, index) => cells.slice(index * 2, index * 2 + 2).join("") + ).join(" ") : cells.join(""); + return this.renderNested(source).trim(); + }).filter(Boolean).join("\n"); + } + if (environment === "cases" || environment === "cases*") { + const rows = this.splitEnvironmentRows(body).map((row) => row.split("&").map((cell) => this.renderNested(cell, false).trim())).filter((row) => row.some(Boolean)); + return rows.map((row, index) => { + const value = (row[0] ?? "").replace(/,\s*$/, ""); + const condition = row[1] ?? ""; + const delimiter = index === 0 ? "\u23A7" : index === rows.length - 1 ? "\u23A9" : "\u23A8"; + const conditionPrefix = /^(?:if|when|for|otherwise)\b/i.test(condition) ? " " : " if "; + return `${delimiter} ${value}${condition ? `${conditionPrefix}${condition}` : ""}`; + }).join("\n"); + } + if (["array", "matrix", "smallmatrix", "pmatrix", "bmatrix", "Bmatrix", "vmatrix", "Vmatrix"].includes(environment)) { + const matrixBody = environment === "array" ? body.replace(/^\s*\{[^}]*\}/, "") : body; + return this.renderMatrix(environment, matrixBody); + } + this.supported = false; + return body; + } + renderMatrix(environment, body) { + const matrix = this.splitEnvironmentRows(body).map((row) => row.split("&").map((cell) => this.renderNested(cell, false).trim())).filter((row) => row.some(Boolean)); + const columnCount = Math.max(0, ...matrix.map((row) => row.length)); + const columnWidths = Array.from( + { length: columnCount }, + (_2, column) => Math.max(0, ...matrix.map((row) => visibleWidth(row[column] ?? ""))) + ); + const rows = matrix.map( + (row) => Array.from({ length: columnCount }, (_2, column) => { + const cell = row[column] ?? ""; + return `${cell}${PROTECTED_SPACE.repeat(Math.max(0, (columnWidths[column] ?? 0) - visibleWidth(cell)))}`; + }).join(" \u2502 ") + ); + let lines; + if (environment === "array" || environment === "matrix" || environment === "smallmatrix") { + lines = rows; + } else { + const delimiters = { + pmatrix: ["\u239B", "\u239E", "\u239C", "\u239F", "\u239D", "\u23A0"], + bmatrix: ["\u23A1", "\u23A4", "\u23A2", "\u23A5", "\u23A3", "\u23A6"], + Bmatrix: ["\u23A7", "\u23AB", "\u23A8", "\u23AC", "\u23A9", "\u23AD"], + vmatrix: ["\u2502", "\u2502", "\u2502", "\u2502", "\u2502", "\u2502"], + Vmatrix: ["\u2551", "\u2551", "\u2551", "\u2551", "\u2551", "\u2551"] + }; + const delimiter = delimiters[environment]; + if (!delimiter) { + this.supported = false; + return rows.join("\n"); + } + lines = rows.map((row, index2) => { + const left = index2 === 0 ? delimiter[0] : index2 === rows.length - 1 ? delimiter[4] : delimiter[2]; + const right = index2 === 0 ? delimiter[1] : index2 === rows.length - 1 ? delimiter[5] : delimiter[3]; + return `${left} ${row} ${right}`; + }); + } + if (lines.length <= 1) { + return lines[0] ?? ""; + } + const index = this.layoutNodes.push({ type: "matrix", lines, baseline: 0 }) - 1; + return `${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`; + } + renderNested(source, stackFractions = true) { + const rendered = new _LatexParser(source, this.layoutNodes, this.display && stackFractions).render(); + if (rendered === void 0) { + this.supported = false; + return source; + } + return rendered; + } + }; + function renderLatex(source, options = {}) { + const layoutNodes = []; + const rendered = new LatexParser(source, layoutNodes, options.display === true).render(); + if (rendered === void 0) { + return void 0; + } + if (layoutNodes.length === 0) { + return rendered.replaceAll(PROTECTED_SPACE, " "); + } + const lines = renderLayout(rendered, layoutNodes).lines; + const indentation = Math.min( + ...lines.filter((line) => line.trim()).map((line) => line.length - line.trimStart().length) + ); + return lines.map((line) => line.slice(indentation).trimEnd()).join("\n").trimEnd().replaceAll(PROTECTED_SPACE, " "); + } + + // ../../../tmp/qtest/shim/terminal-image.ts + var getCapabilities = () => ({ images: false, hyperlinks: false }); + var hyperlink = (text, _url) => text; + var isImageLine = () => false; + + // packages/tui/src/components/markdown.ts + var STRICT_STRIKETHROUGH_REGEX = /^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/; + var StrictStrikethroughTokenizer = class extends w { + del(src) { + const match = STRICT_STRIKETHROUGH_REGEX.exec(src); + if (!match) { + return void 0; + } + const text = match[2]; + return { + type: "del", + raw: match[0], + text, + tokens: this.lexer.inlineTokens(text) + }; + } + }; + function isEscaped(source, index) { + let backslashes = 0; + for (let position = index - 1; position >= 0 && source[position] === "\\"; position--) { + backslashes++; + } + return backslashes % 2 === 1; + } + function findClosingDelimiter(source, closing, start) { + let index = source.indexOf(closing, start); + while (index >= 0 && isEscaped(source, index)) { + index = source.indexOf(closing, index + closing.length); + } + return index; + } + function looksLikePendingDollarMath(source) { + return /\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(source); + } + function tokenizeInlineLatex(source) { + let opening = ""; + let closing = ""; + if (source.startsWith("$$")) { + opening = "$$"; + closing = "$$"; + } else if (source.startsWith("\\(")) { + opening = "\\("; + closing = "\\)"; + } else if (source.startsWith("\\[")) { + opening = "\\["; + closing = "\\]"; + } else if (source.startsWith("$") && !/^\$\s/.test(source)) { + opening = "$"; + closing = "$"; + } else { + return void 0; + } + const closingIndex = findClosingDelimiter(source, closing, opening.length); + if (closingIndex >= 0 && opening === "$" && (/\s$/.test(source.slice(opening.length, closingIndex)) || /^\d/.test(source.slice(closingIndex + 1)) || /^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(source.slice(opening.length, closingIndex)) && /^[A-Za-z_][A-Za-z0-9_]*/.test(source.slice(closingIndex + 1)) || source.slice(opening.length, closingIndex).includes("`"))) { + return void 0; + } + if (closingIndex < 0) { + const pendingSource = source.slice(opening.length); + if (opening.startsWith("\\") || looksLikePendingDollarMath(pendingSource)) { + return { type: "latex", raw: source, text: pendingSource, pending: true }; + } + return void 0; + } + const text = source.slice(opening.length, closingIndex); + if (!text || text.includes("\n")) { + return void 0; + } + const raw = source.slice(0, closingIndex + closing.length); + return { type: "latex", raw, text }; + } + function tokenizeBlockLatex(source) { + const dollarMatch = /^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source); + if (dollarMatch?.[1]) { + return { type: "latexBlock", raw: dollarMatch[0], text: dollarMatch[1].trim() }; + } + const bracketMatch = /^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(source); + if (bracketMatch?.[1]) { + return { type: "latexBlock", raw: bracketMatch[0], text: bracketMatch[1].trim() }; + } + const pendingBracket = /^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(source); + if (pendingBracket) { + return { type: "latexBlock", raw: pendingBracket[0], text: pendingBracket[1], pending: true }; + } + const pendingDollar = /^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(source); + if (pendingDollar?.[1] && looksLikePendingDollarMath(pendingDollar[1])) { + return { type: "latexBlock", raw: pendingDollar[0], text: pendingDollar[1], pending: true }; + } + return void 0; + } + var LATEX_MARKDOWN_EXTENSIONS = [ + { + name: "latexBlock", + level: "block", + start(source) { + const match = /(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source); + return match ? match.index + (match[0].startsWith("\n") ? 1 : 0) : void 0; + }, + tokenizer: tokenizeBlockLatex + }, + { + name: "latex", + level: "inline", + start(source) { + const indices = [source.indexOf("$"), source.indexOf("\\("), source.indexOf("\\[")].filter( + (index) => index >= 0 + ); + return indices.length > 0 ? Math.min(...indices) : void 0; + }, + tokenizer: tokenizeInlineLatex + } + ]; + function trimPartialClosingFences(tokens) { + const token = tokens[tokens.length - 1]; + if (token?.type === "list") { + trimPartialClosingFences(token.items[token.items.length - 1]?.tokens ?? []); + return; + } + if (token?.type === "blockquote") { + trimPartialClosingFences(token.tokens ?? []); + return; + } + if (token?.type !== "code") { + return; + } + const marker = /^(`{3,}|~{3,})/.exec(token.raw)?.[1]; + const lastLine = token.raw.split("\n").pop(); + if (!marker || !lastLine || lastLine.length >= marker.length || lastLine !== marker[0]?.repeat(lastLine.length)) { + return; + } + token.text = token.text.slice(0, -lastLine.length).replace(/\n$/, ""); + } + var markdownParser = new q(); + markdownParser.setOptions({ + tokenizer: new StrictStrikethroughTokenizer() + }); + markdownParser.use({ extensions: [...LATEX_MARKDOWN_EXTENSIONS] }); + var Markdown = class { + constructor(text, paddingX, paddingY, theme, defaultTextStyle, options) { + this.text = text; + this.paddingX = paddingX; + this.paddingY = paddingY; + this.theme = theme; + this.defaultTextStyle = defaultTextStyle; + this.options = options ? { ...options } : {}; + } + setText(text) { + this.text = text; + this.invalidate(); + } + invalidate() { + this.cachedText = void 0; + this.cachedWidth = void 0; + this.cachedLines = void 0; + } + render(width) { + if (this.cachedLines && this.cachedText === this.text && this.cachedWidth === width) { + return this.cachedLines; + } + const contentWidth = Math.max(1, width - this.paddingX * 2); + const text = this.options.transform?.(this.text, contentWidth) ?? this.text; + if (!text || text.trim() === "") { + const result2 = []; + this.cachedText = this.text; + this.cachedWidth = width; + this.cachedLines = result2; + return result2; + } + const normalizedText = text.replace(/\t/g, " "); + const tokens = markdownParser.lexer(normalizedText); + trimPartialClosingFences(tokens); + const renderedLines = []; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + const nextToken = tokens[i + 1]; + const tokenLines = this.renderToken(token, contentWidth, nextToken?.type); + for (const tokenLine of tokenLines) { + renderedLines.push(tokenLine); + } + } + const wrappedLines = []; + for (const line of renderedLines) { + if (isImageLine(line)) { + wrappedLines.push(line); + } else { + for (const wrappedLine of wrapTextWithAnsi(line, contentWidth)) { + wrappedLines.push(wrappedLine); + } + } + } + const leftMargin = " ".repeat(this.paddingX); + const rightMargin = " ".repeat(this.paddingX); + const bgFn = this.defaultTextStyle?.bgColor; + const contentLines = []; + for (const line of wrappedLines) { + if (isImageLine(line)) { + contentLines.push(line); + continue; + } + const lineWithMargins = leftMargin + line + rightMargin; + if (bgFn) { + contentLines.push(applyBackgroundToLine(lineWithMargins, width, bgFn)); + } else { + const visibleLen = visibleWidth(lineWithMargins); + const paddingNeeded = Math.max(0, width - visibleLen); + contentLines.push(lineWithMargins + " ".repeat(paddingNeeded)); + } + } + const emptyLine = " ".repeat(width); + const emptyLines = []; + for (let i = 0; i < this.paddingY; i++) { + const line = bgFn ? applyBackgroundToLine(emptyLine, width, bgFn) : emptyLine; + emptyLines.push(line); + } + const result = emptyLines.concat(contentLines, emptyLines); + this.cachedText = this.text; + this.cachedWidth = width; + this.cachedLines = result; + return result.length > 0 ? result : [""]; + } + /** + * Apply default text style to a string. + * This is the base styling applied to all text content. + * NOTE: Background color is NOT applied here - it's applied at the padding stage + * to ensure it extends to the full line width. + */ + applyDefaultStyle(text) { + if (!this.defaultTextStyle) { + return text; + } + let styled = text; + if (this.defaultTextStyle.color) { + styled = this.defaultTextStyle.color(styled); + } + if (this.defaultTextStyle.bold) { + styled = this.theme.bold(styled); + } + if (this.defaultTextStyle.italic) { + styled = this.theme.italic(styled); + } + if (this.defaultTextStyle.strikethrough) { + styled = this.theme.strikethrough(styled); + } + if (this.defaultTextStyle.underline) { + styled = this.theme.underline(styled); + } + return styled; + } + getDefaultStylePrefix() { + if (!this.defaultTextStyle) { + return ""; + } + if (this.defaultStylePrefix !== void 0) { + return this.defaultStylePrefix; + } + const sentinel = "\0"; + let styled = sentinel; + if (this.defaultTextStyle.color) { + styled = this.defaultTextStyle.color(styled); + } + if (this.defaultTextStyle.bold) { + styled = this.theme.bold(styled); + } + if (this.defaultTextStyle.italic) { + styled = this.theme.italic(styled); + } + if (this.defaultTextStyle.strikethrough) { + styled = this.theme.strikethrough(styled); + } + if (this.defaultTextStyle.underline) { + styled = this.theme.underline(styled); + } + const sentinelIndex = styled.indexOf(sentinel); + this.defaultStylePrefix = sentinelIndex >= 0 ? styled.slice(0, sentinelIndex) : ""; + return this.defaultStylePrefix; + } + getStylePrefix(styleFn) { + const sentinel = "\0"; + const styled = styleFn(sentinel); + const sentinelIndex = styled.indexOf(sentinel); + return sentinelIndex >= 0 ? styled.slice(0, sentinelIndex) : ""; + } + getDefaultInlineStyleContext() { + return { + applyText: (text) => this.applyDefaultStyle(text), + stylePrefix: this.getDefaultStylePrefix() + }; + } + renderToken(token, width, nextTokenType, styleContext) { + const lines = []; + switch (token.type) { + case "heading": { + const headingLevel = token.depth; + const headingPrefix = `${"#".repeat(headingLevel)} `; + let headingStyleFn; + if (headingLevel === 1) { + headingStyleFn = (text) => this.theme.heading(this.theme.bold(this.theme.underline(text))); + } else { + headingStyleFn = (text) => this.theme.heading(this.theme.bold(text)); + } + const headingStyleContext = { + applyText: headingStyleFn, + stylePrefix: this.getStylePrefix(headingStyleFn) + }; + const headingText = this.renderInlineTokens(token.tokens || [], headingStyleContext); + const styledHeading = headingLevel >= 3 ? headingStyleFn(headingPrefix) + headingText : headingText; + lines.push(styledHeading); + if (nextTokenType && nextTokenType !== "space") { + lines.push(""); + } + break; + } + case "paragraph": { + const paragraphText = this.renderInlineTokens(token.tokens || [], styleContext); + lines.push(paragraphText); + if (nextTokenType && nextTokenType !== "list" && nextTokenType !== "space") { + lines.push(""); + } + break; + } + case "text": + lines.push(this.renderInlineTokens([token], styleContext)); + break; + case "latexBlock": { + const latexToken = token; + const rendered = !latexToken.pending && this.options.renderLatex !== false ? renderLatex(latexToken.text, { display: true }) ?? latexToken.raw.trim() : latexToken.raw.trim(); + for (const line of rendered.split("\n")) { + lines.push(this.applyDefaultStyle(line)); + } + if (nextTokenType && nextTokenType !== "space") { + lines.push(""); + } + break; + } + case "code": { + const indent = this.theme.codeBlockIndent ?? " "; + lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang || ""}`)); + if (this.theme.highlightCode) { + const highlightedLines = this.theme.highlightCode(token.text, token.lang); + for (const hlLine of highlightedLines) { + lines.push(`${indent}${hlLine}`); + } + } else { + const codeLines = token.text.split("\n"); + for (const codeLine of codeLines) { + lines.push(`${indent}${this.theme.codeBlock(codeLine)}`); + } + } + lines.push(this.theme.codeBlockBorder("```")); + if (nextTokenType && nextTokenType !== "space") { + lines.push(""); + } + break; + } + case "list": { + const listLines = this.renderList(token, 0, width, styleContext); + lines.push(...listLines); + break; + } + case "table": { + const tableLines = this.renderTable(token, width, nextTokenType, styleContext); + lines.push(...tableLines); + break; + } + case "blockquote": { + const quoteStyle = (text) => this.theme.quote(this.theme.italic(text)); + const quoteStylePrefix = this.getStylePrefix(quoteStyle); + const applyQuoteStyle = (line) => { + if (!quoteStylePrefix) { + return quoteStyle(line); + } + const lineWithReappliedStyle = line.replace(/\x1b\[0m/g, `\x1B[0m${quoteStylePrefix}`); + return quoteStyle(lineWithReappliedStyle); + }; + const quoteContentWidth = Math.max(1, width - 2); + const quoteInlineStyleContext = { + applyText: (text) => text, + stylePrefix: quoteStylePrefix + }; + const quoteTokens = token.tokens || []; + const renderedQuoteLines = []; + for (let i = 0; i < quoteTokens.length; i++) { + const quoteToken = quoteTokens[i]; + const nextQuoteToken = quoteTokens[i + 1]; + renderedQuoteLines.push( + ...this.renderToken(quoteToken, quoteContentWidth, nextQuoteToken?.type, quoteInlineStyleContext) + ); + } + while (renderedQuoteLines.length > 0 && renderedQuoteLines[renderedQuoteLines.length - 1] === "") { + renderedQuoteLines.pop(); + } + for (const quoteLine of renderedQuoteLines) { + const styledLine = applyQuoteStyle(quoteLine); + const wrappedLines = wrapTextWithAnsi(styledLine, quoteContentWidth); + for (const wrappedLine of wrappedLines) { + lines.push(this.theme.quoteBorder("\u2502 ") + wrappedLine); + } + } + if (nextTokenType && nextTokenType !== "space") { + lines.push(""); + } + break; + } + case "hr": + lines.push(this.theme.hr("\u2500".repeat(Math.min(width, 80)))); + if (nextTokenType && nextTokenType !== "space") { + lines.push(""); + } + break; + case "html": + if ("raw" in token && typeof token.raw === "string") { + lines.push(this.applyDefaultStyle(token.raw.trim())); + } + break; + case "space": + lines.push(""); + break; + default: + if ("text" in token && typeof token.text === "string") { + lines.push(token.text); + } + } + return lines; + } + renderInlineTokens(tokens, styleContext) { + let result = ""; + const resolvedStyleContext = styleContext ?? this.getDefaultInlineStyleContext(); + const { applyText, stylePrefix } = resolvedStyleContext; + const applyTextWithNewlines = (text) => { + const segments = text.split("\n"); + return segments.map((segment) => applyText(segment)).join("\n"); + }; + for (const token of tokens) { + switch (token.type) { + case "latex": { + const latexToken = token; + const rendered = !latexToken.pending && this.options.renderLatex !== false ? renderLatex(latexToken.text) ?? latexToken.raw : latexToken.raw; + result += applyTextWithNewlines(rendered); + break; + } + case "escape": + result += applyTextWithNewlines(this.options.preserveBackslashEscapes ? token.raw : token.text); + break; + case "text": + if (token.tokens && token.tokens.length > 0) { + result += this.renderInlineTokens(token.tokens, resolvedStyleContext); + } else { + result += applyTextWithNewlines(token.text); + } + break; + case "paragraph": + result += this.renderInlineTokens(token.tokens || [], resolvedStyleContext); + break; + case "strong": { + const boldContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext); + result += this.theme.bold(boldContent) + stylePrefix; + break; + } + case "em": { + const italicContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext); + result += this.theme.italic(italicContent) + stylePrefix; + break; + } + case "codespan": + result += this.theme.code(token.text) + stylePrefix; + break; + case "link": { + const linkText = this.renderInlineTokens(token.tokens || [], resolvedStyleContext); + const styledLink = this.theme.link(this.theme.underline(linkText)); + if (getCapabilities().hyperlinks) { + result += hyperlink(styledLink, token.href) + stylePrefix; + } else { + const hrefForComparison = token.href.startsWith("mailto:") ? token.href.slice(7) : token.href; + if (token.text === token.href || token.text === hrefForComparison) { + result += styledLink + stylePrefix; + } else { + result += styledLink + this.theme.linkUrl(` (${token.href})`) + stylePrefix; + } + } + break; + } + case "br": + result += "\n"; + break; + case "del": { + const delContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext); + result += this.theme.strikethrough(delContent) + stylePrefix; + break; + } + case "html": + if ("raw" in token && typeof token.raw === "string") { + result += applyTextWithNewlines(token.raw); + } + break; + default: + if ("text" in token && typeof token.text === "string") { + result += applyTextWithNewlines(token.text); + } + } + } + while (stylePrefix && result.endsWith(stylePrefix)) { + result = result.slice(0, -stylePrefix.length); + } + return result; + } + getOrderedListMarker(item) { + const match = /^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(item.raw); + return match ? `${match[1]} ` : void 0; + } + getUnorderedListMarker(item) { + const match = /^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(item.raw); + return match ? `${match[1]} ` : void 0; + } + /** + * Render a list with proper nesting support + */ + renderList(token, depth, width, styleContext) { + const lines = []; + const indent = " ".repeat(depth); + const startNumber = typeof token.start === "number" ? token.start : 1; + for (let i = 0; i < token.items.length; i++) { + const item = token.items[i]; + const isLastItem = i === token.items.length - 1; + const bullet = token.ordered ? this.options.preserveOrderedListMarkers ? this.getOrderedListMarker(item) ?? `${startNumber + i}. ` : `${startNumber + i}. ` : this.options.preserveOrderedListMarkers ? this.getUnorderedListMarker(item) ?? "- " : "- "; + const taskMarker = item.task ? `[${item.checked ? "x" : " "}] ` : ""; + const marker = bullet + taskMarker; + const firstPrefix = indent + this.theme.listBullet(marker); + const continuationPrefix = indent + " ".repeat(visibleWidth(marker)); + const itemWidth = Math.max(1, width - visibleWidth(firstPrefix)); + let renderedAnyLine = false; + for (const itemToken of item.tokens) { + if (itemToken.type === "list") { + lines.push(...this.renderList(itemToken, depth + 1, width, styleContext)); + renderedAnyLine = true; + continue; + } + const itemLines = this.renderToken(itemToken, itemWidth, void 0, styleContext); + for (const line of itemLines) { + for (const wrappedLine of wrapTextWithAnsi(line, itemWidth)) { + const linePrefix = renderedAnyLine ? continuationPrefix : firstPrefix; + lines.push(linePrefix + wrappedLine); + renderedAnyLine = true; + } + } + } + if (!renderedAnyLine) { + lines.push(firstPrefix); + } + if (token.loose && !isLastItem) { + lines.push(""); + } + } + return lines; + } + /** + * Get the visible width of the longest word in a string. + */ + getLongestWordWidth(text, maxWidth) { + const words = text.split(/\s+/).filter((word) => word.length > 0); + let longest = 0; + for (const word of words) { + longest = Math.max(longest, visibleWidth(word)); + } + if (maxWidth === void 0) { + return longest; + } + return Math.min(longest, maxWidth); + } + /** + * Wrap a table cell to fit into a column. + * + * Delegates to wrapTextWithAnsi() so ANSI codes + long tokens are handled + * consistently with the rest of the renderer. + */ + wrapCellText(text, maxWidth, stylePrefix = "") { + const lines = wrapTextWithAnsi(text, Math.max(1, maxWidth)); + return lines.map((line, index) => { + const styleReset = index < lines.length - 1 ? "\x1B[22;23;24;25;27;28;29;39m" : ""; + return `${line}${styleReset}${stylePrefix}`; + }); + } + /** + * Render a table with width-aware cell wrapping. + * Cells that don't fit are wrapped to multiple lines. + */ + renderTable(token, availableWidth, nextTokenType, styleContext) { + const lines = []; + const numCols = token.header.length; + if (numCols === 0) { + return lines; + } + const borderOverhead = 3 * numCols + 1; + const availableForCells = availableWidth - borderOverhead; + if (availableForCells < numCols) { + const fallbackLines = token.raw ? wrapTextWithAnsi(token.raw, availableWidth) : []; + if (nextTokenType && nextTokenType !== "space") { + fallbackLines.push(""); + } + return fallbackLines; + } + const maxUnbrokenWordWidth = 30; + const naturalWidths = []; + const minWordWidths = []; + for (let i = 0; i < numCols; i++) { + const headerText = this.renderInlineTokens(token.header[i].tokens || [], styleContext); + naturalWidths[i] = visibleWidth(headerText); + minWordWidths[i] = Math.max(1, this.getLongestWordWidth(headerText, maxUnbrokenWordWidth)); + } + for (const row of token.rows) { + for (let i = 0; i < row.length; i++) { + const cellText = this.renderInlineTokens(row[i].tokens || [], styleContext); + naturalWidths[i] = Math.max(naturalWidths[i] || 0, visibleWidth(cellText)); + minWordWidths[i] = Math.max( + minWordWidths[i] || 1, + this.getLongestWordWidth(cellText, maxUnbrokenWordWidth) + ); + } + } + let minColumnWidths = minWordWidths; + let minCellsWidth = minColumnWidths.reduce((a, b2) => a + b2, 0); + if (minCellsWidth > availableForCells) { + minColumnWidths = new Array(numCols).fill(1); + const remaining = availableForCells - numCols; + if (remaining > 0) { + const totalWeight = minWordWidths.reduce((total, width) => total + Math.max(0, width - 1), 0); + const growth = minWordWidths.map((width) => { + const weight = Math.max(0, width - 1); + return totalWeight > 0 ? Math.floor(weight / totalWeight * remaining) : 0; + }); + for (let i = 0; i < numCols; i++) { + minColumnWidths[i] += growth[i] ?? 0; + } + const allocated = growth.reduce((total, width) => total + width, 0); + let leftover = remaining - allocated; + for (let i = 0; leftover > 0 && i < numCols; i++) { + minColumnWidths[i]++; + leftover--; + } + } + minCellsWidth = minColumnWidths.reduce((a, b2) => a + b2, 0); + } + const totalNaturalWidth = naturalWidths.reduce((a, b2) => a + b2, 0) + borderOverhead; + let columnWidths; + if (totalNaturalWidth <= availableWidth) { + columnWidths = naturalWidths.map((width, index) => Math.max(width, minColumnWidths[index])); + } else { + const totalGrowPotential = naturalWidths.reduce((total, width, index) => { + return total + Math.max(0, width - minColumnWidths[index]); + }, 0); + const extraWidth = Math.max(0, availableForCells - minCellsWidth); + columnWidths = minColumnWidths.map((minWidth, index) => { + const naturalWidth = naturalWidths[index]; + const minWidthDelta = Math.max(0, naturalWidth - minWidth); + let grow = 0; + if (totalGrowPotential > 0) { + grow = Math.floor(minWidthDelta / totalGrowPotential * extraWidth); + } + return minWidth + grow; + }); + const allocated = columnWidths.reduce((a, b2) => a + b2, 0); + let remaining = availableForCells - allocated; + while (remaining > 0) { + let grew = false; + for (let i = 0; i < numCols && remaining > 0; i++) { + if (columnWidths[i] < naturalWidths[i]) { + columnWidths[i]++; + remaining--; + grew = true; + } + } + if (!grew) { + break; + } + } + } + const topBorderCells = columnWidths.map((w2) => "\u2500".repeat(w2)); + lines.push(`\u250C\u2500${topBorderCells.join("\u2500\u252C\u2500")}\u2500\u2510`); + const headerCellLines = token.header.map((cell, i) => { + const text = this.renderInlineTokens(cell.tokens || [], styleContext); + return this.wrapCellText(text, columnWidths[i], styleContext?.stylePrefix); + }); + const headerLineCount = Math.max(...headerCellLines.map((c) => c.length)); + for (let lineIdx = 0; lineIdx < headerLineCount; lineIdx++) { + const rowParts = headerCellLines.map((cellLines, colIdx) => { + const text = cellLines[lineIdx] || ""; + const padded = text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text))); + return this.theme.bold(padded); + }); + lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`); + } + const separatorCells = columnWidths.map((w2) => "\u2500".repeat(w2)); + const separatorLine = `\u251C\u2500${separatorCells.join("\u2500\u253C\u2500")}\u2500\u2524`; + lines.push(separatorLine); + for (let rowIndex = 0; rowIndex < token.rows.length; rowIndex++) { + const row = token.rows[rowIndex]; + const rowCellLines = row.map((cell, i) => { + const text = this.renderInlineTokens(cell.tokens || [], styleContext); + return this.wrapCellText(text, columnWidths[i], styleContext?.stylePrefix); + }); + const rowLineCount = Math.max(...rowCellLines.map((c) => c.length)); + for (let lineIdx = 0; lineIdx < rowLineCount; lineIdx++) { + const rowParts = rowCellLines.map((cellLines, colIdx) => { + const text = cellLines[lineIdx] || ""; + return text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text))); + }); + lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`); + } + if (rowIndex < token.rows.length - 1) { + lines.push(separatorLine); + } + } + const bottomBorderCells = columnWidths.map((w2) => "\u2500".repeat(w2)); + lines.push(`\u2514\u2500${bottomBorderCells.join("\u2500\u2534\u2500")}\u2500\u2518`); + if (nextTokenType && nextTokenType !== "space") { + lines.push(""); + } + return lines; + } + }; + + // packages/tui/bundle-bench.ts + var sty = (n) => (t) => `\x1B[${n}m${t}\x1B[0m`; + function bench(nPoints, count, reps) { + const theme = { + heading: sty(36), + bold: sty(1), + italic: sty(3), + code: sty(33), + codeBlock: sty(33), + codeBlockBorder: sty(33), + quote: sty(3), + quoteBorder: sty(3), + hr: sty(3), + listBullet: sty(1), + link: sty(34), + linkUrl: sty(34), + strikethrough: sty(3), + underline: sty(1) + }; + let text = "## Section\n\nHere is an explanation with **bold** and `inline code` plus a [link](http://x).\n\n"; + for (let i = 0; i < nPoints; i++) text += `- point ${i} with some trailing prose that wraps at narrow widths +`; + text += "\n```ts\nconst x = 1;\n```\n"; + const comps = Array.from({ length: count }, () => new Markdown(text, 0, 0, theme)); + for (let i = 0; i < 20; i++) comps[0].render(40 + i % 20); + const t0 = Date.now(); + for (let r = 0; r < reps; r++) for (const c of comps) c.render(40 + r % 60); + return (Date.now() - t0) / reps; + } + return __toCommonJS(bundle_bench_exports); +})(); + +globalThis.__bench = __m.bench; \ No newline at end of file diff --git a/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/membrane.ts b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/membrane.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8a2f211e331f546f90cd0a1072b02de5f134ede --- /dev/null +++ b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/membrane.ts @@ -0,0 +1,197 @@ +import ivm from "isolated-vm"; + +/** + * A membrane between the host realm and an isolated-vm isolate. + * + * ── The safety argument, which is structural, not a convention ────────────── + * + * isolated-vm CAN be used unsafely. The documented footgun is handing the guest + * a live handle to a host object — via `derefInto()`, or by returning a + * `Reference` from a host call — after which the guest can walk that object's + * prototype chain into the host realm. + * + * This membrane makes that impossible by construction rather than by care: + * + * 1. `encode()` is the ONLY way a host value reaches the guest, and it is + * `JSON.stringify` with a replacer. Its output is a string. A string + * cannot carry a reference. + * 2. Host callables do not cross. They are replaced by an integer id into + * `hostTable`, which lives entirely host-side. The guest receives a number. + * 3. Exactly ONE `Reference` is ever given to the guest — `__invokeRef`, the + * single call-in point — and its `deref()` throws cross-isolate ("Cannot + * dereference this from current isolate"). Its `derefInto()` yields an + * inert `Dereference` marker: not callable, no host globals. + * 4. `derefInto()` is used exactly once, on the guest's OWN global. No host + * object is ever an argument to it. + * + * The consequence: the guest's entire view of the host is `{ number, string }`. + * There is no object graph to walk, so there is nothing to walk it into. This is + * the same property the QuickJS membrane has, and it is why the choice between + * them is about performance and packaging rather than about safety. + * + * Verified by `src/escape-audit.ts`. + */ +export async function createCompartment({ memoryLimit = 256 } = {}) { + const isolate = new ivm.Isolate({ memoryLimit }); + const ctx = await isolate.createContext(); + await ctx.global.set("global", ctx.global.derefInto()); // guest's own global only + + const hostTable = new Map(); + let nextHostId = 1; + const exposeHost = (o) => { const id = nextHostId++; hostTable.set(id, o); return id; }; + + const guestProxies = new Map(); + const finalizer = new FinalizationRegistry((id) => { + guestProxies.delete(id); + if (!released) ctx.evalSync(`delete __refs[${JSON.stringify(String(id))}]`); + }); + let released = false; + + // Async: `applySync` is synchronous, so a host Promise cannot itself cross. + // Instead the host returns a token, the guest builds a real Promise against + // it, and the host settles that Promise by calling back in when it resolves. + let nextPending = 1; + function encodePending(promise) { + const token = nextPending++; + promise.then( + (v) => settle(token, true, v === undefined ? "" : encode(v)), + (e) => settle(token, false, JSON.stringify(String(e?.message ?? e))), + ); + return JSON.stringify({ __pending: token }); + } + function settle(token, ok, json) { + if (released) return; + ctx.evalSync(`__settle(${token}, ${ok}, ${JSON.stringify(json)})`); + } + + function encode(v) { + if (v && typeof v.then === "function") return encodePending(v); + return JSON.stringify(v, (_k, val) => { + if (typeof val === "function") return { __ref: exposeHost(val) }; + if (val && typeof val === "object" && !Array.isArray(val) && hasMethods(val)) + return { __obj: exposeHost(val), keys: methodNames(val) }; + return val; + }); + } + const decode = (json) => JSON.parse(json, (_k, v) => reviveGuest(v)); + + function intern(id, build) { + const hit = guestProxies.get(id)?.deref(); + if (hit !== undefined) return hit; + const p = build(); + guestProxies.set(id, new WeakRef(p)); + finalizer.register(p, id); + return p; + } + function reviveGuest(v) { + if (!v || typeof v !== "object") return v; + if (typeof v.__guestRef === "number") { const r = v.__guestRef; return intern(r, () => (...a) => callGuestRef(r, a)); } + if (typeof v.__guestObj === "number") { + const r = v.__guestObj; + return intern(r, () => { const o = {}; for (const k of v.keys) o[k] = (...a) => callGuestRef(r, [k, a]); return o; }); + } + return v; + } + + function callGuestRef(ref, args, timeout = 5000) { + const out = ctx.evalSync( + `__refs[${JSON.stringify(String(ref))}](${JSON.stringify(JSON.stringify(args))})`, + { timeout }, + ); + return out === "" || out === undefined ? undefined : decode(out); + } + + // The single host entry point. A Reference, applied synchronously with copied + // arguments — no host object graph is ever exposed. + const invoke = new ivm.Reference((idJson, pathJson, argsJson) => { + const path = JSON.parse(pathJson); + let target = hostTable.get(JSON.parse(idJson)); + for (let i = 0; i < path.length - 1; i++) target = target[path[i]]; + const result = path.length ? target[path[path.length - 1]](...decode(argsJson)) : target(...decode(argsJson)); + return result === undefined ? "" : encode(result); + }); + await ctx.global.set("__invokeRef", invoke); + + await ctx.eval(` + globalThis.__refs = {}; globalThis.__nextRef = 1; + globalThis.__outgoing = new WeakMap(); + globalThis.__methodNames = function (o) { + var out = [], p = o; + while (p && p !== Object.prototype) { + for (const k of Object.getOwnPropertyNames(p)) + if (k !== "constructor" && typeof o[k] === "function" && out.indexOf(k) < 0) out.push(k); + p = Object.getPrototypeOf(p); + } + return out; + }; + globalThis.__mkRef = function (fn) { + var prior = __outgoing.get(fn); if (prior !== undefined) return { __guestRef: prior }; + var id = __nextRef++; __outgoing.set(fn, id); + __refs[String(id)] = function (j) { var r = fn.apply(null, JSON.parse(j)); return r === undefined ? "" : __encode(r); }; + return { __guestRef: id }; + }; + globalThis.__mkObjRef = function (obj) { + var prior = __outgoing.get(obj); + if (prior !== undefined) return { __guestObj: prior, keys: __methodNames(obj) }; + var id = __nextRef++; __outgoing.set(obj, id); + __refs[String(id)] = function (j) { var c = JSON.parse(j); var r = obj[c[0]].apply(obj, c[1]); return r === undefined ? "" : __encode(r); }; + return { __guestObj: id, keys: __methodNames(obj) }; + }; + globalThis.__encode = function (v) { + return JSON.stringify(v, function (k, val) { + if (typeof val === "function") return __mkRef(val); + if (val && typeof val === "object" && !Array.isArray(val) && __methodNames(val).length) return __mkObjRef(val); + return val; + }); + }; + globalThis.__pending = {}; + globalThis.__settle = function (token, ok, json) { + var d = __pending[token]; + if (!d) return; + delete __pending[token]; + var value = json === "" ? undefined : JSON.parse(json); + ok ? d.resolve(__revive(value)) : d.reject(new Error(value)); + }; + globalThis.__revive = function (v) { + if (v && typeof v === "object" && typeof v.__pending === "number") { + var token = v.__pending; + return new Promise(function (res, rej) { __pending[token] = { resolve: res, reject: rej }; }); + } + if (v && typeof v === "object") { + if (typeof v.__ref === "number") return __wrap(v.__ref, []); + if (typeof v.__obj === "number") return __wrap(v.__obj, []); + for (var k in v) v[k] = __revive(v[k]); + } + return v; + }; + globalThis.__wrap = function (id, path) { + return new Proxy(function () {}, { + get: function (t, prop) { + if (typeof prop !== "string") return undefined; + if (prop === "then" || prop === "toJSON" || prop === "inspect") return undefined; + if (prop === "length" || prop === "name") return t[prop]; + return __wrap(id, path.concat([prop])); + }, + apply: function (_t, _this, args) { + var out = __invokeRef.applySync(undefined, [JSON.stringify(id), JSON.stringify(path), __encode(args)]); + return out === "" ? undefined : __revive(JSON.parse(out)); + }, + }); + }; + `); + + return { + async endow(name, obj) { await ctx.eval(`globalThis[${JSON.stringify(name)}] = __wrap(${exposeHost(obj)}, []);`); }, + load: (src, timeout = 30000) => ctx.evalSync(src, { timeout }), + debugRefCount: () => ({ hostTable: hostTable.size, guestRefs: ctx.evalSync(`Object.keys(__refs).length`) }), + dispose() { + released = true; + // An isolate that hit its memory limit is already disposed, and calling + // dispose() again throws "Isolate is already disposed". + try { isolate.dispose(); } catch { /* already gone */ } + }, + }; +} +const RESERVED = new Set(["constructor"]); +const methodNames = (o) => { const out = []; for (let p = o; p && p !== Object.prototype; p = Object.getPrototypeOf(p)) for (const k of Object.getOwnPropertyNames(p)) if (!RESERVED.has(k) && typeof o[k] === "function" && !out.includes(k)) out.push(k); return out; }; +const hasMethods = (o) => methodNames(o).length > 0; diff --git a/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/property-test.ts b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/property-test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a9574edaf1cb5dea6f925dc763559b8a8678dea2 --- /dev/null +++ b/packages/agent/docs/mobile-handoff/02-plugins/02-sandbox/src/property-test.ts @@ -0,0 +1,137 @@ +/** + * Property tests for the membrane. + * + * Every bug found by hand while building it failed SILENTLY — wrong output, no + * throw. That is the worst possible failure mode for a boundary, and the reason + * these exist. Run with: node --experimental-strip-types --expose-gc property-test.ts + */ +import { createCompartment } from "./membrane.ts"; + +let pass = 0; +const failures: string[] = []; +const check = (name: string, ok: boolean, detail = "") => { + if (ok) pass++; + else failures.push(`${name}${detail ? ` — ${detail}` : ""}`); +}; + +/** Random JsonValue. The membrane claims to round-trip exactly these. */ +function randomJson(depth = 0): unknown { + const r = Math.random(); + if (depth > 3 || r < 0.25) return Math.floor(Math.random() * 1000) - 500; + if (r < 0.35) return Math.random() * 1e6 - 5e5; + if (r < 0.45) return Math.random() < 0.5; + if (r < 0.5) return null; + if (r < 0.65) { + const alphabet = ['a', 'z', '0', ' ', '"', '\\', '\n', '\u00e9', '\u4e2d', '\u{1f600}']; + let s = ""; + const n = Math.floor(Math.random() * 12); + for (let i = 0; i < n; i++) s += alphabet[Math.floor(Math.random() * alphabet.length)]; + return s; + } + if (r < 0.8) return Array.from({ length: Math.floor(Math.random() * 5) }, () => randomJson(depth + 1)); + const o: Record = {}; + for (const k of ["a", "b", "c", "d", "__proto__x", "0", "length"]) { + if (Math.random() < 0.5) o[k] = randomJson(depth + 1); + } + return o; +} + +const c = await createCompartment(); + +// ── 1. Value round-trip, both directions ────────────────────────────────── +const echoed: unknown[] = []; +await c.endow("__h", { echo: (v: unknown) => v, sink: (v: unknown) => { echoed.push(v); } }); +c.load(`globalThis.roundTrip = function (v) { return __h.echo(v); }; + globalThis.sendBack = function (v) { __h.sink(v); };`); + +for (let i = 0; i < 400; i++) { + const value = randomJson(); + const json = JSON.stringify(value); + if (json === undefined) continue; + // host -> guest -> host + c.load(`globalThis.__t = roundTrip(${json});`); + c.load(`sendBack(__t);`); + const got = echoed.pop(); + check("value round-trip", JSON.stringify(got) === json, `${json} became ${JSON.stringify(got)}`); +} + +// ── 2. Identity: the same guest object must map to the same host proxy ──── +const seen: unknown[] = []; +await c.endow("__id", { take: (o: unknown) => { seen.push(o); } }); +c.load(`globalThis.shared = { m: function () { return 1; } }; + globalThis.sendShared = function () { __id.take(shared); __id.take(shared); };`); +c.load(`sendShared();`); +check("identity preserved across crossings", seen[0] === seen[1]); +c.load(`sendShared();`); +check("identity stable across separate calls", seen[0] === seen[2]); + +// ── 3. Callables survive and remain callable ────────────────────────────── +let held: any; +await c.endow("__f", { keep: (fn: unknown) => { held = fn; } }); +c.load(`__f.keep(function (a, b) { return a + b; });`); +check("guest function callable from host", held(2, 3) === 5, `got ${held?.(2, 3)}`); + +// ── 4. Errors cross with name and message ───────────────────────────────── +c.load(`__f.keep(function () { throw new TypeError("boom"); });`); +let msg = ""; +try { held(); } catch (e: any) { msg = e.message; } +check("guest throw reaches host", msg.includes("boom"), `got "${msg}"`); + +// ── 5. Reference release: crossings must not leak ───────────────────────── +await c.endow("__l", { drop: (_fn: unknown) => {} }); +c.load(`globalThis.churn = function () { for (var i = 0; i < 500; i++) __l.drop(function () { return i; }); };`); +c.load(`churn();`); +const beforeGc = c.debugRefCount().guestRefs; +globalThis.gc?.(); +await new Promise((r) => setTimeout(r, 60)); +globalThis.gc?.(); +await new Promise((r) => setTimeout(r, 60)); +const afterGc = c.debugRefCount().guestRefs; +check("dropped references are released", afterGc < beforeGc / 2, `${beforeGc} -> ${afterGc}`); + +// ── 5b. Prototype pollution must not cross ──────────────────────────────── +// JSON.parse is safe (it makes __proto__ an own property), but a membrane that +// assigns parsed keys onto a fresh object is not. +const before = ({} as any).polluted; +c.load(`__h.sink(JSON.parse('{"__proto__":{"polluted":true}}'));`); +check("guest cannot pollute host Object.prototype", ({} as any).polluted === before); +await c.endow("__p", { give: () => JSON.parse('{"__proto__":{"hostPolluted":true}}') }); +await c.endow("__q", { show: (v: string) => check("host cannot pollute guest prototype", v === "undefined", v) }); +c.load(`var got = __p.give(); __q.show(String(({}).hostPolluted));`); + +// ── 6. Interrupt budget, and the VM survives it ─────────────────────────── +// Direct: the budget on this call bounds it. +{ + const t0 = Date.now(); + try { c.load(`while (true) {}`, 100); } catch { /* expected */ } + check("runaway guest code is interrupted", Date.now() - t0 < 600, `took ${Date.now() - t0}ms`); +} +// Re-entrant: a guest function invoked BY THE HOST gets `callGuestRef`'s own +// budget, not the outer one. Budgets do not nest — see README "Limitations". +c.load(`globalThis.spin = function () { while (true) {} };`); +await c.endow("__s", { run: (fn: any) => { try { fn(); return "returned"; } catch { return "threw"; } } }); +{ + const t0 = Date.now(); + try { c.load(`globalThis.__x = __s.run(spin);`, 50); } catch { /* expected */ } + const took = Date.now() - t0; + check("re-entrant call uses its OWN budget, not the outer one", took > 1000, + `took ${took}ms — if this is now <1s the nesting behaviour changed`); +} +c.load(`globalThis.__alive = 1 + 1;`); +check("VM usable after an interrupt", true); + +// ── 7. Async, and clean teardown with a pending promise ─────────────────── +await c.endow("__a", { never: () => new Promise(() => {}), soon: () => Promise.resolve("v") }); +c.load(`globalThis.out = null; __a.soon().then(function (v) { out = v; });`); +await new Promise((r) => setTimeout(r, 30)); +await c.endow("__o", { show: (v: string) => check("async host result reaches guest", v === '"v"', v) }); +c.load(`__o.show(JSON.stringify(out));`); +c.load(`__a.never().then(function () {}, function () {});`); // deliberately unsettled + +let disposeOk = true; +try { c.dispose(); } catch { disposeOk = false; } +check("dispose with a pending promise does not crash", disposeOk); + +console.log(`\n${pass} passed, ${failures.length} failed`); +for (const f of failures.slice(0, 10)) console.log(" FAIL", f); +process.exit(failures.length === 0 ? 0 : 1); diff --git a/packages/agent/test/harness/adaptive-publisher.test.ts b/packages/agent/test/harness/adaptive-publisher.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6f13efc85fac1bd89a4e2749cc320e3845ead74 --- /dev/null +++ b/packages/agent/test/harness/adaptive-publisher.test.ts @@ -0,0 +1,76 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { AdaptivePublisher } from "../../src/harness/utils/adaptive-publisher.ts"; + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("AdaptivePublisher", () => { + it("bounds event count and spaces large publications by encoded size", () => { + vi.useFakeTimers(); + vi.setSystemTime(0); + let value = "a"; + const updates: string[] = []; + const publisher = new AdaptivePublisher({ + snapshot: () => value, + update: (_previous, current) => current, + measure: (update) => update.length, + publish: (update) => updates.push(update), + onError: (error) => { + throw error; + }, + minIntervalMs: 100, + targetBytesPerSecond: 100, + }); + + publisher.markDirty(); + value = "x".repeat(100); + publisher.markDirty(); + vi.advanceTimersByTime(100); + expect(updates).toEqual(["a", "x".repeat(100)]); + + value = "held"; + publisher.markDirty(); + vi.advanceTimersByTime(999); + expect(updates).toHaveLength(2); + vi.advanceTimersByTime(1); + expect(updates).toEqual(["a", "x".repeat(100), "held"]); + }); + + it("commits its baseline before a consumer throws", () => { + vi.useFakeTimers(); + vi.setSystemTime(0); + let value = "a"; + const updates: Array<{ previous: string | undefined; current: string }> = []; + let throwAfterApply = false; + const publisher = new AdaptivePublisher({ + snapshot: () => value, + update: (previous, current) => ({ previous, current }), + measure: () => 1, + publish: (update) => { + updates.push(update); + if (throwAfterApply) throw new Error("consumer failed after apply"); + }, + onError: () => {}, + minIntervalMs: 100, + targetBytesPerSecond: 100, + }); + + publisher.markDirty(); + vi.advanceTimersByTime(100); + value = "ab"; + throwAfterApply = true; + expect(() => publisher.markDirty()).toThrow("consumer failed after apply"); + publisher.flush(true); + expect(updates).toEqual([ + { previous: undefined, current: "a" }, + { previous: "a", current: "ab" }, + ]); + + throwAfterApply = false; + vi.advanceTimersByTime(100); + value = "abc"; + publisher.markDirty(); + expect(updates.at(-1)).toEqual({ previous: "ab", current: "abc" }); + }); +}); diff --git a/packages/agent/test/harness/branch-summarization.test.ts b/packages/agent/test/harness/branch-summarization.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e8a6a5ca08111796ccbb0cb8da287b621066d08 --- /dev/null +++ b/packages/agent/test/harness/branch-summarization.test.ts @@ -0,0 +1,71 @@ +import type { AgentMessage } from "@earendil-works/pi-agent-core"; +import { describe, expect, it } from "vitest"; +import { collectEntriesForBranchSummary } from "../../src/harness/compaction/branch-summarization.ts"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import type { Branch, Entry, MessageEntry, Session } from "../../src/harness/session/index.ts"; + +function message(text: string): AgentMessage { + return { role: "user", content: [{ type: "text", text }], timestamp: 1 }; +} + +function messageEntry(id: string, parentId: string | null, text: string, seq: number): MessageEntry { + return { type: "message", id, parentId, message: message(text), seq, timestamp: seq }; +} + +function branchReader(entries: Entry[]): { + branch: Pick; + session: Pick; +} { + const byId = new Map(entries.map((entry) => [entry.id, entry])); + return { + session: { + async getEntry(id) { + return byId.get(id); + }, + }, + branch: { + async findEntries(query = {}) { + const path: Entry[] = []; + let currentId = query.start ?? null; + while (currentId !== null) { + const entry = byId.get(currentId); + if (!entry) throw new Error(`Unknown entry ${currentId}`); + path.push(entry); + currentId = entry.parentId; + } + return path; + }, + }, + }; +} + +describe("v4 branch summarization", () => { + it("collects the abandoned side of a branch in chronological order", async () => { + const root = messageEntry("root", null, "root", 1); + const common = messageEntry("common", root.id, "common", 2); + const abandoned1 = messageEntry("abandoned-1", common.id, "abandoned 1", 3); + const abandoned2 = messageEntry("abandoned-2", abandoned1.id, "abandoned 2", 4); + const target = messageEntry("target", common.id, "target", 5); + const { branch, session } = branchReader([root, common, abandoned1, abandoned2, target]); + + const result = await collectEntriesForBranchSummary( + branch, + session, + abandoned2.id, + target.id, + BACKGROUND_CONTEXT, + ); + expect(result.commonAncestorId).toBe(common.id); + expect(result.entries.map((entry) => entry.id)).toEqual([abandoned1.id, abandoned2.id]); + expect(result.entries.some((entry) => entry.id === root.id)).toBe(false); + }); + + it("returns no entries when there was no previous leaf", async () => { + const target = messageEntry("target", null, "target", 1); + const { branch, session } = branchReader([target]); + expect(await collectEntriesForBranchSummary(branch, session, null, target.id, BACKGROUND_CONTEXT)).toEqual({ + entries: [], + commonAncestorId: null, + }); + }); +}); diff --git a/packages/agent/test/harness/branch.test.ts b/packages/agent/test/harness/branch.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..dbe7f922c388235af9f527cad2d718bdf8c4c828 --- /dev/null +++ b/packages/agent/test/harness/branch.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import { insertEntry } from "../../src/harness/session/commit.ts"; +import { MemoryStorage } from "../../src/harness/session/memory.ts"; +import { SessionPendingAssistantMessageError, StorageBackedSession } from "../../src/harness/session/session.ts"; +import { branchTip, setValue } from "../../src/harness/session/values.ts"; + +function createSession(): StorageBackedSession { + return new StorageBackedSession( + { id: "session", createdAt: 1, storageVersion: 1 }, + new MemoryStorage({ now: () => 10 }), + { idGenerator: { next: () => `entry-${nextId++}` } }, + ); +} + +let nextId = 1; + +describe("Branch", () => { + it("is absent until explicitly created and Session has no implicit Branch surface", async () => { + const session = createSession(); + expect(await session.branch("main", BACKGROUND_CONTEXT)).toBeUndefined(); + expect("getTipId" in session).toBe(false); + expect("appendMessage" in session).toBe(false); + expect("findEntriesOnBranch" in session).toBe(false); + + const branch = await session.createBranch("main", null, BACKGROUND_CONTEXT); + expect(branch.name).toBe("main"); + expect(await branch.getTipId(BACKGROUND_CONTEXT)).toBeNull(); + await session.close(BACKGROUND_CONTEXT); + }); + + it("directly appends immutable entries and advances only its own tip", async () => { + nextId = 1; + const session = createSession(); + const main = await session.createBranch("main", null, BACKGROUND_CONTEXT); + const review = await session.createBranch("review", null, BACKGROUND_CONTEXT); + const message = { role: "user" as const, content: "hello", timestamp: 1 }; + + const messageId = await main.appendMessage(message, BACKGROUND_CONTEXT); + const customId = await main.appendCustomEntry("note", { ok: true }, BACKGROUND_CONTEXT); + const reviewId = await review.appendCustomEntry("review", undefined, BACKGROUND_CONTEXT); + + expect(await main.getTipId(BACKGROUND_CONTEXT)).toBe(customId); + expect(await review.getTipId(BACKGROUND_CONTEXT)).toBe(reviewId); + expect((await main.findEntries({ order: "oldestFirst" }, BACKGROUND_CONTEXT)).map(({ id }) => id)).toEqual([ + messageId, + customId, + ]); + expect(await main.findEntry({ type: "message" }, BACKGROUND_CONTEXT)).toMatchObject({ + id: messageId, + type: "message", + message, + }); + await session.close(BACKGROUND_CONTEXT); + }); + + it("supports explicit starts without moving the Branch tip", async () => { + const session = createSession(); + await session.mutate( + (mutator) => + mutator.commit( + [ + insertEntry({ id: "root", parentId: null, type: "custom", customType: "root" }), + insertEntry({ id: "left", parentId: "root", type: "custom", customType: "left" }), + insertEntry({ id: "right", parentId: "root", type: "custom", customType: "right" }), + setValue(branchTip("main"), "left"), + ], + BACKGROUND_CONTEXT, + ), + BACKGROUND_CONTEXT, + ); + const branch = await session.branch("main", BACKGROUND_CONTEXT); + if (branch === undefined) throw new Error("Expected main Branch"); + + expect( + (await branch.findEntries({ start: "right", order: "oldestFirst" }, BACKGROUND_CONTEXT)).map(({ id }) => id), + ).toEqual(["root", "right"]); + expect(await branch.getTipId(BACKGROUND_CONTEXT)).toBe("left"); + await session.close(BACKGROUND_CONTEXT); + }); + + it("rejects pending assistant messages before committing", async () => { + const session = createSession(); + const branch = await session.createBranch("main", null, BACKGROUND_CONTEXT); + await expect( + branch.appendMessage( + { + role: "assistant", + content: [], + api: "test", + provider: "test", + model: "test", + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "pending", + timestamp: 1, + }, + BACKGROUND_CONTEXT, + ), + ).rejects.toBeInstanceOf(SessionPendingAssistantMessageError); + expect(await branch.getTipId(BACKGROUND_CONTEXT)).toBeNull(); + await session.close(BACKGROUND_CONTEXT); + }); +}); diff --git a/packages/agent/test/harness/compaction.test.ts b/packages/agent/test/harness/compaction.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d39e5228600cf9f212cae01b811b685a126634d0 --- /dev/null +++ b/packages/agent/test/harness/compaction.test.ts @@ -0,0 +1,827 @@ +import { + type Api, + type AssistantMessage, + createModels, + type FauxProviderHandle, + fauxAssistantMessage, + fauxProvider, + type Message, + type Model, + type Models, + type Usage, +} from "@earendil-works/pi-ai"; +import { beforeEach, describe, expect, it } from "vitest"; +import { + type CompactionPreparation, + type CompactionSettings, + calculateContextTokens, + compact, + DEFAULT_COMPACTION_SETTINGS, + estimateContextTokens, + estimateTokens, + findCutPoint, + findTurnStartIndex, + generateSummary, + generateSummaryWithUsage, + getLastAssistantUsage, + prepareCompaction, + serializeConversation, + shouldCompact, +} from "../../src/harness/compaction/compaction.ts"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import { buildSessionContext } from "../../src/harness/session/context.ts"; +import type { + BranchSummaryEntry, + CompactionEntry, + CustomEntry, + Entry, + MessageEntry, +} from "../../src/harness/session/types.ts"; +import { getOrThrow } from "../../src/harness/types.ts"; +import type { AgentMessage } from "../../src/types.ts"; + +let nextId = 0; +function createId(): string { + return `entry-${nextId++}`; +} + +function createMockUsage(input: number, output: number, cacheRead = 0, cacheWrite = 0): Usage { + return { + input, + output, + cacheRead, + cacheWrite, + totalTokens: input + output + cacheRead + cacheWrite, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }; +} + +function createUserMessage(text: string): AgentMessage { + return { + role: "user", + content: [{ type: "text", text }], + timestamp: Date.now(), + }; +} + +function createAssistantMessage(text: string, usage = createMockUsage(100, 50)): AssistantMessage { + return { + role: "assistant", + content: [{ type: "text", text }], + api: "anthropic-messages", + provider: "anthropic", + model: "claude-sonnet-4-5", + usage, + stopReason: "stop", + timestamp: Date.now(), + }; +} + +function createMessageEntry(message: AgentMessage, parentId: string | null = null): MessageEntry { + return { + type: "message", + id: createId(), + parentId, + seq: nextId, + timestamp: Date.now(), + message, + }; +} + +function createCompactionEntry( + summary: string, + parentId: string | null = null, + retainedTail?: AgentMessage[], +): CompactionEntry { + return { + type: "compaction", + id: createId(), + parentId, + seq: nextId, + timestamp: Date.now(), + summary, + tokensBefore: 1234, + retainedTail: retainedTail ?? [], + fromHook: false, + }; +} + +function createCustomEntry(customType: string, parentId: string | null = null): CustomEntry { + return { + type: "custom", + customType, + id: createId(), + parentId, + seq: nextId, + timestamp: Date.now(), + }; +} + +/** Shared collection; each faux provider gets a unique id so coexisting fakes route correctly. */ +const models = createModels(); +let fauxCount = 0; + +function createFauxModel(reasoning: boolean, maxTokens = 8192): { faux: FauxProviderHandle; model: Model } { + const faux = fauxProvider({ + provider: `faux-${++fauxCount}`, + models: [ + { + id: reasoning ? "reasoning-model" : "non-reasoning-model", + reasoning, + contextWindow: 200000, + maxTokens, + }, + ], + }); + models.setProvider(faux.provider); + return { faux, model: faux.getModel() }; +} + +function createModelsWithSimpleResponses(responses: AssistantMessage[]): Models { + const remaining = [...responses]; + const stub = Object.create(models) as Models; + stub.completeSimple = async () => { + const response = remaining.shift(); + if (!response) throw new Error("No faux completeSimple response queued"); + return response; + }; + return stub; +} + +describe("harness compaction", () => { + beforeEach(() => { + nextId = 0; + }); + + it("calculates total context tokens from usage", () => { + expect(calculateContextTokens(createMockUsage(1000, 500, 200, 100))).toBe(1800); + expect(calculateContextTokens(createMockUsage(0, 0, 0, 0))).toBe(0); + }); + + it("checks compaction threshold", () => { + const settings: CompactionSettings = { + enabled: true, + reserveTokens: 10000, + keepRecentTokens: 20000, + }; + expect(shouldCompact(95000, 100000, settings)).toBe(true); + expect(shouldCompact(89000, 100000, settings)).toBe(false); + expect(shouldCompact(95000, 100000, { ...settings, enabled: false })).toBe(false); + }); + + it("finds a cut point based on token differences", () => { + const entries: Entry[] = []; + let parentId: string | null = null; + for (let i = 0; i < 10; i++) { + const user = createMessageEntry(createUserMessage(`User ${i}`), parentId); + entries.push(user); + const assistant = createMessageEntry( + createAssistantMessage(`Assistant ${i}`, createMockUsage(0, 100, (i + 1) * 1000, 0)), + user.id, + ); + entries.push(assistant); + parentId = assistant.id; + } + + const result = findCutPoint(entries, 0, entries.length, 2500); + expect(entries[result.firstKeptEntryIndex]?.type).toBe("message"); + }); + + it("covers cut-point and turn-start edge cases", () => { + const firstCustom = createCustomEntry("first"); + const secondCustom = createCustomEntry("second", firstCustom.id); + expect(findCutPoint([firstCustom, secondCustom], 0, 2, 1)).toEqual({ + firstKeptEntryIndex: 0, + turnStartIndex: -1, + isSplitTurn: false, + }); + + const branchSummary: BranchSummaryEntry = { + type: "branch_summary", + id: createId(), + parentId: secondCustom.id, + seq: nextId, + timestamp: Date.now(), + fromId: "branch", + summary: "branch summary", + fromHook: false, + }; + expect(findTurnStartIndex([firstCustom, branchSummary], 1, 0)).toBe(1); + expect(findTurnStartIndex([firstCustom, secondCustom], 1, 0)).toBe(-1); + + const result = findCutPoint([firstCustom, branchSummary], 0, 2, 1); + expect(result.firstKeptEntryIndex).toBe(0); + + const toolResult = createMessageEntry({ + role: "toolResult", + toolCallId: "call-1", + toolName: "read", + content: [{ type: "text", text: "tool output" }], + isError: false, + timestamp: Date.now(), + }); + expect(findCutPoint([toolResult], 0, 1, 1)).toEqual({ + firstKeptEntryIndex: 0, + turnStartIndex: -1, + isSplitTurn: false, + }); + + const user = createMessageEntry(createUserMessage("user")); + const compaction = createCompactionEntry("summary", user.id); + const assistant = createMessageEntry(createAssistantMessage("assistant"), compaction.id); + expect(findCutPoint([user, compaction, assistant], 0, 3, 1).firstKeptEntryIndex).toBe(2); + }); + + it("estimates tokens and context usage across supported message roles", () => { + const usage = createMockUsage(10, 5, 3, 2); + const assistant = createAssistantMessage("assistant", usage); + const assistantWithThinkingAndTool: AssistantMessage = { + ...assistant, + content: [ + { type: "thinking", thinking: "thinking" }, + { type: "toolCall", id: "call-1", name: "read", arguments: { path: "file.ts" } }, + ], + }; + const customString: AgentMessage = { + role: "custom", + customType: "note", + content: "custom text", + display: true, + timestamp: Date.now(), + }; + const toolResultWithImage: AgentMessage = { + role: "toolResult", + toolCallId: "call-1", + toolName: "read", + content: [ + { type: "text", text: "tool text" }, + { type: "image", mimeType: "image/png", data: "abc" }, + ], + isError: false, + timestamp: Date.now(), + }; + const bashExecution: AgentMessage = { + role: "bashExecution", + command: "npm run check", + output: "ok", + exitCode: 0, + cancelled: false, + truncated: false, + timestamp: Date.now(), + }; + const branchSummaryMessage: AgentMessage = { + role: "branchSummary", + summary: "branch", + fromId: "x", + timestamp: Date.now(), + }; + const compactionSummaryMessage: AgentMessage = { + role: "compactionSummary", + summary: "compact", + tokensBefore: 123, + timestamp: Date.now(), + }; + + expect(estimateTokens({ role: "user", content: "plain user", timestamp: Date.now() })).toBeGreaterThan(0); + expect(estimateTokens(assistantWithThinkingAndTool)).toBeGreaterThan(0); + expect(estimateTokens(customString)).toBeGreaterThan(0); + expect(estimateTokens(toolResultWithImage)).toBeGreaterThan(1000); + expect(estimateTokens(bashExecution)).toBeGreaterThan(0); + expect(estimateTokens(branchSummaryMessage)).toBeGreaterThan(0); + expect(estimateTokens(compactionSummaryMessage)).toBeGreaterThan(0); + expect(estimateTokens({ role: "unknown", timestamp: Date.now() } as unknown as AgentMessage)).toBe(0); + expect( + getLastAssistantUsage([createMessageEntry(createUserMessage("user")), createMessageEntry(assistant)]), + ).toBe(usage); + expect( + getLastAssistantUsage([ + createMessageEntry({ ...assistant, stopReason: "aborted" }), + createMessageEntry({ ...assistant, stopReason: "error" }), + ]), + ).toBeUndefined(); + expect( + getLastAssistantUsage([ + createMessageEntry(createUserMessage("user")), + createMessageEntry(assistant), + createMessageEntry(createAssistantMessage("partial", createMockUsage(0, 0))), + ]), + ).toBe(usage); + expect(estimateContextTokens([createUserMessage("no usage")]).lastUsageIndex).toBeNull(); + expect(estimateContextTokens([assistant, createUserMessage("tail")])).toMatchObject({ + usageTokens: 20, + lastUsageIndex: 0, + }); + const estimate = estimateContextTokens([ + createUserMessage("Hello"), + assistant, + createUserMessage("continue"), + createAssistantMessage("Partial thinking", createMockUsage(0, 0)), + ]); + expect(estimate.usageTokens).toBe(20); + expect(estimate.lastUsageIndex).toBe(1); + expect(estimate.trailingTokens).toBeGreaterThan(0); + expect(estimate.tokens).toBe(20 + estimate.trailingTokens); + }); + + it("builds session context with a compaction entry", async () => { + const u1 = createMessageEntry(createUserMessage("1")); + const a1 = createMessageEntry(createAssistantMessage("a"), u1.id); + const u2 = createMessageEntry(createUserMessage("2"), a1.id); + const a2 = createMessageEntry(createAssistantMessage("b"), u2.id); + const compaction = createCompactionEntry("Summary of 1,a,2,b", a2.id, [ + createUserMessage("2"), + createAssistantMessage("b"), + ]); + const u3 = createMessageEntry(createUserMessage("3"), compaction.id); + const a3 = createMessageEntry(createAssistantMessage("c"), u3.id); + const loaded = await buildSessionContext([u1, a1, u2, a2, compaction, u3, a3], undefined, BACKGROUND_CONTEXT); + expect(loaded).toHaveLength(5); + expect(loaded[0]?.role).toBe("compactionSummary"); + expect(loaded.map((message) => message.role)).toEqual([ + "compactionSummary", + "user", + "assistant", + "user", + "assistant", + ]); + }); + + it("prepares compaction using the latest compaction summary as previousSummary", async () => { + const u1 = createMessageEntry(createUserMessage("user msg 1")); + const a1 = createMessageEntry(createAssistantMessage("assistant msg 1"), u1.id); + const u2 = createMessageEntry(createUserMessage("user msg 2"), a1.id); + const a2 = createMessageEntry(createAssistantMessage("assistant msg 2", createMockUsage(5000, 1000)), u2.id); + const compaction1 = createCompactionEntry("First summary", a2.id); + const u3 = createMessageEntry(createUserMessage("user msg 3"), compaction1.id); + const a3 = createMessageEntry(createAssistantMessage("assistant msg 3", createMockUsage(8000, 2000)), u3.id); + const pathEntries = [u1, a1, u2, a2, compaction1, u3, a3]; + const preparation = getOrThrow(prepareCompaction(pathEntries, DEFAULT_COMPACTION_SETTINGS)); + expect(preparation).toBeDefined(); + expect(preparation?.previousSummary).toBe("First summary"); + expect(preparation?.retainedTail.length).toBeGreaterThan(0); + expect(preparation?.tokensBefore).toBe( + estimateContextTokens(await buildSessionContext(pathEntries, undefined, BACKGROUND_CONTEXT)).tokens, + ); + }); + + it("carries a previous compaction's retained tail into the next preparation", () => { + const retainedUser = createUserMessage("retained user"); + const retainedAssistant = createAssistantMessage("retained assistant"); + const compaction = createCompactionEntry("previous summary", null, [retainedUser, retainedAssistant]); + const user = createMessageEntry(createUserMessage("new user"), compaction.id); + const assistant = createMessageEntry(createAssistantMessage("new assistant"), user.id); + + const preparation = getOrThrow( + prepareCompaction([compaction, user, assistant], { + enabled: true, + reserveTokens: 100, + keepRecentTokens: 1, + }), + ); + expect(preparation?.previousSummary).toBe("previous summary"); + expect([ + ...(preparation?.messagesToSummarize ?? []), + ...(preparation?.turnPrefixMessages ?? []), + ...(preparation?.retainedTail ?? []), + ]).toEqual([retainedUser, retainedAssistant, user.message, assistant.message]); + }); + + it("prepares split-turn compaction with prior file-operation details", () => { + const u1 = createMessageEntry(createUserMessage("user msg 1")); + const assistantMessage: AssistantMessage = { + ...createAssistantMessage("assistant msg 1"), + content: [{ type: "toolCall", id: "tool-1", name: "write", arguments: { path: "written.ts" } }], + }; + const a1 = createMessageEntry(assistantMessage, u1.id); + const compaction1: CompactionEntry = { + ...createCompactionEntry("First summary", a1.id), + details: { readFiles: ["old-read.ts"], modifiedFiles: ["old-edit.ts", "written.ts"] }, + }; + const u2 = createMessageEntry(createUserMessage("large turn"), compaction1.id); + const a2 = createMessageEntry(createAssistantMessage("large assistant message"), u2.id); + const preparation = getOrThrow( + prepareCompaction([u1, a1, compaction1, u2, a2], { + enabled: true, + reserveTokens: 100, + keepRecentTokens: 1, + }), + ); + + expect(preparation).toMatchObject({ previousSummary: "First summary", isSplitTurn: true }); + expect(preparation?.turnPrefixMessages.map((message) => message.role)).toEqual(["user"]); + expect([...preparation!.fileOps.read]).toContain("old-read.ts"); + expect([...preparation!.fileOps.edited]).toContain("old-edit.ts"); + expect([...preparation!.fileOps.edited]).toContain("written.ts"); + }); + + it("does not prepare compaction when there is nothing valid to compact", () => { + const compaction = createCompactionEntry("already compacted"); + expect(getOrThrow(prepareCompaction([compaction], DEFAULT_COMPACTION_SETTINGS))).toBeUndefined(); + expect(getOrThrow(prepareCompaction([], DEFAULT_COMPACTION_SETTINGS))).toBeUndefined(); + }); + + it("serializes conversation with truncated tool results", () => { + const longContent = "x".repeat(5000); + const messages = convertMessages([ + { + role: "toolResult", + toolCallId: "tc1", + toolName: "read", + content: [{ type: "text", text: longContent }], + isError: false, + timestamp: Date.now(), + }, + ]); + const result = serializeConversation(messages); + expect(result).toContain("[Tool result]:"); + expect(result).toContain("[... 3000 more characters truncated]"); + }); + + it("passes reasoning through generateSummary only for reasoning models with thinking enabled", async () => { + const messages: AgentMessage[] = [createUserMessage("Summarize this.")]; + const seenOptions: Array | undefined> = []; + const { faux: fauxReasoning, model: reasoningModel } = createFauxModel(true); + fauxReasoning.setResponses([ + (_context, options) => { + seenOptions.push(options as Record | undefined); + return fauxAssistantMessage("## Goal\nTest summary"); + }, + ]); + getOrThrow( + await generateSummary( + messages, + models, + reasoningModel, + 2000, + undefined, + undefined, + "medium", + undefined, + undefined, + BACKGROUND_CONTEXT, + ), + ); + expect(seenOptions[0]).toMatchObject({ reasoning: "medium" }); + + const { faux: fauxOff, model: offModel } = createFauxModel(true); + fauxOff.setResponses([ + (_context, options) => { + seenOptions.push(options as Record | undefined); + return fauxAssistantMessage("## Goal\nTest summary"); + }, + ]); + getOrThrow( + await generateSummary( + messages, + models, + offModel, + 2000, + undefined, + undefined, + "off", + undefined, + undefined, + BACKGROUND_CONTEXT, + ), + ); + expect(seenOptions[1]).not.toHaveProperty("reasoning"); + + const { faux: fauxNonReasoning, model: nonReasoningModel } = createFauxModel(false); + fauxNonReasoning.setResponses([ + (_context, options) => { + seenOptions.push(options as Record | undefined); + return fauxAssistantMessage("## Goal\nTest summary"); + }, + ]); + getOrThrow( + await generateSummary( + messages, + models, + nonReasoningModel, + 2000, + undefined, + undefined, + "medium", + undefined, + undefined, + BACKGROUND_CONTEXT, + ), + ); + expect(seenOptions[2]).not.toHaveProperty("reasoning"); + }); + + it("includes previous summaries and custom instructions in generateSummary prompts", async () => { + const messages: AgentMessage[] = [createUserMessage("Summarize this.")]; + let promptText = ""; + const { faux, model } = createFauxModel(false); + faux.setResponses([ + (context) => { + const message = context.messages[0]; + const content = message?.role === "user" ? message.content : []; + promptText = Array.isArray(content) && content[0]?.type === "text" ? content[0].text : ""; + return fauxAssistantMessage("## Goal\nTest summary"); + }, + ]); + + const summary = getOrThrow( + await generateSummaryWithUsage( + messages, + models, + model, + 2000, + "focus", + "old summary", + undefined, + undefined, + undefined, + BACKGROUND_CONTEXT, + ), + ); + + expect(summary.text).toContain("Test summary"); + expect(summary.usage.input).toBeGreaterThan(0); + expect(summary.usage.output).toBeGreaterThan(0); + expect(summary.usage.totalTokens).toBe( + summary.usage.input + summary.usage.output + summary.usage.cacheRead + summary.usage.cacheWrite, + ); + expect(promptText).toContain("\nold summary\n"); + expect(promptText).toContain("Additional focus: focus"); + }); + + it("preserves the string result from generateSummary", async () => { + const messages: AgentMessage[] = [createUserMessage("Summarize this.")]; + const { faux, model } = createFauxModel(false); + faux.setResponses([fauxAssistantMessage("## Goal\nTest summary")]); + + expect( + getOrThrow( + await generateSummary( + messages, + models, + model, + 2000, + undefined, + undefined, + undefined, + undefined, + undefined, + BACKGROUND_CONTEXT, + ), + ), + ).toBe("## Goal\nTest summary"); + }); + + it("returns error results for failed or aborted summary generations", async () => { + const messages: AgentMessage[] = [createUserMessage("Summarize this.")]; + const { faux: errorFaux, model: errorModel } = createFauxModel(false); + errorFaux.setResponses([fauxAssistantMessage("", { stopReason: "error", errorMessage: "boom" })]); + const errorResult = await generateSummary( + messages, + models, + errorModel, + 2000, + undefined, + undefined, + undefined, + undefined, + undefined, + BACKGROUND_CONTEXT, + ); + expect(errorResult).toMatchObject({ + ok: false, + error: { code: "summarization_failed", message: "Summarization failed: boom" }, + }); + + const { faux: abortedFaux, model: abortedModel } = createFauxModel(false); + abortedFaux.setResponses([fauxAssistantMessage("", { stopReason: "aborted", errorMessage: "stopped" })]); + const abortedResult = await generateSummary( + messages, + models, + abortedModel, + 2000, + undefined, + undefined, + undefined, + undefined, + undefined, + BACKGROUND_CONTEXT, + ); + expect(abortedResult).toMatchObject({ ok: false, error: { code: "aborted", message: "stopped" } }); + }); + + it("clamps compaction summary maxTokens to the model output cap", async () => { + const messages: AgentMessage[] = [createUserMessage("Summarize this.")]; + const seenOptions: Array | undefined> = []; + const { faux, model } = createFauxModel(false, 128000); + faux.setResponses([ + (_context, options) => { + seenOptions.push(options as Record | undefined); + return fauxAssistantMessage("## Goal\nTest summary"); + }, + (_context, options) => { + seenOptions.push(options as Record | undefined); + return fauxAssistantMessage("## Goal\nTest summary"); + }, + ]); + const preparation: CompactionPreparation = { + messagesToSummarize: messages, + turnPrefixMessages: messages, + retainedTail: messages, + isSplitTurn: true, + tokensBefore: 600000, + fileOps: { read: new Set(), written: new Set(), edited: new Set() }, + settings: { enabled: true, reserveTokens: 500000, keepRecentTokens: 20000 }, + }; + + getOrThrow( + await compact(preparation, models, model, undefined, undefined, undefined, undefined, BACKGROUND_CONTEXT), + ); + + expect(seenOptions.map((options) => options?.maxTokens)).toEqual([128000, 128000]); + expect(seenOptions.map((options) => options?.cacheRetention)).toEqual(["none", "none"]); + const sessionIds = seenOptions.map((options) => options?.sessionId); + expect(sessionIds[0]).not.toBe(sessionIds[1]); + }); + + it("retains per-request retries for non-harness compaction callers", async () => { + const messages: AgentMessage[] = [createUserMessage("Summarize this.")]; + const preparation: CompactionPreparation = { + messagesToSummarize: messages, + turnPrefixMessages: [], + retainedTail: messages, + isSplitTurn: false, + tokensBefore: 100, + fileOps: { read: new Set(), written: new Set(), edited: new Set() }, + settings: { enabled: true, reserveTokens: 2_000, keepRecentTokens: 20 }, + }; + const { faux, model } = createFauxModel(false); + faux.setResponses([ + fauxAssistantMessage("", { stopReason: "error", errorMessage: "rate limit exceeded" }), + fauxAssistantMessage("recovered summary"), + ]); + + expect( + getOrThrow( + await compact( + preparation, + models, + model, + undefined, + undefined, + { enabled: true, maxRetries: 1, baseDelayMs: 0 }, + undefined, + BACKGROUND_CONTEXT, + ), + ).summary, + ).toContain("recovered summary"); + }); + + it("returns compaction error results without throwing", async () => { + const messages: AgentMessage[] = [createUserMessage("Summarize this.")]; + const preparation: CompactionPreparation = { + messagesToSummarize: messages, + turnPrefixMessages: [], + retainedTail: messages, + isSplitTurn: false, + tokensBefore: 100, + fileOps: { read: new Set(), written: new Set(), edited: new Set() }, + settings: { enabled: true, reserveTokens: 2000, keepRecentTokens: 20 }, + }; + const { faux: historyFaux, model: historyModel } = createFauxModel(false); + historyFaux.setResponses([fauxAssistantMessage("", { stopReason: "error", errorMessage: "history failed" })]); + expect( + await compact( + preparation, + models, + historyModel, + undefined, + undefined, + undefined, + undefined, + BACKGROUND_CONTEXT, + ), + ).toMatchObject({ + ok: false, + error: { code: "summarization_failed", message: "Summarization failed: history failed" }, + }); + }); + + it("combines usage for split-turn compaction summaries", async () => { + const messages: AgentMessage[] = [createUserMessage("Summarize this.")]; + const { model } = createFauxModel(false); + const historyUsage = createMockUsage(1, 2, 3, 4); + const turnPrefixUsage = createMockUsage(5, 6, 7, 8); + const usageModels = createModelsWithSimpleResponses([ + { ...fauxAssistantMessage("history summary"), usage: historyUsage }, + { ...fauxAssistantMessage("turn prefix summary"), usage: turnPrefixUsage }, + ]); + const preparation: CompactionPreparation = { + messagesToSummarize: messages, + turnPrefixMessages: messages, + isSplitTurn: true, + tokensBefore: 100, + retainedTail: messages, + fileOps: { read: new Set(), written: new Set(), edited: new Set() }, + settings: { enabled: true, reserveTokens: 2000, keepRecentTokens: 20 }, + }; + + const result = getOrThrow( + await compact(preparation, usageModels, model, undefined, undefined, undefined, undefined, BACKGROUND_CONTEXT), + ); + + expect(result.usage).toEqual(createMockUsage(6, 8, 10, 12)); + }); + + it("passes reasoning through turn-prefix summaries when enabled", async () => { + const messages: AgentMessage[] = [createUserMessage("Summarize this.")]; + const seenOptions: Array | undefined> = []; + const { faux, model } = createFauxModel(true); + faux.setResponses([ + (_context, options) => { + seenOptions.push(options as Record | undefined); + return fauxAssistantMessage("## Original Request\nTest summary"); + }, + ]); + const preparation: CompactionPreparation = { + messagesToSummarize: [], + turnPrefixMessages: messages, + retainedTail: messages, + isSplitTurn: true, + tokensBefore: 100, + fileOps: { read: new Set(), written: new Set(), edited: new Set() }, + settings: { enabled: true, reserveTokens: 2000, keepRecentTokens: 20 }, + }; + + getOrThrow( + await compact(preparation, models, model, undefined, "high", undefined, undefined, BACKGROUND_CONTEXT), + ); + + expect(seenOptions[0]).toMatchObject({ reasoning: "high" }); + }); + + it("returns turn-prefix compaction errors without throwing", async () => { + const messages: AgentMessage[] = [createUserMessage("Summarize this.")]; + const preparation: CompactionPreparation = { + messagesToSummarize: [], + turnPrefixMessages: messages, + retainedTail: messages, + isSplitTurn: true, + tokensBefore: 100, + fileOps: { read: new Set(), written: new Set(), edited: new Set() }, + settings: { enabled: true, reserveTokens: 2000, keepRecentTokens: 20 }, + }; + const { faux, model } = createFauxModel(false); + faux.setResponses([fauxAssistantMessage("", { stopReason: "error", errorMessage: "prefix failed" })]); + + expect( + await compact(preparation, models, model, undefined, undefined, undefined, undefined, BACKGROUND_CONTEXT), + ).toMatchObject({ + ok: false, + error: { code: "summarization_failed", message: "Turn prefix summarization failed: prefix failed" }, + }); + + const { faux: abortedFaux, model: abortedModel } = createFauxModel(false); + abortedFaux.setResponses([fauxAssistantMessage("", { stopReason: "aborted", errorMessage: "prefix stopped" })]); + expect( + await compact( + preparation, + models, + abortedModel, + undefined, + undefined, + undefined, + undefined, + BACKGROUND_CONTEXT, + ), + ).toMatchObject({ + ok: false, + error: { code: "aborted", message: "prefix stopped" }, + }); + }); + + it("returns a compaction result with file details", async () => { + const u1 = createMessageEntry(createUserMessage("read a file")); + const assistantMessage: AssistantMessage = { + ...createAssistantMessage("calling tool", createMockUsage(1000, 200)), + content: [{ type: "toolCall", id: "tool-1", name: "read", arguments: { path: "src/index.ts" } }], + }; + const a1 = createMessageEntry(assistantMessage, u1.id); + const u2 = createMessageEntry(createUserMessage("continue"), a1.id); + const a2 = createMessageEntry(createAssistantMessage("done", createMockUsage(4000, 500)), u2.id); + const preparation = getOrThrow(prepareCompaction([u1, a1, u2, a2], DEFAULT_COMPACTION_SETTINGS)); + expect(preparation).toBeDefined(); + const { faux, model } = createFauxModel(false); + faux.setResponses([fauxAssistantMessage("## Goal\nTest summary")]); + const result = getOrThrow( + await compact(preparation!, models, model, undefined, undefined, undefined, undefined, BACKGROUND_CONTEXT), + ); + expect(result.summary.length).toBeGreaterThan(0); + expect(result.usage?.totalTokens).toBeGreaterThan(0); + expect(result.retainedTail?.length).toBeGreaterThan(0); + expect(result.details).toBeDefined(); + }); +}); + +function convertMessages(messages: Message[]): Message[] { + return messages; +} diff --git a/packages/agent/test/harness/context.test.ts b/packages/agent/test/harness/context.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b540d89483ee3d5ce9ef0ec601b9bd33b4e69737 --- /dev/null +++ b/packages/agent/test/harness/context.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { + BACKGROUND_CONTEXT, + getTelemetryContext, + TODO_CONTEXT, + withTelemetryContext, +} from "../../src/harness/context.ts"; +import { InMemoryTelemetryContext, NOOP_TELEMETRY_CONTEXT } from "../../src/index.ts"; + +describe("harness Context telemetry", () => { + it("uses no-op telemetry when none is attached", () => { + expect(getTelemetryContext(BACKGROUND_CONTEXT)).toBe(NOOP_TELEMETRY_CONTEXT); + expect(getTelemetryContext(TODO_CONTEXT)).toBe(NOOP_TELEMETRY_CONTEXT); + }); + + it("carries telemetry as an ordinary context value", async () => { + const telemetry = new InMemoryTelemetryContext(); + const context = withTelemetryContext(telemetry, BACKGROUND_CONTEXT); + + await getTelemetryContext(context).startSpan({ name: "parent" }, async (span) => { + const childContext = withTelemetryContext(span, context); + await getTelemetryContext(childContext).startSpan({ name: "child" }, () => undefined); + }); + + const spans = telemetry.getSpans(); + expect(spans.map((span) => span.name)).toEqual(["parent", "child"]); + expect(spans[1]?.parentId).toBe(spans[0]?.id); + }); +}); diff --git a/packages/agent/test/harness/execution-assistant.test.ts b/packages/agent/test/harness/execution-assistant.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5129b5ffe3c06e5e01abcc6e433d794a5f5f4477 --- /dev/null +++ b/packages/agent/test/harness/execution-assistant.test.ts @@ -0,0 +1,343 @@ +import { + type Api, + type AssistantMessage, + createAssistantMessageEventStream, + fauxAssistantMessage, + fauxProvider, + type Message, + type Model, + type SimpleStreamOptions, + type UserMessage, +} from "@earendil-works/pi-ai"; +import { NOOP_TELEMETRY_CONTEXT } from "@earendil-works/pi-telemetry"; +import { describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT, withAbortSignal } from "../../src/harness/context.ts"; +import { type AssistantResponseMetadata, streamHarnessAssistant } from "../../src/harness/execution/assistant.ts"; +import { AbortRequested } from "../../src/harness/execution/effect-gate.ts"; +import type { AgentMessage } from "../../src/types.ts"; + +function usage() { + return { + input: 1, + output: 2, + cacheRead: 3, + cacheWrite: 4, + totalTokens: 10, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }; +} + +function model(): Model { + return { + id: "model", + name: "Model", + api: "test", + provider: "provider", + baseUrl: "https://example.invalid", + reasoning: true, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 128_000, + maxTokens: 16_384, + }; +} + +function user(text: string): UserMessage { + return { role: "user", content: text, timestamp: 1 }; +} + +function assistant( + text: string, + stopReason: Exclude = "stop", +): AssistantMessage & { stopReason: Exclude } { + return { + role: "assistant", + content: [{ type: "text", text }], + api: "test", + provider: "provider", + model: "model", + usage: usage(), + stopReason, + ...(stopReason === "error" ? { errorMessage: text } : {}), + timestamp: 2, + }; +} + +function toProviderMessages(messages: AgentMessage[]): Message[] { + return messages.filter( + (message): message is Message => + message.role === "user" || message.role === "assistant" || message.role === "toolResult", + ); +} + +describe("streamHarnessAssistant", () => { + it("maps curated options and runs the assistant lifecycle without mutating input", async () => { + const input: AgentMessage[] = [user("original")]; + const originalArray = input; + const requestModel = model(); + const controller = new AbortController(); + const order: string[] = []; + const starts: AssistantMessage[] = []; + const updates: AssistantMessage[] = []; + const ends: AssistantMessage[] = []; + let transformedInputWasCopy = false; + let convertedMessages: AgentMessage[] = []; + let requestContext: Parameters>[0] | undefined; + let receivedContext: { systemPrompt?: string; messages: Message[]; tools?: unknown[] } | undefined; + let receivedOptions: SimpleStreamOptions | undefined; + let responseMetadata: AssistantResponseMetadata | undefined; + let startEventType: string | undefined; + + const result = await streamHarnessAssistant( + input, + { + model: requestModel, + systemPrompt: "system", + thinkingLevel: "high", + streamOptions: { + transport: "websocket", + timeoutMs: 123, + maxRetries: 2, + maxRetryDelayMs: 456, + headers: { authorization: "test" }, + metadata: { tenant: "one" }, + cacheRetention: "long", + deferred: { window: "1h" }, + }, + transformContext: async (context) => { + order.push("transform_context"); + transformedInputWasCopy = context.messages !== originalArray; + context.messages.push(user("injected")); + return { messages: context.messages, systemPrompt: "transformed system" }; + }, + toProviderMessages: (messages) => { + order.push("to_provider_messages"); + convertedMessages = messages; + return toProviderMessages(messages); + }, + beforePayload: (payload, seenModel) => { + order.push("before_payload"); + expect(seenModel.id).toBe("resolved"); + requestContext = payload; + return { replaced: true }; + }, + afterResponse: async (message, metadata) => { + order.push("after_response"); + responseMetadata = metadata; + return { ...message, content: [{ type: "text", text: "transformed" }] }; + }, + request: async (context, options) => { + order.push("request"); + receivedContext = context; + receivedOptions = options; + expect(await options.onPayload?.({ original: true }, { ...requestModel, id: "resolved" })).toEqual({ + replaced: true, + }); + await options.onResponse?.({ status: 201, headers: { "request-id": "r1" } }, requestModel); + const stream = createAssistantMessageEventStream(); + queueMicrotask(() => { + const initial = { ...assistant(""), stopReason: "pending" as const }; + const partial = { ...initial, content: [{ type: "text" as const, text: "raw" }] }; + stream.push({ type: "start", partial: initial }); + stream.push({ type: "text_delta", contentIndex: 0, delta: "raw", partial }); + stream.push({ type: "done", reason: "stop", message: assistant("raw") }); + }); + return stream; + }, + observer: { + start(message, event) { + order.push("observer_start"); + starts.push(message); + startEventType = event.type; + }, + update(message) { + order.push("observer_update"); + updates.push(message); + }, + end(message) { + order.push("observer_end"); + ends.push(message); + }, + }, + }, + withAbortSignal(controller.signal, BACKGROUND_CONTEXT), + ); + + expect(input).toEqual([user("original")]); + expect(transformedInputWasCopy).toBe(true); + expect(convertedMessages).toEqual([user("original"), user("injected")]); + expect(receivedContext).toMatchObject({ + systemPrompt: "transformed system", + messages: [user("original"), user("injected")], + }); + expect(requestContext).toEqual({ original: true }); + expect(receivedOptions).toMatchObject({ + transport: "websocket", + timeoutMs: 123, + maxRetries: 2, + maxRetryDelayMs: 456, + headers: { authorization: "test" }, + metadata: { tenant: "one" }, + cacheRetention: "long", + deferred: { window: "1h" }, + reasoning: "high", + signal: controller.signal, + telemetryContext: NOOP_TELEMETRY_CONTEXT, + }); + expect(responseMetadata).toEqual({ status: 201, headers: { "request-id": "r1" } }); + expect(starts).toHaveLength(1); + expect(startEventType).toBe("start"); + expect(starts[0]).not.toBe(updates[0]); + expect(updates).toHaveLength(1); + expect(ends[0]).toBe(result); + expect(result.content).toEqual([{ type: "text", text: "transformed" }]); + expect(order).toEqual([ + "transform_context", + "to_provider_messages", + "request", + "before_payload", + "observer_start", + "observer_update", + "after_response", + "observer_end", + ]); + }); + + it("runs against the faux provider request boundary", async () => { + const faux = fauxProvider({ tokenSize: { min: 1, max: 1 } }); + faux.setResponses([fauxAssistantMessage("hello")]); + const lifecycle: string[] = []; + let seenContext: Message[] = []; + + const result = await streamHarnessAssistant( + [user("prompt")], + { + model: faux.getModel(), + systemPrompt: "system", + thinkingLevel: "off", + streamOptions: {}, + toProviderMessages, + request: (context, options) => { + seenContext = context.messages; + return faux.provider.streamSimple(faux.getModel(), context, options); + }, + observer: { + start() { + lifecycle.push("start"); + }, + update() { + lifecycle.push("update"); + }, + end() { + lifecycle.push("end"); + }, + }, + }, + BACKGROUND_CONTEXT, + ); + + expect(seenContext).toEqual([user("prompt")]); + expect(result.content).toEqual([{ type: "text", text: "hello" }]); + expect(lifecycle[0]).toBe("start"); + expect(lifecycle.at(-1)).toBe("end"); + expect(lifecycle.filter((event) => event === "update").length).toBeGreaterThan(0); + }); + + it("rejects a successful terminal event before start", async () => { + const final = assistant("complete"); + let options: SimpleStreamOptions | undefined; + await expect( + streamHarnessAssistant( + [user("prompt")], + { + model: model(), + systemPrompt: "system", + thinkingLevel: "off", + streamOptions: {}, + toProviderMessages, + request: (_context, requestOptions) => { + options = requestOptions; + const stream = createAssistantMessageEventStream(); + queueMicrotask(() => stream.push({ type: "done", reason: "stop", message: final })); + return stream; + }, + observer: { start() {}, update() {}, end() {} }, + }, + BACKGROUND_CONTEXT, + ), + ).rejects.toThrow("done before start"); + expect(options).not.toHaveProperty("reasoning"); + }); + + it("keeps the raw settlement when cancellation interrupts after_response", async () => { + const final = assistant("raw"); + const ended: AssistantMessage[] = []; + const result = await streamHarnessAssistant( + [user("prompt")], + { + model: model(), + systemPrompt: "system", + thinkingLevel: "off", + streamOptions: {}, + toProviderMessages, + request: () => { + const stream = createAssistantMessageEventStream(); + queueMicrotask(() => { + stream.push({ type: "start", partial: { ...final, content: [], stopReason: "pending" } }); + stream.push({ type: "done", reason: "stop", message: final }); + }); + return stream; + }, + afterResponse: async () => { + throw new AbortRequested(Promise.resolve()); + }, + observer: { + start() {}, + update() {}, + end(message) { + ended.push(message); + }, + }, + }, + BACKGROUND_CONTEXT, + ); + + expect(result).toBe(final); + expect(ended).toEqual([final]); + }); + + it("returns provider error settlements through the same lifecycle", async () => { + const final = assistant("provider failed", "error"); + const events: string[] = []; + const result = await streamHarnessAssistant( + [user("prompt")], + { + model: model(), + systemPrompt: "system", + thinkingLevel: "off", + streamOptions: {}, + toProviderMessages, + request: () => { + const stream = createAssistantMessageEventStream(); + queueMicrotask(() => stream.push({ type: "error", reason: "error", error: final })); + return stream; + }, + observer: { + start() { + throw new Error("pre-generation error must not synthesize start"); + }, + update() { + events.push("update"); + }, + end(message) { + events.push(`end:${message.stopReason}`); + }, + }, + }, + BACKGROUND_CONTEXT, + ); + + expect(result).toBe(final); + expect(events).toEqual(["end:error"]); + }); +}); diff --git a/packages/agent/test/harness/execution-primitives.test.ts b/packages/agent/test/harness/execution-primitives.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f2abd6edc32a1db841ab8301c37e77519931854 --- /dev/null +++ b/packages/agent/test/harness/execution-primitives.test.ts @@ -0,0 +1,670 @@ +import { fauxProvider } from "@earendil-works/pi-ai"; +import { describe, expect, it, vi } from "vitest"; +import { + BACKGROUND_CONTEXT, + createContextKey, + getTelemetryContext, + withAbortSignal, + withContextValue, + withTelemetryContext, +} from "../../src/harness/context.ts"; +import { HarnessEventBus } from "../../src/harness/events.ts"; +import { AbortRequested, createGate } from "../../src/harness/execution/effect-gate.ts"; +import { HookRegistry } from "../../src/harness/hooks.ts"; +import { InMemoryTelemetryContext } from "../../src/index.ts"; + +function deferred(): { promise: Promise; resolve(): void } { + let resolvePromise: (() => void) | undefined; + const promise = new Promise((resolve) => { + resolvePromise = resolve; + }); + return { promise, resolve: () => resolvePromise?.() }; +} + +describe("createGate", () => { + it("closes starts synchronously and signals only after cancellation commits", async () => { + const { gate, control } = createGate(); + const cancellation = deferred(); + control.beginAbort(cancellation.promise); + + let refusal: unknown; + try { + gate.admit(() => undefined); + } catch (error) { + refusal = error; + } + expect(refusal).toBeInstanceOf(AbortRequested); + expect((refusal as AbortRequested).cancellation).toBe(cancellation.promise); + expect(gate.signal.aborted).toBe(false); + cancellation.resolve(); + await cancellation.promise; + control.signalAbort(); + expect(gate.signal.aborted).toBe(true); + }); + + it("permanently closes and signals admitted work", () => { + const { gate, control } = createGate(); + const error = new Error("closed"); + control.close(error); + expect(() => gate.admit(() => undefined)).toThrow(error); + expect(gate.signal.aborted).toBe(true); + }); +}); + +describe("HookRegistry", () => { + it("aggregates before_run messages in registration order with each handler seeing prior output", async () => { + const errors: Error[] = []; + const hooks = new HookRegistry((error) => { + errors.push(error); + }); + const second = vi.fn((event: { prompt: Array<{ role: string }> }) => { + expect(event.prompt).toHaveLength(2); + return { messages: [{ role: "user" as const, content: "second", timestamp: 3 }] }; + }); + hooks.on("before_run", () => ({ messages: [{ role: "user", content: "first", timestamp: 2 }] })); + hooks.on("before_run", second); + + const result = await hooks.runWithGate( + "before_run", + { + lane: "main", + runId: "run", + prompt: [{ role: "user", content: "prompt", timestamp: 1 }], + resources: {}, + }, + createGate().gate, + BACKGROUND_CONTEXT, + ); + + expect(result).toMatchObject({ + messages: [ + { role: "user", content: "first" }, + { role: "user", content: "second" }, + ], + }); + expect(second).toHaveBeenCalledOnce(); + expect(errors).toEqual([]); + }); + + it("checks the effect gate immediately before the complete before_run pipeline", async () => { + const hooks = new HookRegistry(() => {}); + const calls: string[] = []; + const release = deferred(); + hooks.on("before_run", async () => { + calls.push("first:start"); + await release.promise; + calls.push("first:end"); + return undefined; + }); + hooks.on("before_run", () => { + calls.push("second"); + return undefined; + }); + const event = { lane: "main", runId: "run", prompt: [], resources: {} }; + const closed = new Error("closed"); + const closedGate = createGate(); + closedGate.control.close(closed); + expect(() => hooks.runWithGate("before_run", event, closedGate.gate, BACKGROUND_CONTEXT)).toThrow(closed); + expect(calls).toEqual([]); + + const running = hooks.runWithGate("before_run", event, createGate().gate, BACKGROUND_CONTEXT); + expect(calls).toEqual(["first:start"]); + hooks.on("before_run", () => { + calls.push("late"); + return undefined; + }); + hooks.close(closed); + release.resolve(); + await running; + expect(calls).toEqual(["first:start", "first:end", "second"]); + }); + + it("rejects pre-aborted invocations and combines admitted hook cancellation with the effect gate", async () => { + const event = { operation: "run" as const, lane: "main", runId: "run" }; + const preAbortedHooks = new HookRegistry(() => {}); + const handler = vi.fn(); + preAbortedHooks.on("before_drive", handler); + const preAbortedGate = createGate(); + const invocationController = new AbortController(); + const abortReason = new Error("invocation aborted"); + invocationController.abort(abortReason); + + expect(() => + preAbortedHooks.runWithGate( + "before_drive", + event, + preAbortedGate.gate, + withAbortSignal(invocationController.signal, BACKGROUND_CONTEXT), + ), + ).toThrow(abortReason); + expect(handler).not.toHaveBeenCalled(); + expect(() => preAbortedGate.gate.admit(() => undefined)).not.toThrow(); + + const admittedHooks = new HookRegistry(() => {}); + const admittedGate = createGate(); + let admittedSignal: AbortSignal | undefined; + admittedHooks.on("before_drive", (_event, context) => { + admittedSignal = context.abortSignal; + }); + await admittedHooks.runWithGate("before_drive", event, admittedGate.gate, BACKGROUND_CONTEXT); + expect(admittedSignal?.aborted).toBe(false); + + const gateReason = new Error("gate closed"); + admittedGate.control.close(gateReason); + expect(admittedSignal?.aborted).toBe(true); + expect(admittedSignal?.reason).toBe(gateReason); + }); + + it("passes tool handlers a child context of the active hook span", async () => { + const telemetry = new InMemoryTelemetryContext(); + const valueKey = createContextKey("hook.test.value"); + const hooks = new HookRegistry(() => {}); + let receivedValue: string | undefined; + hooks.on("before_tool", async (_event, context) => { + receivedValue = context.value(valueKey); + await getTelemetryContext(context).startSpan({ name: "handler.child" }, () => undefined); + return undefined; + }); + + await telemetry.startSpan({ name: "invocation" }, (invocationSpan) => + hooks.runToolWithGate( + "before_tool", + { + lane: "main", + runId: "run", + toolCallId: "call", + toolName: "tool", + args: {}, + }, + createGate().gate, + withContextValue(valueKey, "preserved", withTelemetryContext(invocationSpan, BACKGROUND_CONTEXT)), + ), + ); + + expect(receivedValue).toBe("preserved"); + const spans = telemetry.getSpans(); + const invocationSpan = spans.find((span) => span.name === "invocation"); + const hookSpan = spans.find((span) => span.name === "pi.harness.hook"); + const handlerSpan = spans.find((span) => span.name === "handler.child"); + expect(hookSpan?.parentId).toBe(invocationSpan?.id); + expect(handlerSpan?.parentId).toBe(hookSpan?.id); + }); + + it("treats registration ids as optional metadata and fails before_drive closed", async () => { + const errors: Error[] = []; + const hooks = new HookRegistry((error) => { + errors.push(error); + }); + const failure = new Error("prerequisite failed"); + const later = vi.fn(); + hooks.on( + "before_drive", + () => { + throw failure; + }, + { id: "duplicate" }, + ); + hooks.on("before_drive", later, { id: "duplicate" }); + + await expect( + hooks.runWithGate( + "before_drive", + { lane: "main", runId: "run", operation: "run" }, + createGate().gate, + BACKGROUND_CONTEXT, + ), + ).rejects.toBe(failure); + expect(later).not.toHaveBeenCalled(); + expect(errors).toEqual([failure]); + }); + + it("chains transform_context output and isolates handler failures", async () => { + const errors: Error[] = []; + const hooks = new HookRegistry((error) => { + errors.push(error); + }); + const messages = [{ role: "user" as const, content: "transformed", timestamp: 2 }]; + hooks.on("transform_context", () => ({ messages, systemPrompt: "first" })); + hooks.on("transform_context", (event) => { + expect(event.messages).toBe(messages); + expect(event.systemPrompt).toBe("first"); + throw new Error("ignored transform failure"); + }); + hooks.on("transform_context", (event) => { + expect(event.messages).toBe(messages); + expect(event.systemPrompt).toBe("first"); + return { systemPrompt: "final" }; + }); + + const result = await hooks.runWithGate( + "transform_context", + { + lane: "main", + runId: "run", + messages: [{ role: "user", content: "original", timestamp: 1 }], + systemPrompt: "base", + }, + createGate().gate, + BACKGROUND_CONTEXT, + ); + + expect(result).toEqual({ messages, systemPrompt: "final" }); + expect(errors).toHaveLength(1); + expect(errors[0]?.message).toBe("ignored transform failure"); + }); + + it("preserves clear-all before_request patches across later handlers", async () => { + const hooks = new HookRegistry(() => {}); + hooks.on("before_request", () => ({ streamOptions: { headers: undefined, metadata: undefined } })); + hooks.on("before_request", (event) => { + expect(event.streamOptions.headers).toBeUndefined(); + expect(event.streamOptions.metadata).toBeUndefined(); + return { streamOptions: { headers: { c: "3" }, metadata: { y: 2 } } }; + }); + const result = await hooks.runWithGate( + "before_request", + { + lane: "main", + runId: "run", + model: fauxProvider().getModel(), + step: "assistant", + attempt: 1, + streamOptions: { headers: { a: "1", b: "2" }, metadata: { x: 1 } }, + }, + createGate().gate, + BACKGROUND_CONTEXT, + ); + expect(result).toEqual({ + streamOptions: { + headers: { a: undefined, b: undefined, c: "3" }, + metadata: { x: undefined, y: 2 }, + }, + }); + }); + + it("preserves earlier after_tool fields when a later patch returns undefined", async () => { + const hooks = new HookRegistry(() => {}); + hooks.on("after_tool", () => ({ content: [{ type: "text", text: "patched" }] })); + hooks.on("after_tool", () => ({ content: undefined, isError: false })); + const result = await hooks.runWithGate( + "after_tool", + { + lane: "main", + runId: "run", + toolCallId: "call", + toolName: "tool", + args: {}, + content: [{ type: "text", text: "raw" }], + isError: true, + }, + createGate().gate, + BACKGROUND_CONTEXT, + ); + expect(result).toEqual({ content: [{ type: "text", text: "patched" }], isError: false }); + }); + + it("accepts explicit false structural declines and rejects true conflicts", async () => { + const errors: Error[] = []; + const hooks = new HookRegistry((error) => { + errors.push(error); + }); + const ignored = { summary: "ignored", readFiles: [], modifiedFiles: [] }; + const selected = { summary: "selected", readFiles: [], modifiedFiles: [] }; + hooks.on("before_navigation", () => ({ decline: true, summary: ignored })); + hooks.on("before_navigation", () => ({ decline: false, summary: selected })); + + const result = await hooks.runWithGate( + "before_navigation", + { + lane: "main", + runId: "run", + targetId: "target", + preparation: { + messages: [], + fileOps: { read: new Set(), written: new Set(), edited: new Set() }, + totalTokens: 0, + }, + }, + createGate().gate, + BACKGROUND_CONTEXT, + ); + expect(result).toEqual({ decline: false, summary: selected }); + expect(errors).toHaveLength(1); + expect(errors[0].message).toMatch(/cannot return both decline and summary/); + }); + + it("admits the complete before_drive pipeline as one gated effect", async () => { + const hooks = new HookRegistry(() => {}); + const calls: string[] = []; + const release = deferred(); + hooks.on("before_drive", async () => { + calls.push("first:start"); + await release.promise; + calls.push("first:end"); + }); + hooks.on("before_drive", () => { + calls.push("second"); + }); + const event = { operation: "run" as const, lane: "main", runId: "run" }; + + const abortFirstGate = createGate(); + const cancellation = Promise.resolve(); + abortFirstGate.control.beginAbort(cancellation); + expect(() => hooks.runWithGate("before_drive", event, abortFirstGate.gate, BACKGROUND_CONTEXT)).toThrow( + AbortRequested, + ); + expect(calls).toEqual([]); + + const startFirstGate = createGate(); + const running = hooks.runWithGate("before_drive", event, startFirstGate.gate, BACKGROUND_CONTEXT); + expect(calls).toEqual(["first:start"]); + startFirstGate.control.beginAbort(cancellation); + startFirstGate.control.signalAbort(); + release.resolve(); + await running; + expect(calls).toEqual(["first:start", "first:end", "second"]); + }); +}); + +describe("HarnessEventBus", () => { + it("buffers between snapshot and start, then delivers each event once in order", async () => { + const bus = new HarnessEventBus(); + const watcher = bus.watch({ tipId: null }, () => true, BACKGROUND_CONTEXT); + await bus.emit({ type: "run_start", runId: "one", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + const seen: string[] = []; + watcher.start((event) => { + seen.push(`${event.type}:${"runId" in event ? event.runId : ""}`); + }); + await bus.emit({ type: "run_start", runId: "two", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(watcher.snapshot).toEqual({ tipId: null }); + expect(seen).toEqual(["run_start:one", "run_start:two"]); + watcher.unsubscribe(); + await bus.emit({ type: "run_start", runId: "three", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + expect(seen).toHaveLength(2); + }); + + it("drops pre-snapshot delivery and holds later events when resnapshotting inside a listener", async () => { + const bus = new HarnessEventBus(); + const listenerStarted = deferred(); + const releaseListener = deferred(); + const resnapshotDone = deferred(); + const watcher = bus.watch( + { version: "old" }, + () => true, + BACKGROUND_CONTEXT, + async (_context, markBoundary) => { + markBoundary(); + return { version: "fresh" }; + }, + ); + const queueEvents: string[] = []; + watcher.start(async (event, context) => { + if (event.type === "run_start" && event.runId === "blocking") { + listenerStarted.resolve(); + await releaseListener.promise; + } else if (event.type === "navigation_end") { + await watcher.resnapshot(context); + resnapshotDone.resolve(); + } else if (event.type === "queue_update") { + queueEvents.push(event.queues[0]?.entryId ?? "empty"); + } + }); + await bus.emit({ type: "run_start", runId: "blocking", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + await listenerStarted.promise; + const queued = bus.emitBatch( + [ + { + type: "navigation_end", + runId: "navigation", + status: "completed", + fromTipId: null, + tipId: null, + endedAt: 2, + lane: "main", + }, + { + type: "queue_update", + queues: [ + { + entryId: "stale", + kind: "nextRun", + type: "message", + message: { role: "user", content: "stale", timestamp: 2 }, + }, + ], + lane: "main", + }, + ], + BACKGROUND_CONTEXT, + ); + releaseListener.resolve(); + await Promise.all([queued, resnapshotDone.promise]); + + expect(watcher.snapshot).toEqual({ version: "fresh" }); + expect(queueEvents).toEqual([]); + await bus.emit( + { + type: "queue_update", + queues: [ + { + entryId: "later", + kind: "nextRun", + type: "message", + message: { role: "user", content: "later", timestamp: 3 }, + }, + ], + lane: "main", + }, + BACKGROUND_CONTEXT, + ); + await expect.poll(() => queueEvents).toEqual(["later"]); + }); + + it("isolates each listener from payload mutation", async () => { + const bus = new HarnessEventBus(); + let observed: string[] = []; + bus.on("config_update", (event) => { + if (event.property === "activeTools") event.value.push("mutated"); + }); + bus.on("config_update", (event) => { + if (event.property === "activeTools") observed = event.value; + }); + await bus.emit( + { + type: "config_update", + property: "activeTools", + value: ["read"], + previous: [], + lane: "main", + }, + BACKGROUND_CONTEXT, + ); + expect(observed).toEqual(["read"]); + }); + + it("serializes concurrent publications in process order", async () => { + const bus = new HarnessEventBus(); + const started = deferred(); + const release = deferred(); + const seen: string[] = []; + bus.on("run_start", async (event) => { + seen.push(`${event.runId}:start`); + if (event.runId === "one") { + started.resolve(); + await release.promise; + } + seen.push(`${event.runId}:end`); + }); + + const one = bus.emit({ type: "run_start", runId: "one", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + await started.promise; + const two = bus.emit({ type: "run_start", runId: "two", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(seen).toEqual(["one:start"]); + release.resolve(); + await Promise.all([one, two]); + expect(seen).toEqual(["one:start", "one:end", "two:start", "two:end"]); + }); + + it("keeps concurrent batches contiguous with their emitting contexts", async () => { + const bus = new HarnessEventBus(); + const sourceKey = createContextKey("event.batch.source"); + const firstContext = withContextValue(sourceKey, "first", BACKGROUND_CONTEXT); + const secondContext = withContextValue(sourceKey, "second", BACKGROUND_CONTEXT); + const seen: Array<{ runId: string; context: typeof firstContext }> = []; + bus.on("run_start", async (event, context) => { + seen.push({ runId: event.runId, context }); + await Promise.resolve(); + }); + + const first = bus.emitBatch( + [ + { type: "run_start", runId: "a1", startedAt: 1, lane: "main" }, + { type: "run_start", runId: "a2", startedAt: 1, lane: "main" }, + ], + firstContext, + ); + const second = bus.emitBatch( + [ + { type: "run_start", runId: "b1", startedAt: 1, lane: "worker" }, + { type: "run_start", runId: "b2", startedAt: 1, lane: "worker" }, + ], + secondContext, + ); + + await Promise.all([first, second]); + expect(seen.map(({ runId }) => runId)).toEqual(["a1", "a2", "b1", "b2"]); + expect(seen.slice(0, 2).every(({ context }) => context === firstContext)).toBe(true); + expect(seen.slice(2).every(({ context }) => context === secondContext)).toBe(true); + }); + + it("binds listeners and watchers when a batch is emitted", async () => { + const bus = new HarnessEventBus(); + const started = deferred(); + const release = deferred(); + bus.on("run_start", async (event) => { + if (event.runId !== "blocking") return; + started.resolve(); + await release.promise; + }); + const blocking = bus.emit( + { type: "run_start", runId: "blocking", startedAt: 1, lane: "main" }, + BACKGROUND_CONTEXT, + ); + await started.promise; + + const queued = bus.emit({ type: "run_start", runId: "queued", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + const lateListenerEvents: string[] = []; + bus.on("run_start", (event) => { + lateListenerEvents.push(event.runId); + }); + const lateWatcherEvents: string[] = []; + const lateWatcher = bus.watch({}, (event) => event.type === "run_start", BACKGROUND_CONTEXT); + lateWatcher.start((event) => { + if (event.type === "run_start") lateWatcherEvents.push(event.runId); + }); + + release.resolve(); + await Promise.all([blocking, queued]); + expect(lateListenerEvents).toEqual([]); + expect(lateWatcherEvents).toEqual([]); + + await bus.emit({ type: "run_start", runId: "later", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + expect(lateListenerEvents).toEqual(["later"]); + expect(lateWatcherEvents).toEqual(["later"]); + }); + + it("resolves an empty batch without delivery", async () => { + const bus = new HarnessEventBus(); + const listener = vi.fn(); + bus.on("run_start", listener); + + await bus.emitBatch([], BACKGROUND_CONTEXT); + + expect(listener).not.toHaveBeenCalled(); + }); + + it("drains already emitted contiguous batches during close and ignores later publication", async () => { + const bus = new HarnessEventBus(); + const started = deferred(); + const release = deferred(); + const seen: string[] = []; + bus.on("run_start", async (event) => { + seen.push(event.runId); + if (event.runId === "blocking") { + started.resolve(); + await release.promise; + } + }); + const blocking = bus.emit( + { type: "run_start", runId: "blocking", startedAt: 1, lane: "main" }, + BACKGROUND_CONTEXT, + ); + await started.promise; + const batch = bus.emitBatch( + [ + { type: "run_start", runId: "one", startedAt: 1, lane: "main" }, + { type: "run_start", runId: "two", startedAt: 1, lane: "main" }, + ], + BACKGROUND_CONTEXT, + ); + + bus.close(new Error("closed")); + await bus.emit({ type: "run_start", runId: "late", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + release.resolve(); + await Promise.all([blocking, batch]); + + expect(seen).toEqual(["blocking", "one", "two"]); + }); + + it("continues watcher delivery after listener failure and reports it", async () => { + const bus = new HarnessEventBus(); + const failures: string[] = []; + bus.on("handler_error", (event) => { + failures.push(event.error); + }); + const watcher = bus.watch({}, (event) => event.type === "run_start", BACKGROUND_CONTEXT); + const seen: string[] = []; + watcher.start((event) => { + if (event.type !== "run_start") return; + if (event.runId === "one") throw new Error("watcher failed"); + seen.push(event.runId); + }); + + await bus.emit({ type: "run_start", runId: "one", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + await bus.emit({ type: "run_start", runId: "two", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(seen).toEqual(["two"]); + expect(failures).toEqual(["watcher failed"]); + }); + + it("isolates listener failures and emits handler_error", async () => { + const bus = new HarnessEventBus(); + const failures: string[] = []; + bus.on("run_start", () => { + throw new Error("listener failed"); + }); + bus.on("handler_error", (event) => { + failures.push(event.error); + }); + await bus.emit({ type: "run_start", runId: "run", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + expect(failures).toEqual(["listener failed"]); + }); + + it("does not recurse when a handler_error listener fails", async () => { + const bus = new HarnessEventBus(); + let handlerErrors = 0; + bus.on("run_start", () => { + throw new Error("listener failed"); + }); + bus.on("handler_error", () => { + handlerErrors += 1; + throw new Error("error listener failed"); + }); + + await bus.emit({ type: "run_start", runId: "run", startedAt: 1, lane: "main" }, BACKGROUND_CONTEXT); + + expect(handlerErrors).toBe(1); + }); +}); diff --git a/packages/agent/test/harness/execution-tools.test.ts b/packages/agent/test/harness/execution-tools.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f15182ed42a8486f8c5642709239e8e97114252 --- /dev/null +++ b/packages/agent/test/harness/execution-tools.test.ts @@ -0,0 +1,247 @@ +import { Type } from "typebox"; +import { describe, expect, it, vi } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import { AbortRequested, createGate, type Gate } from "../../src/harness/execution/effect-gate.ts"; +import { + applyBeforeToolDecision, + createToolResultMessage, + executeToolCall, + finalizeToolCall, + prepareToolCall, +} from "../../src/harness/execution/tools.ts"; +import type { AgentHarnessTool } from "../../src/harness/types.ts"; +import type { AgentToolCall, AgentToolResult } from "../../src/types.ts"; + +const parameters = Type.Object({ value: Type.String() }); + +function call(arguments_: Record = { value: "input" }): AgentToolCall { + return { type: "toolCall", id: "call-1", name: "echo", arguments: arguments_ }; +} + +function tool( + overrides: Partial> = {}, +): AgentHarnessTool { + return { + name: "echo", + label: "Echo", + description: "Echo input", + parameters, + async execute(_toolCallId, args) { + return { + content: [{ type: "text", text: args.value }], + details: { value: args.value }, + }; + }, + ...overrides, + }; +} + +function text(result: AgentToolResult): string { + return result.content.flatMap((content) => (content.type === "text" ? [content.text] : [])).join("\n"); +} + +function isImmediate( + result: ReturnType | ReturnType, +): result is Extract, { kind: "immediate" }> { + return "kind" in result; +} + +function clearPrepared(callToClear: ReturnType) { + if (isImmediate(callToClear)) throw new Error("expected prepared call"); + const cleared = applyBeforeToolDecision(callToClear, undefined); + if (isImmediate(cleared)) throw new Error("expected cleared call"); + return cleared; +} + +function effectGate(): Gate { + return createGate().gate; +} + +const invocation = { + invocationId: "result-1", + operationId: "operation-1", + turnId: "turn-1", + getMemo: async () => undefined, + setMemo: async () => {}, +}; + +describe("tool execution primitives", () => { + it("prepares arguments before validation and preserves the provider call", () => { + const providerCall = call({ legacy: "prepared" }); + const prepared = prepareToolCall(providerCall, [ + tool({ + prepareArguments(args) { + return { value: (args as { legacy: string }).legacy }; + }, + }), + ]); + + expect(isImmediate(prepared)).toBe(false); + if (isImmediate(prepared)) return; + expect(prepared.toolCall).toBe(providerCall); + expect(prepared.args).toEqual({ value: "prepared" }); + expect(providerCall.arguments).toEqual({ legacy: "prepared" }); + }); + + it("returns immediate errors for unknown tools, preparation throws, and invalid arguments", () => { + const unknown = prepareToolCall(call(), []); + const preparationFailure = prepareToolCall(call(), [ + tool({ + prepareArguments() { + throw new Error("cannot prepare"); + }, + }), + ]); + const invalid = prepareToolCall(call({}), [tool()]); + + expect(isImmediate(unknown) ? text(unknown.result) : "").toBe('Tool "echo" is unavailable'); + expect(isImmediate(unknown) ? unknown.result.details : null).toBeUndefined(); + expect(isImmediate(preparationFailure) ? text(preparationFailure.result) : "").toBe("cannot prepare"); + expect(isImmediate(invalid) ? text(invalid.result) : "").toContain('Validation failed for tool "echo"'); + }); + + it("blocks calls and revalidates replacement arguments", () => { + const prepared = prepareToolCall(call(), [tool()]); + if (isImmediate(prepared)) throw new Error("expected prepared call"); + + const blocked = applyBeforeToolDecision(prepared, { + block: { reason: "denied", terminate: true }, + }); + const replaced = applyBeforeToolDecision(prepared, { args: { value: "replacement" } }); + const invalid = applyBeforeToolDecision(prepared, { args: {} }); + + expect(blocked).toMatchObject({ kind: "immediate", isError: true, terminate: true }); + expect(isImmediate(blocked) ? text(blocked.result) : "").toBe("denied"); + expect(isImmediate(replaced) ? undefined : replaced.args).toEqual({ value: "replacement" }); + expect(isImmediate(invalid)).toBe(true); + }); + + it("executes with updates, passes the signal, and ignores late updates", async () => { + const gate = effectGate(); + let lateUpdate: ((partial: AgentToolResult<{ value: string }>) => void) | undefined; + const execute: AgentHarnessTool["execute"] = vi.fn( + async (_id, args, onUpdate, _toolContext, _invocation, context) => { + expect(context.abortSignal).toBe(gate.signal); + onUpdate?.({ content: [{ type: "text", text: "partial" }], details: { value: args.value } }); + lateUpdate = onUpdate; + return { content: [{ type: "text" as const, text: "done" }], details: { value: args.value } }; + }, + ); + const cleared = clearPrepared(prepareToolCall(call(), [tool({ execute })])); + const updates: AgentToolResult[] = []; + + const result = await executeToolCall( + cleared, + gate, + (update) => updates.push(update), + undefined, + invocation, + BACKGROUND_CONTEXT, + ); + lateUpdate?.({ content: [{ type: "text", text: "late" }], details: { value: "late" } }); + + expect(vi.mocked(execute)).toHaveBeenCalledOnce(); + expect(result.isError).toBe(false); + expect(text(result.result)).toBe("done"); + expect(updates).toHaveLength(1); + expect(text(updates[0])).toBe("partial"); + }); + + it.each([ + [ + "synchronous", + () => { + throw new Error("tool failed"); + }, + ], + [ + "asynchronous", + async () => { + throw new Error("tool failed"); + }, + ], + ])("converts %s tool throws to error output", async (_kind, execute) => { + const cleared = clearPrepared(prepareToolCall(call(), [tool({ execute })])); + + const result = await executeToolCall(cleared, effectGate(), () => {}, undefined, invocation, BACKGROUND_CONTEXT); + + expect(result.isError).toBe(true); + expect(text(result.result)).toBe("tool failed"); + }); + + it("lets abort-first gate refusal escape without invoking the tool", async () => { + const execute = vi.fn(tool().execute); + const cleared = clearPrepared(prepareToolCall(call(), [tool({ execute })])); + const { gate, control } = createGate(); + control.beginAbort(Promise.resolve()); + + expect(() => executeToolCall(cleared, gate, () => {}, undefined, invocation, BACKGROUND_CONTEXT)).toThrow( + AbortRequested, + ); + expect(execute).not.toHaveBeenCalled(); + }); + + it("applies patches field by field and constructs the tool-result message", () => { + const cleared = clearPrepared(prepareToolCall(call(), [tool()])); + const originalUsage = { + input: 1, + output: 2, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 3, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }; + const replacementUsage = { ...originalUsage, input: 5, totalTokens: 7 }; + const executed: AgentToolResult = { + content: [{ type: "text", text: "original" }], + details: { original: true }, + usage: originalUsage, + addedToolNames: ["new-tool"], + }; + + const finalized = finalizeToolCall( + cleared, + { result: executed, isError: true }, + { + content: [{ type: "text", text: "patched" }], + details: { patched: true }, + usage: replacementUsage, + isError: false, + terminate: true, + }, + ); + const before = Date.now(); + const message = createToolResultMessage(finalized); + + expect(finalized).toMatchObject({ isError: false, terminate: true }); + expect(finalized.result).toMatchObject({ + content: [{ type: "text", text: "patched" }], + details: { patched: true }, + usage: replacementUsage, + addedToolNames: ["new-tool"], + terminate: true, + }); + expect(message).toMatchObject({ + role: "toolResult", + toolCallId: "call-1", + toolName: "echo", + content: [{ type: "text", text: "patched" }], + details: { patched: true }, + usage: replacementUsage, + addedToolNames: ["new-tool"], + isError: false, + }); + expect(message.timestamp).toBeGreaterThanOrEqual(before); + }); + + it("normalizes missing content from untyped tools", () => { + const cleared = clearPrepared(prepareToolCall(call(), [tool()])); + const finalized = finalizeToolCall( + cleared, + { result: { content: undefined, details: {} } as never, isError: false }, + undefined, + ); + + expect(createToolResultMessage(finalized).content).toEqual([]); + }); +}); diff --git a/packages/agent/test/harness/gating-storage.test.ts b/packages/agent/test/harness/gating-storage.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa00fff0367e4215b97b8c229c064f20fa7f625a --- /dev/null +++ b/packages/agent/test/harness/gating-storage.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT, type Context } from "../../src/harness/context.ts"; +import { MemoryStorage } from "../../src/harness/session/memory.ts"; +import { CommitDiscarded, GatingStorage, InstrumentedStorage } from "../../src/harness/session/testing/index.ts"; +import type { CommitResult, Write } from "../../src/harness/session/types.ts"; +import * as storedValues from "../../src/harness/session/values.ts"; +import { deferred } from "./runtime/test-utils.ts"; + +class ControlledLandingStorage extends MemoryStorage { + readonly started = deferred(); + readonly release = deferred(); + + override async commit(writes: Write[], context: Context): Promise { + this.started.resolve(); + await this.release.promise; + return super.commit(writes, context); + } +} + +describe("GatingStorage", () => { + it("bypasses setup writes until armed and waits for commits parked after waitPending", async () => { + const storage = new GatingStorage(new MemoryStorage({ now: () => 10 })); + await storage.commit([storedValues.setValue(storedValues.sessionName, "setup")], BACKGROUND_CONTEXT); + expect(storage.pending()).toBe(0); + + storage.arm(); + let waitingResolved = false; + const waiting = storage.waitPending().then(() => { + waitingResolved = true; + }); + await Promise.resolve(); + expect(waitingResolved).toBe(false); + const commit = storage.commit([storedValues.setValue(storedValues.sessionName, "parked")], BACKGROUND_CONTEXT); + await waiting; + expect(storage.pending()).toBe(1); + expect((await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.value).toBe("setup"); + + await storage.next(); + await commit; + expect(storage.pending()).toBe(0); + expect((await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.value).toBe("parked"); + await storage.close(BACKGROUND_CONTEXT); + }); + + it("releases in FIFO order and next resolves only after the backend write lands", async () => { + const delegate = new ControlledLandingStorage({ now: () => 10 }); + const storage = new GatingStorage(delegate); + storage.arm(); + const first = storage.commit([storedValues.setValue(storedValues.sessionName, "first")], BACKGROUND_CONTEXT); + const second = storage.commit([storedValues.setValue(storedValues.sessionName, "second")], BACKGROUND_CONTEXT); + await storage.waitPending(2); + expect(storage.pending()).toBe(2); + + let released = false; + const next = storage.next().then(() => { + released = true; + }); + await delegate.started.promise; + await Promise.resolve(); + expect(released).toBe(false); + expect(storage.pending()).toBe(1); + delegate.release.resolve(); + await next; + await first; + expect(released).toBe(true); + expect((await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.value).toBe("first"); + + await storage.next(); + await second; + expect((await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.value).toBe("second"); + await storage.close(BACKGROUND_CONTEXT); + }); + + it("permanently rejects parked, waiting, and later commits after discard", async () => { + const storage = new GatingStorage(new MemoryStorage()); + storage.arm(); + const waiting = storage.waitPending(2); + const parked = storage.commit([storedValues.setValue(storedValues.sessionName, "lost")], BACKGROUND_CONTEXT); + await storage.waitPending(); + expect(storage.pending()).toBe(1); + + storage.discard(); + expect(storage.pending()).toBe(0); + await expect(parked).rejects.toBeInstanceOf(CommitDiscarded); + await expect(waiting).rejects.toBeInstanceOf(CommitDiscarded); + await expect(storage.next()).rejects.toBeInstanceOf(CommitDiscarded); + await expect(storage.commit([], BACKGROUND_CONTEXT)).rejects.toBeInstanceOf(CommitDiscarded); + await storage.close(BACKGROUND_CONTEXT); + + const unarmed = new GatingStorage(new MemoryStorage()); + unarmed.discard(); + await expect(unarmed.commit([], BACKGROUND_CONTEXT)).rejects.toBeInstanceOf(CommitDiscarded); + await unarmed.close(BACKGROUND_CONTEXT); + }); + + it("records attempts before gating parks them", async () => { + const gating = new GatingStorage(new MemoryStorage()); + const storage = new InstrumentedStorage(gating); + gating.arm(); + const writes = [storedValues.setValue(storedValues.sessionName, "recorded")]; + + const commit = storage.commit(writes, BACKGROUND_CONTEXT); + expect(storage.getCommitAttempts()).toEqual([writes]); + await gating.waitPending(); + expect(gating.pending()).toBe(1); + await gating.next(); + await commit; + await storage.close(BACKGROUND_CONTEXT); + }); +}); diff --git a/packages/agent/test/harness/instrumented-storage.test.ts b/packages/agent/test/harness/instrumented-storage.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6561ce60b8f64937352e9c023454f246609b7490 --- /dev/null +++ b/packages/agent/test/harness/instrumented-storage.test.ts @@ -0,0 +1,190 @@ +import { describe, expect, it, vi } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import * as sessionWrites from "../../src/harness/session/commit.ts"; +import { MemoryStorage } from "../../src/harness/session/memory.ts"; +import { InstrumentedStorage } from "../../src/harness/session/testing/index.ts"; +import type { CommitResult, SessionStats, Write } from "../../src/harness/session/types.ts"; +import * as storedValues from "../../src/harness/session/values.ts"; + +const EMPTY_STATS: SessionStats = { + messageCount: 0, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, +}; + +class ControlledCommitStorage extends MemoryStorage { + private readonly pending: Array<{ + resolve: (result: CommitResult) => void; + reject: (error: unknown) => void; + }> = []; + private latestCommit: Promise | undefined; + + override commit(_transaction: Write[]): Promise { + this.latestCommit = new Promise((resolve, reject) => { + this.pending.push({ resolve, reject }); + }); + return this.latestCommit; + } + + get admissionCount(): number { + return this.pending.length; + } + + get lastCommit(): Promise | undefined { + return this.latestCommit; + } + + resolveNextCommit(result: CommitResult): void { + const pending = this.pending.shift(); + if (pending === undefined) throw new Error("No pending commit"); + pending.resolve(result); + } + + rejectNextCommit(error: unknown): void { + const pending = this.pending.shift(); + if (pending === undefined) throw new Error("No pending commit"); + pending.reject(error); + } +} + +describe("InstrumentedStorage", () => { + it("records commit attempts synchronously in admission order before settlement", async () => { + const delegate = new ControlledCommitStorage(); + const storage = new InstrumentedStorage(delegate); + const firstTransaction: Write[] = [storedValues.setValue(storedValues.sessionName, "first")]; + const secondTransaction: Write[] = [storedValues.setValue(storedValues.sessionName, "second")]; + + const firstCommit = storage.commit(firstTransaction, BACKGROUND_CONTEXT); + expect(firstCommit).toBe(delegate.lastCommit); + expect(storage.getCommitAttempts()).toEqual([firstTransaction]); + const secondCommit = storage.commit(secondTransaction, BACKGROUND_CONTEXT); + expect(secondCommit).toBe(delegate.lastCommit); + expect(storage.getCommitAttempts()).toEqual([firstTransaction, secondTransaction]); + + const firstResult = { firstSeq: 1, seqs: [1], timestamp: 10, stats: EMPTY_STATS }; + delegate.resolveNextCommit(firstResult); + expect(await firstCommit).toBe(firstResult); + expect(storage.getCommitAttempts()).toEqual([firstTransaction, secondTransaction]); + const secondResult = { firstSeq: 2, seqs: [2], timestamp: 20, stats: EMPTY_STATS }; + delegate.resolveNextCommit(secondResult); + expect(await secondCommit).toBe(secondResult); + await storage.close(BACKGROUND_CONTEXT); + }); + it("records the transaction reference passed to the delegate", async () => { + const delegate = new ControlledCommitStorage(); + const storage = new InstrumentedStorage(delegate); + const transaction: Write[] = [storedValues.setValue(storedValues.sessionName, "value")]; + + const commit = storage.commit(transaction, BACKGROUND_CONTEXT); + expect(storage.getCommitAttempts()[0]).toBe(transaction); + delegate.resolveNextCommit({ firstSeq: 1, seqs: [1], timestamp: 10, stats: EMPTY_STATS }); + await commit; + await storage.close(BACKGROUND_CONTEXT); + }); + + it("clears recorded attempts between phases without affecting the delegate", async () => { + const delegate = new MemoryStorage({ now: () => 100 }); + const storage = new InstrumentedStorage(delegate); + await storage.commit([storedValues.setValue(storedValues.sessionName, "first")], BACKGROUND_CONTEXT); + + storage.clearCommitAttempts(); + expect(storage.getCommitAttempts()).toEqual([]); + expect(await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toMatchObject({ value: "first" }); + + const secondTransaction: Write[] = [storedValues.setValue(storedValues.sessionName, "second")]; + await storage.commit(secondTransaction, BACKGROUND_CONTEXT); + expect(storage.getCommitAttempts()).toEqual([secondTransaction]); + await storage.close(BACKGROUND_CONTEXT); + }); + + it("delegates every read and query without recording synthetic writes", async () => { + const delegate = new MemoryStorage({ now: () => 100 }); + const storage = new InstrumentedStorage(delegate); + const events = storedValues.list("test.events"); + await storage.commit( + [ + sessionWrites.insertEntry({ id: "root", parentId: null, type: "custom", customType: "note" }), + storedValues.setValue(storedValues.sessionName, "session"), + storedValues.appendList(events, "event"), + sessionWrites.insertUsage({ + id: "usage", + adjustment: false, + usage: { + input: 1, + output: 2, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 3, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + }), + ], + BACKGROUND_CONTEXT, + ); + + expect(await storage.getEntries(["root"], BACKGROUND_CONTEXT)).toEqual( + await delegate.getEntries(["root"], BACKGROUND_CONTEXT), + ); + expect(await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toEqual( + await delegate.getValue(storedValues.sessionName, BACKGROUND_CONTEXT), + ); + expect(await storage.scanValues(storedValues.sessionName, BACKGROUND_CONTEXT)).toEqual( + await delegate.scanValues(storedValues.sessionName, BACKGROUND_CONTEXT), + ); + expect(await storage.readList(events, undefined, BACKGROUND_CONTEXT)).toEqual( + await delegate.readList(events, undefined, BACKGROUND_CONTEXT), + ); + expect(await storage.scanBranch({ start: "root" }, BACKGROUND_CONTEXT)).toEqual( + await delegate.scanBranch({ start: "root" }, BACKGROUND_CONTEXT), + ); + expect(await storage.scanBranchStructure({ start: "root" }, BACKGROUND_CONTEXT)).toEqual( + await delegate.scanBranchStructure({ start: "root" }, BACKGROUND_CONTEXT), + ); + expect(await storage.scanEntries({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual( + await delegate.scanEntries({ order: "asc" }, BACKGROUND_CONTEXT), + ); + expect(await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual( + await delegate.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT), + ); + expect(await storage.getStats(BACKGROUND_CONTEXT)).toEqual(await delegate.getStats(BACKGROUND_CONTEXT)); + expect(storage.getCommitAttempts()).toHaveLength(1); + await storage.close(BACKGROUND_CONTEXT); + }); + + it("records list appends without reading the target list", async () => { + const delegate = new MemoryStorage({ now: () => 100 }); + const readList = vi.spyOn(delegate, "readList"); + const storage = new InstrumentedStorage(delegate); + const events = storedValues.list("test.events"); + + await storage.commit([storedValues.appendList(events, "event")], BACKGROUND_CONTEXT); + + expect(readList).not.toHaveBeenCalled(); + expect(storage.getCommitAttempts()).toEqual([ + [{ kind: "list", op: "append", namespace: "test.events", key: "", value: "event" }], + ]); + await storage.close(BACKGROUND_CONTEXT); + }); + + it("delegates close idempotence and admitted commit draining", async () => { + const delegate = new MemoryStorage({ now: () => 100 }); + const storage = new InstrumentedStorage(delegate); + const admitted = storage.commit( + [storedValues.setValue(storedValues.sessionName, "admitted")], + BACKGROUND_CONTEXT, + ); + + const firstClose = storage.close(BACKGROUND_CONTEXT); + const secondClose = storage.close(BACKGROUND_CONTEXT); + await admitted; + await Promise.all([firstClose, secondClose]); + await expect(storage.getStats(BACKGROUND_CONTEXT)).rejects.toThrow("MemoryStorage is closed"); + expect(storage.getCommitAttempts()).toHaveLength(1); + }); +}); diff --git a/packages/agent/test/harness/jsonl-io.test.ts b/packages/agent/test/harness/jsonl-io.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..35aa6c42d575b65f187b834744c84a2ad26b975c --- /dev/null +++ b/packages/agent/test/harness/jsonl-io.test.ts @@ -0,0 +1,108 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts"; +import { publishFileAtomically, publishJsonl } from "../../src/harness/session/jsonl/io.ts"; +import type { JsonlStorageHeader } from "../../src/harness/session/jsonl/types.ts"; +import { sessionName, setValue } from "../../src/harness/session/values.ts"; +import { err, FileError } from "../../src/harness/types.ts"; + +let root: string; +let path: string; +let fileSystem: NodeExecutionEnv; + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "pi-jsonl-io-")); + path = join(root, "session.jsonl"); + fileSystem = new NodeExecutionEnv({ cwd: root }); +}); + +afterEach(async () => { + vi.restoreAllMocks(); + await rm(root, { recursive: true, force: true }); +}); + +describe("atomic file publication", () => { + it("keeps the destination unchanged until all content has been written", async () => { + await writeFile(path, "original"); + + await publishFileAtomically(fileSystem, path, BACKGROUND_CONTEXT, async (append) => { + await append("first\n"); + expect(await readFile(`${path}.tmp`, "utf8")).toBe("first\n"); + expect(await readFile(path, "utf8")).toBe("original"); + await append("second\n"); + expect(await readFile(path, "utf8")).toBe("original"); + }); + + expect(await readFile(path, "utf8")).toBe("first\nsecond\n"); + await expect(readFile(`${path}.tmp`)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("discards partial content and preserves the original error when the callback fails", async () => { + await writeFile(path, "original"); + const failure = new Error("content generation failed"); + + await expect( + publishFileAtomically(fileSystem, path, BACKGROUND_CONTEXT, async (append) => { + await append("partial"); + throw failure; + }), + ).rejects.toBe(failure); + + expect(await readFile(path, "utf8")).toBe("original"); + await expect(readFile(`${path}.tmp`)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it.each(["writeFile", "appendFile", "renameFile"] as const)( + "preserves the destination and allows retry after %s fails", + async (method) => { + await writeFile(path, "original"); + const failure = new FileError("unknown", "injected I/O failure", path); + vi.spyOn(fileSystem, method).mockResolvedValueOnce(err(failure)); + + await expect( + publishFileAtomically(fileSystem, path, BACKGROUND_CONTEXT, (append) => append("replacement")), + ).rejects.toMatchObject({ cause: failure }); + + expect(await readFile(path, "utf8")).toBe("original"); + await expect(readFile(`${path}.tmp`)).rejects.toMatchObject({ code: "ENOENT" }); + + await publishFileAtomically(fileSystem, path, BACKGROUND_CONTEXT, (append) => append("retry")); + expect(await readFile(path, "utf8")).toBe("retry"); + }, + ); +}); + +describe("JSONL publication", () => { + const header: JsonlStorageHeader = { + v: 4, + kind: "header", + id: "session", + storageVersion: 1, + createdAt: 1_700_000_000_000, + cwd: "/workspace", + nextSeq: 4, + }; + + it("writes the header first and preserves single-write and multi-write transaction boundaries", async () => { + const first = { ...setValue(sessionName, "first"), seq: 1 }; + const second = { ...setValue(sessionName, "second"), seq: 2 }; + const third = { ...setValue(sessionName, "third"), seq: 3 }; + + await publishJsonl(fileSystem, path, header, BACKGROUND_CONTEXT, async (append) => { + await append([first]); + await append([second, third]); + }); + + expect(await readFile(path, "utf8")).toBe( + [JSON.stringify(header), JSON.stringify(first), JSON.stringify([second, third]), ""].join("\n"), + ); + }); + + it("publishes a header-only file when the callback emits no transactions", async () => { + await publishJsonl(fileSystem, path, header, BACKGROUND_CONTEXT, async () => {}); + expect(await readFile(path, "utf8")).toBe(`${JSON.stringify(header)}\n`); + }); +}); diff --git a/packages/agent/test/harness/jsonl-session-repo-conformance.test.ts b/packages/agent/test/harness/jsonl-session-repo-conformance.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..782ba14e8b41ff40bfbe10b675ebd9b7419e479e --- /dev/null +++ b/packages/agent/test/harness/jsonl-session-repo-conformance.test.ts @@ -0,0 +1,65 @@ +import { describe, it } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts"; +import { type JsonlSessionMetadata, JsonlSessionRepo } from "../../src/harness/session/jsonl/index.ts"; +import { + type ConformanceCase, + createSessionRepoForkBehaviorConformance, + createSessionRepoForkSourceSnapshotConformance, + createSessionRepoLifecycleConformance, + createSessionRepoMessageConformance, + createSessionRepoOwnershipConformance, + createSessionRepoStreamingForkConformance, +} from "../../src/harness/session/testing/index.ts"; +import type { ForkOptions } from "../../src/harness/session/types.ts"; +import { createTempDir } from "./session-test-utils.ts"; + +const NOW = 1_700_000_000_000; +const CONFORMANCE_CWD = "/workspace"; + +function registerConformance(name: string, cases: readonly ConformanceCase[]): void { + describe(name, () => { + for (const group of new Set(cases.map((testCase) => testCase.group))) { + describe(group, () => { + for (const testCase of cases.filter((candidate) => candidate.group === group)) { + it(testCase.name, () => testCase.run()); + } + }); + } + }); +} + +let jsonlRepo: JsonlSessionRepo; +async function createConformanceRepo() { + const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() }); + jsonlRepo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW }); + return { + create: (options: { id?: string; parentSessionId?: string }) => + jsonlRepo.create({ ...options, cwd: CONFORMANCE_CWD }, BACKGROUND_CONTEXT), + open: (metadata: JsonlSessionMetadata) => jsonlRepo.open(metadata, BACKGROUND_CONTEXT), + list: () => jsonlRepo.list({ cwd: CONFORMANCE_CWD }, BACKGROUND_CONTEXT), + delete: (metadata: JsonlSessionMetadata) => jsonlRepo.delete(metadata, BACKGROUND_CONTEXT), + fork: (source: JsonlSessionMetadata, options: ForkOptions) => jsonlRepo.fork(source, options, BACKGROUND_CONTEXT), + }; +} + +registerConformance("JsonlSessionRepo conformance", [ + ...createSessionRepoLifecycleConformance(createConformanceRepo, () => + jsonlRepo.close(BACKGROUND_CONTEXT), + ), + ...createSessionRepoOwnershipConformance(createConformanceRepo, () => + jsonlRepo.close(BACKGROUND_CONTEXT), + ), + ...createSessionRepoMessageConformance(createConformanceRepo, () => + jsonlRepo.close(BACKGROUND_CONTEXT), + ), + ...createSessionRepoForkBehaviorConformance(createConformanceRepo, () => + jsonlRepo.close(BACKGROUND_CONTEXT), + ), + ...createSessionRepoStreamingForkConformance(createConformanceRepo, () => + jsonlRepo.close(BACKGROUND_CONTEXT), + ), + ...createSessionRepoForkSourceSnapshotConformance(createConformanceRepo, () => + jsonlRepo.close(BACKGROUND_CONTEXT), + ), +]); diff --git a/packages/agent/test/harness/jsonl-session-repo.test.ts b/packages/agent/test/harness/jsonl-session-repo.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..33cf05887a15cfa6f02667bae63edd2c17f6a9c1 --- /dev/null +++ b/packages/agent/test/harness/jsonl-session-repo.test.ts @@ -0,0 +1,199 @@ +import { describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT, type Context } from "../../src/harness/context.ts"; +import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts"; +import { JSONL_STORAGE_VERSION, JsonlSessionRepo } from "../../src/harness/session/jsonl/index.ts"; +import { sessionName, setValue } from "../../src/harness/session/values.ts"; +import { getOrThrow } from "../../src/harness/types.ts"; +import { createTempDir } from "./session-test-utils.ts"; + +const NOW = 1_700_000_000_000; + +class AtomicPublicationNodeExecutionEnv extends NodeExecutionEnv { + publication: + | { sourcePath: string; destinationPath: string; destinationExisted: boolean; stagedContent: string } + | undefined; + + override async renameFile(sourcePath: string, destinationPath: string, context: Context) { + const destinationExists = await super.exists(destinationPath, context); + const stagedContent = await super.readTextFile(sourcePath, context); + if (destinationExists.ok && stagedContent.ok) { + this.publication = { + sourcePath, + destinationPath, + destinationExisted: destinationExists.value, + stagedContent: stagedContent.value, + }; + } + return super.renameFile(sourcePath, destinationPath, context); + } +} + +describe("JsonlSessionRepo cwd-scoped lifecycle", () => { + it("persists metadata and filters discovery by cwd", async () => { + const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() }); + const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW }); + const session = await repo.create( + { id: "child", cwd: "/workspace", parentSessionId: "parent" }, + BACKGROUND_CONTEXT, + ); + const metadata = session.metadata; + + expect(metadata).toMatchObject({ + id: "child", + createdAt: NOW, + storageVersion: JSONL_STORAGE_VERSION, + cwd: "/workspace", + parentSessionId: "parent", + }); + expect(metadata.path).toContain("/sessions/--workspace--/"); + expect(metadata.path.endsWith("_child.jsonl")).toBe(true); + expect(Number.isFinite(metadata.modifiedAt)).toBe(true); + await session.close(BACKGROUND_CONTEXT); + + expect(await repo.list({ cwd: "/other" }, BACKGROUND_CONTEXT)).toEqual([]); + expect(await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT)).toEqual([metadata]); + const firstLine = getOrThrow( + await fileSystem.readTextLines(metadata.path, { maxLines: 1 }, BACKGROUND_CONTEXT), + )[0]; + expect(JSON.parse(firstLine!)).toEqual({ + v: 4, + kind: "header", + id: "child", + storageVersion: JSONL_STORAGE_VERSION, + createdAt: NOW, + cwd: "/workspace", + parentSessionId: "parent", + }); + await repo.close(BACKGROUND_CONTEXT); + }); + + it("atomically publishes a branchless session header", async () => { + const fileSystem = new AtomicPublicationNodeExecutionEnv({ cwd: createTempDir() }); + const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW }); + const session = await repo.create({ id: "session", cwd: "/workspace" }, BACKGROUND_CONTEXT); + + const publication = fileSystem.publication; + if (publication === undefined) throw new Error("Expected atomic session publication"); + expect(publication.destinationPath).toBe(session.metadata.path); + expect(publication.destinationExisted).toBe(false); + const lines = publication.stagedContent.trimEnd().split("\n"); + expect(lines).toHaveLength(1); + expect(JSON.parse(lines[0]!)).toMatchObject({ kind: "header", id: "session" }); + expect(getOrThrow(await fileSystem.readTextFile(session.metadata.path, BACKGROUND_CONTEXT))).toBe( + publication.stagedContent, + ); + expect(getOrThrow(await fileSystem.exists(publication.sourcePath, BACKGROUND_CONTEXT))).toBe(false); + + await session.close(BACKGROUND_CONTEXT); + await repo.close(BACKGROUND_CONTEXT); + }); + + it("keeps an explicit Session mutation through commit until end", async () => { + const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() }); + const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW }); + const session = await repo.create({ id: "session", cwd: "/workspace" }, BACKGROUND_CONTEXT); + const mutation = await session.beginMutation(BACKGROUND_CONTEXT); + let queuedStarted = false; + const queued = session.mutate(() => { + queuedStarted = true; + }, BACKGROUND_CONTEXT); + + const result = await mutation.commit([setValue(sessionName, "explicit")], BACKGROUND_CONTEXT); + expect(result.seqs).toHaveLength(1); + expect(queuedStarted).toBe(false); + expect(await mutation.getValue(sessionName, BACKGROUND_CONTEXT)).toMatchObject({ value: "explicit" }); + await mutation.end(BACKGROUND_CONTEXT); + await queued; + expect(queuedStarted).toBe(true); + + await session.close(BACKGROUND_CONTEXT); + const reopened = await repo.open(session.metadata, BACKGROUND_CONTEXT); + expect(await reopened.getName(BACKGROUND_CONTEXT)).toBe("explicit"); + await reopened.close(BACKGROUND_CONTEXT); + await repo.close(BACKGROUND_CONTEXT); + }); + + it("rejects unsupported storage versions without repairing a torn tail", async () => { + const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() }); + const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW }); + const session = await repo.create({ id: "future", cwd: "/workspace" }, BACKGROUND_CONTEXT); + const metadata = session.metadata; + await session.close(BACKGROUND_CONTEXT); + + const lines = getOrThrow(await fileSystem.readTextFile(metadata.path, BACKGROUND_CONTEXT)) + .trimEnd() + .split("\n"); + const unsupportedVersion = JSONL_STORAGE_VERSION + 1; + lines[0] = JSON.stringify({ ...JSON.parse(lines[0]!), storageVersion: unsupportedVersion }); + const unsupportedContent = `${lines.join("\n")}\n{"kind":"entry"`; + getOrThrow(await fileSystem.writeFile(metadata.path, unsupportedContent, BACKGROUND_CONTEXT)); + + await expect(repo.open(metadata, BACKGROUND_CONTEXT)).rejects.toThrow( + `unsupported storage version ${unsupportedVersion}`, + ); + expect(getOrThrow(await fileSystem.readTextFile(metadata.path, BACKGROUND_CONTEXT))).toBe(unsupportedContent); + + await repo.close(BACKGROUND_CONTEXT); + }); + + it("keeps fork destinations claimed until close and rejects deleting open sessions", async () => { + const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() }); + const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW }); + const source = await repo.create({ id: "source", cwd: "/workspace" }, BACKGROUND_CONTEXT); + const fork = await repo.fork(source.metadata, { id: "fork", scope: "tree" }, BACKGROUND_CONTEXT); + + await expect(repo.open(fork.metadata, BACKGROUND_CONTEXT)).rejects.toThrow("already open"); + await expect(repo.delete(fork.metadata, BACKGROUND_CONTEXT)).rejects.toThrow("open"); + await fork.close(BACKGROUND_CONTEXT); + + const reopened = await repo.open(fork.metadata, BACKGROUND_CONTEXT); + await reopened.close(BACKGROUND_CONTEXT); + await repo.delete(fork.metadata, BACKGROUND_CONTEXT); + await expect(repo.open(fork.metadata, BACKGROUND_CONTEXT)).rejects.toThrow("does not exist"); + + await source.close(BACKGROUND_CONTEXT); + await repo.close(BACKGROUND_CONTEXT); + }); + + it("rejects concurrent creates for the same working-directory id", async () => { + const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() }); + const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW }); + + const results = await Promise.allSettled([ + repo.create({ id: "session", cwd: "/workspace" }, BACKGROUND_CONTEXT), + repo.create({ id: "session", cwd: "/workspace" }, BACKGROUND_CONTEXT), + ]); + + expect(results.filter((result) => result.status === "fulfilled")).toHaveLength(1); + expect(results.filter((result) => result.status === "rejected")).toHaveLength(1); + expect(await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT)).toHaveLength(1); + for (const result of results) { + if (result.status === "fulfilled") await result.value.close(BACKGROUND_CONTEXT); + } + await repo.close(BACKGROUND_CONTEXT); + }); + + it("allows the same id to be active in different working directories", async () => { + const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() }); + const repo = new JsonlSessionRepo({ fileSystem, sessionsRoot: "sessions", now: () => NOW }); + const first = await repo.create({ id: "shared", cwd: "/workspace-a" }, BACKGROUND_CONTEXT); + const second = await repo.create({ id: "shared", cwd: "/workspace-b" }, BACKGROUND_CONTEXT); + + expect(first.metadata.path).not.toBe(second.metadata.path); + await expect(repo.create({ id: "shared", cwd: "/workspace-a" }, BACKGROUND_CONTEXT)).rejects.toThrow( + "already exists", + ); + expect((await repo.list(undefined, BACKGROUND_CONTEXT)).map(({ cwd, id }) => ({ cwd, id }))).toEqual([ + { cwd: "/workspace-a", id: "shared" }, + { cwd: "/workspace-b", id: "shared" }, + ]); + + await Promise.all([first.close(BACKGROUND_CONTEXT), second.close(BACKGROUND_CONTEXT)]); + const reopened = await Promise.all([ + repo.open(first.metadata, BACKGROUND_CONTEXT), + repo.open(second.metadata, BACKGROUND_CONTEXT), + ]); + await Promise.all(reopened.map((session) => session.close(BACKGROUND_CONTEXT))); + await repo.close(BACKGROUND_CONTEXT); + }); +}); diff --git a/packages/agent/test/harness/jsonl-storage-conformance.test.ts b/packages/agent/test/harness/jsonl-storage-conformance.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..26535843b538de883437e1b5fc04b38d744669e9 --- /dev/null +++ b/packages/agent/test/harness/jsonl-storage-conformance.test.ts @@ -0,0 +1,48 @@ +import { describe, it } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts"; +import { JSONL_FORMAT_VERSION, JsonlStorage } from "../../src/harness/session/jsonl/index.ts"; +import { + type ConformanceCase, + createStorageConformance, + type StorageFixture, +} from "../../src/harness/session/testing/index.ts"; +import { createTempDir } from "./session-test-utils.ts"; + +const NOW = 1_700_000_000_000; + +function registerConformance(name: string, cases: readonly ConformanceCase[]): void { + describe(name, () => { + for (const group of new Set(cases.map((testCase) => testCase.group))) { + describe(group, () => { + for (const testCase of cases.filter((candidate) => candidate.group === group)) { + it(testCase.name, () => testCase.run()); + } + }); + } + }); +} + +registerConformance( + "JsonlStorage conformance", + createStorageConformance(async () => { + const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() }); + const storage = await JsonlStorage.create( + { fileSystem, path: "session.jsonl", now: () => NOW }, + { + v: JSONL_FORMAT_VERSION, + kind: "header", + id: "session", + storageVersion: 1, + createdAt: NOW, + cwd: "/workspace", + }, + [], + BACKGROUND_CONTEXT, + ); + return { + storage, + [Symbol.asyncDispose]: () => storage.close(BACKGROUND_CONTEXT), + } satisfies StorageFixture; + }), +); diff --git a/packages/agent/test/harness/jsonl-storage.test.ts b/packages/agent/test/harness/jsonl-storage.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..57e71999c885ab446d7c5ae2ff2b5fbfdf5647a2 --- /dev/null +++ b/packages/agent/test/harness/jsonl-storage.test.ts @@ -0,0 +1,248 @@ +import { describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts"; +import * as sessionWrites from "../../src/harness/session/commit.ts"; +import { JSONL_FORMAT_VERSION, JsonlStorage, type JsonlStorageHeader } from "../../src/harness/session/jsonl/index.ts"; +import * as storedValues from "../../src/harness/session/values.ts"; +import { getOrThrow } from "../../src/harness/types.ts"; +import { createTempDir } from "./session-test-utils.ts"; + +const NOW = 1_700_000_000_000; + +function header(id: string): JsonlStorageHeader { + return { + v: JSONL_FORMAT_VERSION, + kind: "header", + id, + storageVersion: 1, + createdAt: NOW, + cwd: "/workspace", + }; +} + +describe("JsonlStorage persistence", () => { + it("replays whole-list deletion without resurrecting earlier appends", async () => { + const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() }); + const options = { fileSystem, path: "list-delete.jsonl", now: () => NOW }; + const events = storedValues.list("test.events"); + const storage = await JsonlStorage.create(options, header("list-delete"), [], BACKGROUND_CONTEXT); + await storage.commit( + [storedValues.appendList(events, "first"), storedValues.appendList(events, "second")], + BACKGROUND_CONTEXT, + ); + await storage.commit([storedValues.deleteList(events)], BACKGROUND_CONTEXT); + await storage.close(BACKGROUND_CONTEXT); + + const reopened = await JsonlStorage.open(options, BACKGROUND_CONTEXT); + expect(await reopened.readList(events, undefined, BACKGROUND_CONTEXT)).toEqual([]); + const recreated = await reopened.commit([storedValues.appendList(events, "after")], BACKGROUND_CONTEXT); + expect(recreated.firstSeq).toBe(4); + expect(await reopened.readList(events, undefined, BACKGROUND_CONTEXT)).toEqual([{ seq: 4, value: "after" }]); + await reopened.close(BACKGROUND_CONTEXT); + }); + + it("writes one line per transaction and replays stamped state", async () => { + const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() }); + const options = { fileSystem, path: "session.jsonl", now: () => NOW }; + const storage = await JsonlStorage.create(options, header("round-trip"), [], BACKGROUND_CONTEXT); + const committed = await storage.commit( + [ + sessionWrites.insertEntry({ + id: "root", + parentId: null, + type: "message", + message: { role: "user", content: "hello", timestamp: 1 }, + }), + storedValues.setValue(storedValues.branchTip("main"), "root"), + sessionWrites.insertUsage({ + id: "usage", + entryId: "root", + adjustment: false, + usage: { + input: 1, + output: 2, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 3, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + }), + ], + BACKGROUND_CONTEXT, + ); + await storage.commit([storedValues.setValue(storedValues.sessionName, "name")], BACKGROUND_CONTEXT); + + const lines = getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT)) + .trimEnd() + .split("\n"); + expect(JSON.parse(lines[0]!)).toEqual(header("round-trip")); + expect(JSON.parse(lines[1]!)).toHaveLength(3); + expect(Array.isArray(JSON.parse(lines[2]!))).toBe(false); + await storage.close(BACKGROUND_CONTEXT); + + const reopened = await JsonlStorage.open(options, BACKGROUND_CONTEXT); + expect((await reopened.getEntries(["root"], BACKGROUND_CONTEXT)).get("root")).toEqual({ + id: "root", + parentId: null, + type: "message", + message: { role: "user", content: "hello", timestamp: 1 }, + seq: committed.seqs[0], + timestamp: committed.timestamp, + }); + expect(await reopened.getValue(storedValues.branchTip("main"), BACKGROUND_CONTEXT)).toEqual({ + address: storedValues.branchTip("main"), + value: "root", + seq: committed.seqs[1], + }); + expect( + (await reopened.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT)).map(({ id, seq }) => ({ id, seq })), + ).toEqual([{ id: "usage", seq: committed.seqs[2] }]); + const historicalStats = { + messageCount: 1, + usage: { + input: 1, + output: 2, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 3, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + }; + expect(await reopened.getStats(BACKGROUND_CONTEXT)).toEqual(historicalStats); + const next = await reopened.commit([], BACKGROUND_CONTEXT); + expect(next.firstSeq).toBe(5); + expect(next.stats).toEqual(historicalStats); + await reopened.close(BACKGROUND_CONTEXT); + }); +}); + +describe("JsonlStorage torn tail", () => { + function entryWrite(id: string) { + return sessionWrites.insertEntry({ + id, + parentId: null, + type: "message", + message: { role: "user", content: id, timestamp: 1 }, + }); + } + + async function seed() { + const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() }); + const options = { fileSystem, path: "session.jsonl" as const, now: () => NOW }; + const storage = await JsonlStorage.create(options, header("torn"), [], BACKGROUND_CONTEXT); + await storage.commit([entryWrite("kept")], BACKGROUND_CONTEXT); + await storage.close(BACKGROUND_CONTEXT); + const prefix = getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT)); + return { fileSystem, options, prefix }; + } + + it("discards an unterminated final object line and truncates before admitting writes", async () => { + const { fileSystem, options, prefix } = await seed(); + await fileSystem.appendFile( + "session.jsonl", + JSON.stringify({ + kind: "entry", + id: "torn", + parentId: null, + type: "message", + message: { role: "user", content: "torn", timestamp: 1 }, + seq: 2, + timestamp: NOW, + }), + BACKGROUND_CONTEXT, + ); + + const reopened = await JsonlStorage.open(options, BACKGROUND_CONTEXT); + expect((await reopened.getEntries(["kept", "torn"], BACKGROUND_CONTEXT)).has("torn")).toBe(false); + expect((await reopened.getEntries(["kept"], BACKGROUND_CONTEXT)).get("kept")?.id).toBe("kept"); + expect(getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))).toBe(prefix); + expect(getOrThrow(await fileSystem.exists("session.jsonl.tmp", BACKGROUND_CONTEXT))).toBe(false); + + const next = await reopened.commit([entryWrite("after")], BACKGROUND_CONTEXT); + expect(next.firstSeq).toBe(2); + expect((await reopened.getEntries(["after"], BACKGROUND_CONTEXT)).get("after")?.seq).toBe(2); + await reopened.close(BACKGROUND_CONTEXT); + }); + + it("discards a torn array line wholly, including list elements", async () => { + const { fileSystem, options, prefix } = await seed(); + const events = storedValues.list("test.events"); + await fileSystem.appendFile( + "session.jsonl", + JSON.stringify([ + { + kind: "entry", + id: "torn-a", + parentId: null, + type: "message", + message: { role: "user", content: "torn-a", timestamp: 1 }, + seq: 2, + timestamp: NOW, + }, + storedValues.setValue(storedValues.sessionName, "lost"), + storedValues.appendList(events, "lost"), + ]), + BACKGROUND_CONTEXT, + ); + + const reopened = await JsonlStorage.open(options, BACKGROUND_CONTEXT); + expect((await reopened.getEntries(["torn-a"], BACKGROUND_CONTEXT)).has("torn-a")).toBe(false); + expect(await reopened.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toBeUndefined(); + expect(await reopened.readList(events, undefined, BACKGROUND_CONTEXT)).toEqual([]); + expect(getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))).toBe(prefix); + await reopened.close(BACKGROUND_CONTEXT); + }); + + it("rejects a malformed interior line without rewriting", async () => { + const { fileSystem, options, prefix } = await seed(); + const corrupted = `${prefix}not-json\n${JSON.stringify(storedValues.setValue(storedValues.sessionName, "after"))}\n`; + await fileSystem.writeFile("session.jsonl", corrupted, BACKGROUND_CONTEXT); + + await expect(JsonlStorage.open(options, BACKGROUND_CONTEXT)).rejects.toThrow(/line 3/); + expect(getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))).toBe(corrupted); + expect(getOrThrow(await fileSystem.exists("session.jsonl.tmp", BACKGROUND_CONTEXT))).toBe(false); + }); + + it("rejects the unsupported pre-WP01 scalar record spelling", async () => { + const { fileSystem, options, prefix } = await seed(); + const legacyKind = ["reg", "ister"].join(""); + const corrupted = `${prefix}${JSON.stringify({ + kind: legacyKind, + op: "set", + seq: 2, + namespace: "legacy.value", + key: "state", + value: true, + })}\n`; + await fileSystem.writeFile("session.jsonl", corrupted, BACKGROUND_CONTEXT); + + await expect(JsonlStorage.open(options, BACKGROUND_CONTEXT)).rejects.toThrow(/line 3/); + expect(getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))).toBe(corrupted); + }); + + it("rejects a complete malformed final line without rewriting", async () => { + const { fileSystem, options, prefix } = await seed(); + const corrupted = `${prefix}not-json\n`; + await fileSystem.writeFile("session.jsonl", corrupted, BACKGROUND_CONTEXT); + + await expect(JsonlStorage.open(options, BACKGROUND_CONTEXT)).rejects.toThrow(/line 3/); + expect(getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))).toBe(corrupted); + }); + + it("rejects a complete final line with invalid transaction framing", async () => { + const { fileSystem, options, prefix } = await seed(); + const corrupted = `${prefix}${JSON.stringify({ kind: "nope", seq: 2 })}\n`; + await fileSystem.writeFile("session.jsonl", corrupted, BACKGROUND_CONTEXT); + + await expect(JsonlStorage.open(options, BACKGROUND_CONTEXT)).rejects.toThrow(/line 3/); + expect(getOrThrow(await fileSystem.readTextFile("session.jsonl", BACKGROUND_CONTEXT))).toBe(corrupted); + }); + + it("rejects an unterminated header", async () => { + const fileSystem = new NodeExecutionEnv({ cwd: createTempDir() }); + const options = { fileSystem, path: "session.jsonl", now: () => NOW }; + await fileSystem.writeFile("session.jsonl", JSON.stringify(header("torn")).slice(0, -4), BACKGROUND_CONTEXT); + + await expect(JsonlStorage.open(options, BACKGROUND_CONTEXT)).rejects.toThrow(/missing header/); + }); +}); diff --git a/packages/agent/test/harness/jsonl-v3-migration.test.ts b/packages/agent/test/harness/jsonl-v3-migration.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e11dffde699e5ac747b980c462f9ed116e559372 --- /dev/null +++ b/packages/agent/test/harness/jsonl-v3-migration.test.ts @@ -0,0 +1,2013 @@ +import type { Usage } from "@earendil-works/pi-ai"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT, type Context } from "../../src/harness/context.ts"; +import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts"; +import { + JSONL_FORMAT_VERSION, + JSONL_STORAGE_VERSION, + type JsonlSessionMetadata, + JsonlSessionRepo, + JsonlStorage, +} from "../../src/harness/session/jsonl/index.ts"; +import type { Entry, Session } from "../../src/harness/session/types.ts"; +import * as storedValues from "../../src/harness/session/values.ts"; +import { err, FileError, getOrThrow, type Result } from "../../src/harness/types.ts"; +import type { AgentMessage } from "../../src/types.ts"; +import { createTempDir } from "./session-test-utils.ts"; + +const NOW = 1_700_000_000_000; + +class FailableRenameNodeExecutionEnv extends NodeExecutionEnv { + failRename = false; + + override async renameFile( + sourcePath: string, + destinationPath: string, + context: Context, + ): Promise> { + if (this.failRename) { + return err(new FileError("unknown", "Injected rename failure", sourcePath)); + } + return super.renameFile(sourcePath, destinationPath, context); + } +} + +function uuidTimestamp(id: string): number { + return Number.parseInt(id.replaceAll("-", "").slice(0, 12), 16); +} + +async function mainBranch(session: Session) { + const branch = await session.branch("main", BACKGROUND_CONTEXT); + if (branch === undefined) throw new Error("Expected imported main Branch"); + return branch; +} + +async function mainTip(session: Session): Promise { + return (await mainBranch(session)).getTipId(BACKGROUND_CONTEXT); +} + +describe("JSONL v3 migration", () => { + let fileSystem: FailableRenameNodeExecutionEnv; + let repo: JsonlSessionRepo; + + beforeEach(() => { + fileSystem = new FailableRenameNodeExecutionEnv({ cwd: createTempDir() }); + repo = new JsonlSessionRepo({ + fileSystem, + sessionsRoot: "sessions", + now: () => NOW, + }); + }); + + afterEach(async () => { + await repo.close(BACKGROUND_CONTEXT); + }); + + async function writeLegacyV3Fixture( + records: readonly unknown[], + headerOptions: { parentSession?: string } = {}, + ): Promise<{ path: string; content: string }> { + const directory = getOrThrow(await fileSystem.joinPath(["sessions", "--workspace--"], BACKGROUND_CONTEXT)); + getOrThrow(await fileSystem.createDir(directory, undefined, BACKGROUND_CONTEXT)); + const relativePath = getOrThrow(await fileSystem.joinPath([directory, "legacy.jsonl"], BACKGROUND_CONTEXT)); + const path = getOrThrow(await fileSystem.absolutePath(relativePath, BACKGROUND_CONTEXT)); + const content = `${[ + { + type: "session", + version: 3, + id: "legacy", + timestamp: new Date(NOW).toISOString(), + cwd: "/workspace", + ...headerOptions, + }, + ...records, + ] + .map((record) => JSON.stringify(record)) + .join("\n")}\n`; + getOrThrow(await fileSystem.writeFile(path, content, BACKGROUND_CONTEXT)); + return { path, content }; + } + + it("discovers legacy v3 session files without rewriting them", async () => { + const { path, content } = await writeLegacyV3Fixture([], { + parentSession: "/old-session.jsonl", + }); + + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + const after = getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT)); + + expect(metadata).toMatchObject({ + id: "legacy", + createdAt: NOW, + storageVersion: JSONL_STORAGE_VERSION, + cwd: "/workspace", + path, + legacyParentSessionPath: "/old-session.jsonl", + }); + expect(Number.isFinite(metadata?.modifiedAt)).toBe(true); + expect(after).toBe(content); + }); + + it.each([ + { + format: "v3", + parentId: "legacy-parent", + header: { + type: "session", + version: 3, + id: "legacy-parent", + timestamp: new Date(NOW - 1_000).toISOString(), + cwd: "/workspace", + }, + }, + { + format: "v4", + parentId: "current-parent", + header: { + v: 4, + kind: "header", + id: "current-parent", + storageVersion: JSONL_STORAGE_VERSION, + createdAt: NOW - 1_000, + cwd: "/workspace", + }, + }, + ])("resolves an available $format parent path to its session id", async ({ format, parentId, header }) => { + const parentPath = getOrThrow(await fileSystem.absolutePath(`parent-${format}.jsonl`, BACKGROUND_CONTEXT)); + getOrThrow(await fileSystem.writeFile(parentPath, `${JSON.stringify(header)}\n`, BACKGROUND_CONTEXT)); + await writeLegacyV3Fixture([], { parentSession: parentPath }); + + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + expect(metadata).toMatchObject({ + id: "legacy", + parentSessionId: parentId, + }); + expect(metadata).not.toHaveProperty("legacyParentSessionPath"); + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + expect(session.metadata).toMatchObject({ parentSessionId: parentId }); + expect(session.metadata).not.toHaveProperty("legacyParentSessionPath"); + await session.close(BACKGROUND_CONTEXT); + }); + + it("preserves an invalid parent path as legacy metadata", async () => { + const parentPath = getOrThrow(await fileSystem.absolutePath("invalid-parent.jsonl", BACKGROUND_CONTEXT)); + getOrThrow(await fileSystem.writeFile(parentPath, '{"not":"a session header"}\n', BACKGROUND_CONTEXT)); + await writeLegacyV3Fixture([], { parentSession: parentPath }); + + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + + expect(metadata).toMatchObject({ + id: "legacy", + legacyParentSessionPath: parentPath, + }); + expect(metadata).not.toHaveProperty("parentSessionId"); + }); + + describe("forking legacy v3 sessions", () => { + const firstMessage = { + role: "user", + content: [{ type: "text", text: "fork me" }], + timestamp: NOW + 1_000, + } satisfies AgentMessage; + const usage = { + input: 10, + output: 5, + cacheRead: 2, + cacheWrite: 1, + totalTokens: 18, + cost: { + input: 0.1, + output: 0.05, + cacheRead: 0.02, + cacheWrite: 0.01, + total: 0.18, + }, + } satisfies Usage; + const secondMessage = { + role: "assistant", + content: [{ type: "text", text: "forked" }], + api: "anthropic-messages", + provider: "anthropic", + model: "claude-sonnet-4-5", + usage, + stopReason: "stop", + timestamp: NOW + 4_000, + } satisfies AgentMessage; + + async function writeForkFixture() { + const fixture = await writeLegacyV3Fixture([ + { + type: "message", + id: "message-1", + parentId: null, + timestamp: new Date(NOW + 1_000).toISOString(), + message: firstMessage, + }, + { + type: "label", + id: "label-1", + parentId: "message-1", + timestamp: new Date(NOW + 2_000).toISOString(), + targetId: "message-1", + label: "Fork point", + }, + { + type: "session_info", + id: "session-info", + parentId: "label-1", + timestamp: new Date(NOW + 3_000).toISOString(), + name: "Imported fork", + }, + { + type: "message", + id: "message-2", + parentId: "session-info", + timestamp: new Date(NOW + 4_000).toISOString(), + message: secondMessage, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + return { ...fixture, metadata }; + } + + async function expectForkedState(fork: Session): Promise { + expect(fork.metadata).toMatchObject({ + storageVersion: JSONL_STORAGE_VERSION, + parentSessionId: "legacy", + }); + const entries = await fork.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(2); + const [first, second] = entries; + if (first === undefined || second === undefined) throw new Error("Forked entries were not written"); + expect(first).toMatchObject({ + type: "message", + parentId: null, + message: firstMessage, + }); + expect(second).toMatchObject({ + type: "message", + parentId: first.id, + message: secondMessage, + }); + expect(first.id).not.toBe("message-1"); + expect(second.id).not.toBe("message-2"); + expect(await mainTip(fork)).toBe(second.id); + expect(await fork.getName(BACKGROUND_CONTEXT)).toBe("Imported fork"); + expect(await fork.getLabel(first.id, BACKGROUND_CONTEXT)).toBe("Fork point"); + expect(await fork.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT)).toBeUndefined(); + expect(await fork.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT)).toBeUndefined(); + expect(await fork.getStats(BACKGROUND_CONTEXT)).toEqual({ + messageCount: 2, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + }); + return entries; + } + + it("forks a closed source into a complete v4 destination without rewriting it", async () => { + const { path, content, metadata } = await writeForkFixture(); + + const fork = await repo.fork(metadata, { id: "closed-fork", scope: "tree" }, BACKGROUND_CONTEXT); + + expect(getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))).toBe(content); + expect(fork.metadata.id).toBe("closed-fork"); + const [headerLine] = getOrThrow( + await fileSystem.readTextLines(fork.metadata.path, { maxLines: 1 }, BACKGROUND_CONTEXT), + ); + if (headerLine === undefined) throw new Error("Fork header was not written"); + expect(JSON.parse(headerLine)).toMatchObject({ + v: 4, + kind: "header", + id: "closed-fork", + storageVersion: JSONL_STORAGE_VERSION, + parentSessionId: "legacy", + }); + await expectForkedState(fork); + + await fork.close(BACKGROUND_CONTEXT); + const destinationStorage = await JsonlStorage.open( + { fileSystem, path: fork.metadata.path, now: () => NOW }, + BACKGROUND_CONTEXT, + ); + expect(await destinationStorage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual([]); + await destinationStorage.close(BACKGROUND_CONTEXT); + expect(getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))).toBe(content); + }); + + it("forks a configured closed source at its main tip when entryId is omitted", async () => { + await writeLegacyV3Fixture([ + { + type: "model_change", + id: "model", + parentId: null, + timestamp: new Date(NOW + 1_000).toISOString(), + provider: "anthropic", + modelId: "claude-sonnet-4-5", + }, + { + type: "thinking_level_change", + id: "thinking", + parentId: "model", + timestamp: new Date(NOW + 2_000).toISOString(), + thinkingLevel: "high", + }, + { + type: "message", + id: "tip", + parentId: "thinking", + timestamp: new Date(NOW + 3_000).toISOString(), + message: firstMessage, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const fork = await repo.fork( + metadata, + { id: "branch-fork", scope: "branch", branch: "main" }, + BACKGROUND_CONTEXT, + ); + const entries = await fork.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(1); + expect(await mainTip(fork)).toBe(entries[0]!.id); + expect((await fork.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT))?.value).toEqual({ + model: { provider: "anthropic", modelId: "claude-sonnet-4-5" }, + thinkingLevel: "high", + activeToolNames: [], + }); + expect((await fork.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT))?.value).toEqual({ + currentOperationId: null, + lastOperationId: null, + inbox: [], + }); + await fork.close(BACKGROUND_CONTEXT); + }); + + it("forks a configured closed source at an original legacy entry id", async () => { + await writeLegacyV3Fixture([ + { + type: "model_change", + id: "model", + parentId: null, + timestamp: new Date(NOW + 1_000).toISOString(), + provider: "anthropic", + modelId: "claude-sonnet-4-5", + }, + { + type: "thinking_level_change", + id: "thinking", + parentId: "model", + timestamp: new Date(NOW + 2_000).toISOString(), + thinkingLevel: "high", + }, + { + type: "message", + id: "message-1", + parentId: "thinking", + timestamp: new Date(NOW + 3_000).toISOString(), + message: firstMessage, + }, + { + type: "message", + id: "message-2", + parentId: "message-1", + timestamp: new Date(NOW + 4_000).toISOString(), + message: secondMessage, + }, + { + type: "message", + id: "message-3", + parentId: "message-2", + timestamp: new Date(NOW + 5_000).toISOString(), + message: firstMessage, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const fork = await repo.fork( + metadata, + { id: "entry-fork", scope: "branch", branch: "main", entryId: "message-2" }, + BACKGROUND_CONTEXT, + ); + const entries = await fork.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(2); + expect(entries[1]).toMatchObject({ parentId: entries[0]!.id, message: secondMessage }); + expect(await mainTip(fork)).toBe(entries[1]!.id); + await fork.close(BACKGROUND_CONTEXT); + }); + + it("rejects an open v3 source until a non-empty commit persists its format-4 ids", async () => { + const { path, content, metadata } = await writeForkFixture(); + const source = await repo.open(metadata, BACKGROUND_CONTEXT); + const sourceEntries = await source.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + + await expect(repo.fork(metadata, { id: "open-fork", scope: "tree" }, BACKGROUND_CONTEXT)).rejects.toThrow( + "Cannot fork an open legacy v3 JSONL session", + ); + expect(getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))).toBe(content); + + await source.setName("Upgraded source", BACKGROUND_CONTEXT); + const fork = await repo.fork(metadata, { id: "open-fork", scope: "tree" }, BACKGROUND_CONTEXT); + + expect(fork.metadata.id).toBe("open-fork"); + expect(await fork.findEntries({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual(sourceEntries); + expect(await fork.getName(BACKGROUND_CONTEXT)).toBe("Upgraded source"); + await Promise.all([source.close(BACKGROUND_CONTEXT), fork.close(BACKGROUND_CONTEXT)]); + }); + }); + + it("opens an empty legacy session with a data-only main Branch", async () => { + await writeLegacyV3Fixture([]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + expect(await session.findEntries(undefined, BACKGROUND_CONTEXT)).toEqual([]); + expect(await mainTip(session)).toBeNull(); + expect(await session.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT)).toBeUndefined(); + expect(await session.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT)).toBeUndefined(); + await session.close(BACKGROUND_CONTEXT); + }); + + it("reports embedded legacy usage without creating usage rows or rewriting the source", async () => { + const usage = (factor: number): Usage => ({ + input: factor, + output: factor * 2, + cacheRead: factor * 3, + cacheWrite: factor * 4, + cacheWrite1h: factor * 5, + reasoning: factor * 6, + totalTokens: factor * 10, + cost: { + input: factor, + output: factor * 2, + cacheRead: factor * 3, + cacheWrite: factor * 4, + total: factor * 10, + }, + }); + const assistantUsage = usage(1); + const toolUsage = usage(10); + const compactionUsage = usage(100); + const branchSummaryUsage = usage(1_000); + const { path, content } = await writeLegacyV3Fixture([ + { + type: "message", + id: "assistant", + parentId: null, + timestamp: new Date(NOW + 1_000).toISOString(), + message: { + role: "assistant", + content: [{ type: "text", text: "answer" }], + api: "anthropic-messages", + provider: "anthropic", + model: "claude-sonnet-4-5", + usage: assistantUsage, + stopReason: "stop", + timestamp: NOW + 1_000, + } satisfies AgentMessage, + }, + { + type: "message", + id: "tool-result", + parentId: "assistant", + timestamp: new Date(NOW + 2_000).toISOString(), + message: { + role: "toolResult", + toolCallId: "call-1", + toolName: "test", + content: [{ type: "text", text: "result" }], + usage: toolUsage, + isError: false, + timestamp: NOW + 2_000, + } satisfies AgentMessage, + }, + { + type: "compaction", + id: "compaction", + parentId: "tool-result", + timestamp: new Date(NOW + 3_000).toISOString(), + summary: "Earlier context", + firstKeptEntryId: "assistant", + tokensBefore: 1_000, + usage: compactionUsage, + }, + { + type: "branch_summary", + id: "branch-summary", + parentId: "compaction", + timestamp: new Date(NOW + 4_000).toISOString(), + fromId: "assistant", + summary: "Abandoned branch", + usage: branchSummaryUsage, + }, + ]); + + const storage = await JsonlStorage.open({ fileSystem, path, now: () => NOW }, BACKGROUND_CONTEXT); + + expect(await storage.getStats(BACKGROUND_CONTEXT)).toEqual({ + messageCount: 2, + usage: usage(1_111), + }); + expect(await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual([]); + await storage.close(BACKGROUND_CONTEXT); + expect(getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))).toBe(content); + }); + + describe("upgrading legacy v3 sessions to v4", () => { + const importedUsage = { + input: 10, + output: 5, + cacheRead: 2, + cacheWrite: 1, + totalTokens: 18, + cost: { + input: 0.1, + output: 0.05, + cacheRead: 0.02, + cacheWrite: 0.01, + total: 0.18, + }, + } satisfies Usage; + const importedMessage = { + role: "assistant", + content: [{ type: "text", text: "imported answer" }], + api: "anthropic-messages", + provider: "anthropic", + model: "claude-sonnet-4-5", + usage: importedUsage, + stopReason: "stop", + timestamp: NOW + 1_000, + } satisfies AgentMessage; + + function writeUsageFixture() { + return writeLegacyV3Fixture([ + { + type: "message", + id: "assistant", + parentId: null, + timestamp: new Date(NOW + 1_000).toISOString(), + message: importedMessage, + }, + ]); + } + + it("writes one zero-valued usage adjustment when converting a session without imported usage", async () => { + const { path } = await writeLegacyV3Fixture([]); + const storage = await JsonlStorage.open({ fileSystem, path, now: () => NOW }, BACKGROUND_CONTEXT); + + await storage.commit( + [storedValues.setValue(storedValues.sessionName, "Converted session")], + BACKGROUND_CONTEXT, + ); + + const usageRows = await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT); + expect(usageRows).toHaveLength(1); + expect(usageRows[0]).toMatchObject({ + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + adjustment: true, + details: { source: "v3-import" }, + }); + expect(usageRows[0]).not.toHaveProperty("entryId"); + await storage.close(BACKGROUND_CONTEXT); + }); + + it("converts to v4 and preserves the first caller transaction with one usage adjustment", async () => { + // Seed a v3 session whose embedded usage must become a durable v4 ledger adjustment. + const { path } = await writeUsageFixture(); + // Capture the normalized read-only view so conversion can be checked for identity and stats stability. + const options = { fileSystem, path, now: () => NOW }; + const storage = await JsonlStorage.open(options, BACKGROUND_CONTEXT); + const importedEntries = await storage.scanEntries({ order: "asc" }, BACKGROUND_CONTEXT); + const statsBefore = await storage.getStats(BACKGROUND_CONTEXT); + + // The first caller write triggers conversion and must not expose the internal adjustment sequence. + const committed = await storage.commit( + [storedValues.setValue(storedValues.sessionName, "Converted session")], + BACKGROUND_CONTEXT, + ); + + expect(committed.seqs).toHaveLength(1); + expect(committed.firstSeq).toBe(committed.seqs[0]); + expect((await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.seq).toBe(committed.seqs[0]); + const usageRows = await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT); + expect(usageRows).toHaveLength(1); + const [adjustment] = usageRows; + if (adjustment === undefined) throw new Error("Import usage adjustment was not committed"); + expect(adjustment).toMatchObject({ + usage: importedUsage, + adjustment: true, + details: { source: "v3-import" }, + }); + expect(adjustment).not.toHaveProperty("entryId"); + expect(committed.seqs).not.toContain(adjustment.seq); + expect(committed.stats).toEqual(statsBefore); + expect(await storage.getStats(BACKGROUND_CONTEXT)).toEqual(statsBefore); + + // Conversion replaces the legacy file and retains the adjustment and caller writes as its first transaction. + const convertedLines = getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT)) + .trimEnd() + .split("\n"); + const headerLine = convertedLines[0]; + const transactionLine = convertedLines.at(-1); + if (headerLine === undefined || transactionLine === undefined) + throw new Error("Converted file was not written"); + expect(JSON.parse(headerLine)).toMatchObject({ + v: JSONL_FORMAT_VERSION, + kind: "header", + id: "legacy", + storageVersion: JSONL_STORAGE_VERSION, + createdAt: NOW, + cwd: "/workspace", + }); + expect(JSON.parse(transactionLine)).toEqual([ + { kind: "usage", ...adjustment }, + { + kind: "value", + op: "set", + seq: committed.seqs[0], + namespace: storedValues.sessionName.namespace, + key: storedValues.sessionName.key, + value: "Converted session", + }, + ]); + await storage.close(BACKGROUND_CONTEXT); + + // Reopening through the ordinary v4 path must recover the complete normalized and newly committed state. + const reopened = await JsonlStorage.open(options, BACKGROUND_CONTEXT); + expect(await reopened.scanEntries({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual(importedEntries); + const [importedEntry] = importedEntries; + if (importedEntry === undefined) throw new Error("Legacy message was not imported"); + expect((await reopened.getValue(storedValues.branchTip("main"), BACKGROUND_CONTEXT))?.value).toBe( + importedEntry.id, + ); + expect(await reopened.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT)).toBeUndefined(); + expect((await reopened.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.value).toBe( + "Converted session", + ); + expect(await reopened.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual([adjustment]); + expect(await reopened.getStats(BACKGROUND_CONTEXT)).toEqual(statsBefore); + await reopened.close(BACKGROUND_CONTEXT); + }); + + it("leaves the v3 source and live state unchanged when atomic publication fails", async () => { + const { path, content } = await writeUsageFixture(); + const options = { fileSystem, path, now: () => NOW }; + const storage = await JsonlStorage.open(options, BACKGROUND_CONTEXT); + const entriesBefore = await storage.scanEntries({ order: "asc" }, BACKGROUND_CONTEXT); + const leafBefore = await storage.getValue(storedValues.branchTip("main"), BACKGROUND_CONTEXT); + const laneStateBefore = await storage.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT); + const nameBefore = await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT); + const statsBefore = await storage.getStats(BACKGROUND_CONTEXT); + const usageBefore = await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT); + if (leafBefore === undefined) throw new Error("Normalized main Branch tip is missing"); + expect(laneStateBefore).toBeUndefined(); + + fileSystem.failRename = true; + await expect( + storage.commit([storedValues.setValue(storedValues.sessionName, "Converted session")], BACKGROUND_CONTEXT), + ).rejects.toThrow(`Failed to publish JSONL storage ${path}`); + fileSystem.failRename = false; + + expect(getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))).toBe(content); + expect(await storage.scanEntries({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual(entriesBefore); + expect(await storage.getValue(storedValues.branchTip("main"), BACKGROUND_CONTEXT)).toEqual(leafBefore); + expect(await storage.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT)).toEqual(laneStateBefore); + expect(await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toEqual(nameBefore); + expect(await storage.getStats(BACKGROUND_CONTEXT)).toEqual(statsBefore); + expect(await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT)).toEqual(usageBefore); + + const committed = await storage.commit( + [storedValues.setValue(storedValues.sessionName, "Converted session")], + BACKGROUND_CONTEXT, + ); + + expect(committed.firstSeq).toBe(leafBefore.seq + 2); + expect(committed.seqs).toEqual([committed.firstSeq]); + expect(await storage.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toMatchObject({ + seq: committed.firstSeq, + value: "Converted session", + }); + const usageRows = await storage.scanUsage({ order: "asc" }, BACKGROUND_CONTEXT); + expect(usageRows).toHaveLength(1); + expect(usageRows[0]).toMatchObject({ + usage: importedUsage, + adjustment: true, + details: { source: "v3-import" }, + }); + expect(await storage.getStats(BACKGROUND_CONTEXT)).toEqual(statsBefore); + await storage.close(BACKGROUND_CONTEXT); + }); + }); + + describe("reconstructing legacy lane configuration", () => { + const firstTimestamp = NOW + 1_000; + const modelChangeTimestamp = NOW + 2_000; + const thinkingChangeTimestamp = NOW + 3_000; + const activeToolsChangeTimestamp = NOW + 4_000; + const secondTimestamp = NOW + 5_000; + const firstMessage = { + role: "user", + content: [{ type: "text", text: "first" }], + timestamp: firstTimestamp, + } satisfies AgentMessage; + const secondMessage = { + role: "user", + content: [{ type: "text", text: "second" }], + timestamp: secondTimestamp, + } satisfies AgentMessage; + const configurationChanges = [ + { + type: "model_change", + id: "model-change", + parentId: "message-1", + timestamp: new Date(modelChangeTimestamp).toISOString(), + provider: "anthropic", + modelId: "claude-sonnet-4-5", + }, + { + type: "thinking_level_change", + id: "thinking-change", + parentId: "model-change", + timestamp: new Date(thinkingChangeTimestamp).toISOString(), + thinkingLevel: "high", + }, + { + type: "active_tools_change", + id: "active-tools-change", + parentId: "thinking-change", + timestamp: new Date(activeToolsChangeTimestamp).toISOString(), + activeToolNames: ["read", "bash"], + }, + ] as const; + + it("reparents a retained child through configuration changes", async () => { + await writeLegacyV3Fixture([ + { + type: "message", + id: "message-1", + parentId: null, + timestamp: new Date(firstTimestamp).toISOString(), + message: firstMessage, + }, + ...configurationChanges, + { + type: "message", + id: "message-2", + parentId: "active-tools-change", + timestamp: new Date(secondTimestamp).toISOString(), + message: secondMessage, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(2); + const [first, second] = entries; + if (first === undefined || second === undefined) { + throw new Error("Legacy configuration-change chain was not imported"); + } + expect(first).toMatchObject({ + type: "message", + parentId: null, + message: firstMessage, + }); + expect(second).toMatchObject({ + type: "message", + parentId: first.id, + message: secondMessage, + }); + expect(second.seq).toBeGreaterThan(first.seq); + expect(await mainTip(session)).toBe(second.id); + expect((await session.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT))?.value).toEqual({ + model: { provider: "anthropic", modelId: "claude-sonnet-4-5" }, + thinkingLevel: "high", + activeToolNames: ["read", "bash"], + }); + expect((await session.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT))?.value).toEqual({ + currentOperationId: null, + lastOperationId: null, + inbox: [], + }); + await session.close(BACKGROUND_CONTEXT); + }); + + it("retains only configuration changes on the selected physical branch", async () => { + await writeLegacyV3Fixture([ + { + type: "message", + id: "root", + parentId: null, + timestamp: new Date(firstTimestamp).toISOString(), + message: firstMessage, + }, + { + type: "model_change", + id: "selected-model", + parentId: "root", + timestamp: new Date(modelChangeTimestamp).toISOString(), + provider: "anthropic", + modelId: "selected", + }, + { + type: "thinking_level_change", + id: "selected-thinking", + parentId: "selected-model", + timestamp: new Date(thinkingChangeTimestamp).toISOString(), + thinkingLevel: "high", + }, + { + type: "model_change", + id: "abandoned-model", + parentId: "root", + timestamp: new Date(activeToolsChangeTimestamp).toISOString(), + provider: "openai", + modelId: "abandoned", + }, + { + type: "message", + id: "selected-tip", + parentId: "selected-thinking", + timestamp: new Date(secondTimestamp).toISOString(), + message: secondMessage, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + expect((await session.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT))?.value).toEqual({ + model: { provider: "anthropic", modelId: "selected" }, + thinkingLevel: "high", + activeToolNames: [], + }); + expect((await session.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT))?.value).toEqual({ + currentOperationId: null, + lastOperationId: null, + inbox: [], + }); + await session.close(BACKGROUND_CONTEXT); + }); + + it.each([ + { + name: "missing model", + changes: [ + { + type: "thinking_level_change", + id: "thinking", + parentId: "root", + timestamp: new Date(thinkingChangeTimestamp).toISOString(), + thinkingLevel: "high", + }, + ], + }, + { + name: "missing thinking level", + changes: [ + { + type: "model_change", + id: "model", + parentId: "root", + timestamp: new Date(modelChangeTimestamp).toISOString(), + provider: "anthropic", + modelId: "selected", + }, + ], + }, + ])("leaves main data-only for $name", async ({ changes }) => { + await writeLegacyV3Fixture([ + { + type: "message", + id: "root", + parentId: null, + timestamp: new Date(firstTimestamp).toISOString(), + message: firstMessage, + }, + ...changes, + { + type: "message", + id: "tip", + parentId: changes.at(-1)?.id ?? "root", + timestamp: new Date(secondTimestamp).toISOString(), + message: secondMessage, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + expect(await session.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT)).toBeUndefined(); + expect(await session.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT)).toBeUndefined(); + await session.close(BACKGROUND_CONTEXT); + }); + + it("resolves the main tip through trailing configuration changes", async () => { + await writeLegacyV3Fixture([ + { + type: "message", + id: "message-1", + parentId: null, + timestamp: new Date(firstTimestamp).toISOString(), + message: firstMessage, + }, + ...configurationChanges, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(1); + const [message] = entries; + if (message === undefined) throw new Error("Legacy message was not imported"); + expect(await mainTip(session)).toBe(message.id); + expect((await session.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT))?.value).toEqual({ + model: { provider: "anthropic", modelId: "claude-sonnet-4-5" }, + thinkingLevel: "high", + activeToolNames: ["read", "bash"], + }); + expect((await session.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT))?.value).toEqual({ + currentOperationId: null, + lastOperationId: null, + inbox: [], + }); + await session.close(BACKGROUND_CONTEXT); + }); + }); + + it("imports session info as the current name without retaining a tree entry", async () => { + await writeLegacyV3Fixture([ + { + type: "session_info", + id: "session-info", + parentId: null, + timestamp: new Date(NOW + 1_000).toISOString(), + name: "Imported session", + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + expect(await session.getName(BACKGROUND_CONTEXT)).toBe("Imported session"); + expect(await session.findEntries(undefined, BACKGROUND_CONTEXT)).toEqual([]); + expect(await mainTip(session)).toBeNull(); + await session.close(BACKGROUND_CONTEXT); + }); + + it("uses the latest session info and resolves tree structure through discarded records", async () => { + const firstMessage = { + role: "user", + content: [{ type: "text", text: "first" }], + timestamp: NOW + 1_000, + } satisfies AgentMessage; + const secondMessage = { + role: "user", + content: [{ type: "text", text: "second" }], + timestamp: NOW + 3_000, + } satisfies AgentMessage; + await writeLegacyV3Fixture([ + { + type: "message", + id: "message-1", + parentId: null, + timestamp: new Date(NOW + 1_000).toISOString(), + message: firstMessage, + }, + { + type: "session_info", + id: "session-info-1", + parentId: "message-1", + timestamp: new Date(NOW + 2_000).toISOString(), + name: "Earlier name", + }, + { + type: "message", + id: "message-2", + parentId: "session-info-1", + timestamp: new Date(NOW + 3_000).toISOString(), + message: secondMessage, + }, + { + type: "session_info", + id: "session-info-2", + parentId: "message-2", + timestamp: new Date(NOW + 4_000).toISOString(), + name: "Latest name", + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(2); + const [first, second] = entries; + if (first === undefined || second === undefined) throw new Error("Legacy message chain was not imported"); + expect(second.parentId).toBe(first.id); + expect(await session.getName(BACKGROUND_CONTEXT)).toBe("Latest name"); + expect(await mainTip(session)).toBe(second.id); + await session.close(BACKGROUND_CONTEXT); + }); + + it.each([{ name: undefined }, { name: "" }])("clears the session name with $name", async ({ name }) => { + await writeLegacyV3Fixture([ + { + type: "session_info", + id: "session-info-1", + parentId: null, + timestamp: new Date(NOW + 1_000).toISOString(), + name: "Earlier name", + }, + { + type: "session_info", + id: "session-info-2", + parentId: "session-info-1", + timestamp: new Date(NOW + 2_000).toISOString(), + ...(name === undefined ? {} : { name }), + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + expect(await session.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toBeUndefined(); + await session.close(BACKGROUND_CONTEXT); + }); + + it("imports a label for its remapped entry without retaining a tree node", async () => { + const message = { + role: "user", + content: [{ type: "text", text: "label me" }], + timestamp: NOW + 1_000, + } satisfies AgentMessage; + await writeLegacyV3Fixture([ + { + type: "message", + id: "message-1", + parentId: null, + timestamp: new Date(NOW + 1_000).toISOString(), + message, + }, + { + type: "label", + id: "label-1", + parentId: "message-1", + timestamp: new Date(NOW + 2_000).toISOString(), + targetId: "message-1", + label: "Important", + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(1); + const [entry] = entries; + if (entry === undefined) throw new Error("Legacy message was not imported"); + expect((await session.getValue(storedValues.entryLabel(entry.id), BACKGROUND_CONTEXT))?.value).toBe("Important"); + expect(await mainTip(session)).toBe(entry.id); + await session.close(BACKGROUND_CONTEXT); + }); + + it("skips a label whose target has no retained ancestor", async () => { + const message = { + role: "user", + content: [{ type: "text", text: "retained message" }], + timestamp: NOW + 3_000, + } satisfies AgentMessage; + await writeLegacyV3Fixture([ + { + type: "session_info", + id: "root-session-info", + parentId: null, + timestamp: new Date(NOW + 1_000).toISOString(), + }, + { + type: "label", + id: "root-label", + parentId: "root-session-info", + timestamp: new Date(NOW + 2_000).toISOString(), + targetId: "root-session-info", + label: "Skipped label", + }, + { + type: "message", + id: "message-1", + parentId: "root-label", + timestamp: new Date(NOW + 3_000).toISOString(), + message, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(1); + const [entry] = entries; + if (entry === undefined) throw new Error("Legacy message was not imported"); + expect(entry.parentId).toBeNull(); + expect(await session.getLabel(entry.id, BACKGROUND_CONTEXT)).toBeUndefined(); + expect(await mainTip(session)).toBe(entry.id); + await session.close(BACKGROUND_CONTEXT); + }); + + it("uses the latest label after remapping discarded targets", async () => { + const firstMessage = { + role: "user", + content: [{ type: "text", text: "first" }], + timestamp: NOW + 1_000, + } satisfies AgentMessage; + const secondMessage = { + role: "user", + content: [{ type: "text", text: "second" }], + timestamp: NOW + 5_000, + } satisfies AgentMessage; + await writeLegacyV3Fixture([ + { + type: "message", + id: "message-1", + parentId: null, + timestamp: new Date(NOW + 1_000).toISOString(), + message: firstMessage, + }, + { + type: "session_info", + id: "session-info", + parentId: "message-1", + timestamp: new Date(NOW + 2_000).toISOString(), + }, + { + type: "label", + id: "label-1", + parentId: "session-info", + timestamp: new Date(NOW + 3_000).toISOString(), + targetId: "session-info", + label: "Earlier label", + }, + { + type: "label", + id: "label-2", + parentId: "label-1", + timestamp: new Date(NOW + 4_000).toISOString(), + targetId: "message-1", + label: "Latest label", + }, + { + type: "message", + id: "message-2", + parentId: "label-2", + timestamp: new Date(NOW + 5_000).toISOString(), + message: secondMessage, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(2); + const [first, second] = entries; + if (first === undefined || second === undefined) throw new Error("Legacy message chain was not imported"); + expect(second.parentId).toBe(first.id); + expect(await session.getLabel(first.id, BACKGROUND_CONTEXT)).toBe("Latest label"); + expect(await mainTip(session)).toBe(second.id); + await session.close(BACKGROUND_CONTEXT); + }); + + it.each([{ label: undefined }, { label: "" }])("clears a label with $label", async ({ label }) => { + const message = { + role: "user", + content: [{ type: "text", text: "clear my label" }], + timestamp: NOW + 1_000, + } satisfies AgentMessage; + await writeLegacyV3Fixture([ + { + type: "message", + id: "message-1", + parentId: null, + timestamp: new Date(NOW + 1_000).toISOString(), + message, + }, + { + type: "label", + id: "label-1", + parentId: "message-1", + timestamp: new Date(NOW + 2_000).toISOString(), + targetId: "message-1", + label: "Earlier label", + }, + { + type: "label", + id: "label-2", + parentId: "label-1", + timestamp: new Date(NOW + 3_000).toISOString(), + targetId: "message-1", + ...(label === undefined ? {} : { label }), + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries(undefined, BACKGROUND_CONTEXT); + const [entry] = entries; + if (entry === undefined) throw new Error("Legacy message was not imported"); + expect(await session.getLabel(entry.id, BACKGROUND_CONTEXT)).toBeUndefined(); + expect(await mainTip(session)).toBe(entry.id); + await session.close(BACKGROUND_CONTEXT); + }); + + it("imports a custom entry without rewriting opaque data references", async () => { + const messageTimestamp = NOW + 1_000; + const customTimestamp = NOW + 2_000; + const message = { + role: "user", + content: [{ type: "text", text: "first" }], + timestamp: messageTimestamp, + } satisfies AgentMessage; + const data = { + legacyReference: "message-1", + nested: { legacyReference: "custom-1" }, + }; + await writeLegacyV3Fixture([ + { + type: "message", + id: "message-1", + parentId: null, + timestamp: new Date(messageTimestamp).toISOString(), + message, + }, + { + type: "custom", + id: "custom-1", + parentId: "message-1", + timestamp: new Date(customTimestamp).toISOString(), + customType: "checkpoint", + data, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(2); + const [messageEntry, customEntry] = entries; + if (messageEntry === undefined || customEntry === undefined) { + throw new Error("Legacy custom chain was not imported"); + } + expect(messageEntry.seq).toBe(1); + expect(customEntry).toMatchObject({ + type: "custom", + parentId: messageEntry.id, + seq: 2, + timestamp: customTimestamp, + customType: "checkpoint", + data, + }); + expect(customEntry.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + expect(uuidTimestamp(customEntry.id)).toBe(customTimestamp); + expect(await mainTip(session)).toBe(customEntry.id); + await session.close(BACKGROUND_CONTEXT); + }); + + it("imports a custom message as a current message entry", async () => { + const parentTimestamp = NOW + 1_000; + const customMessageTimestamp = NOW + 2_000; + const parentMessage = { + role: "user", + content: [{ type: "text", text: "first" }], + timestamp: parentTimestamp, + } satisfies AgentMessage; + const content = [{ type: "text", text: "legacy custom message" }]; + const details = { status: "complete" }; + await writeLegacyV3Fixture([ + { + type: "message", + id: "message-1", + parentId: null, + timestamp: new Date(parentTimestamp).toISOString(), + message: parentMessage, + }, + { + type: "custom_message", + id: "custom-message-1", + parentId: "message-1", + timestamp: new Date(customMessageTimestamp).toISOString(), + customType: "status", + content, + details, + display: false, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(2); + const [parentEntry, customMessageEntry] = entries; + if (parentEntry === undefined || customMessageEntry === undefined) { + throw new Error("Legacy custom message chain was not imported"); + } + expect(parentEntry.seq).toBe(1); + expect(customMessageEntry).toMatchObject({ + type: "message", + parentId: parentEntry.id, + seq: 2, + timestamp: customMessageTimestamp, + message: { + role: "custom", + customType: "status", + content, + details, + display: false, + timestamp: customMessageTimestamp, + }, + }); + expect(customMessageEntry.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + expect(uuidTimestamp(customMessageEntry.id)).toBe(customMessageTimestamp); + expect(await mainTip(session)).toBe(customMessageEntry.id); + expect((await session.getStats(BACKGROUND_CONTEXT)).messageCount).toBe(2); + await session.close(BACKGROUND_CONTEXT); + }); + + describe("importing branch summaries", () => { + const branchPointTimestamp = NOW + 1_000; + const abandonedResponseTimestamp = NOW + 2_000; + const summaryTimestamp = NOW + 3_000; + const details = { reason: "navigation" }; + const usage = { + input: 11, + output: 7, + cacheRead: 3, + cacheWrite: 2, + totalTokens: 23, + cost: { + input: 0.11, + output: 0.07, + cacheRead: 0.03, + cacheWrite: 0.02, + total: 0.23, + }, + } satisfies Usage; + const branchPointMessage = { + role: "user", + content: [{ type: "text", text: "Try the first approach" }], + timestamp: branchPointTimestamp, + } satisfies AgentMessage; + const abandonedResponse = { + role: "assistant", + content: [{ type: "text", text: "Implemented the first approach" }], + api: "anthropic-messages", + provider: "anthropic", + model: "claude-sonnet-4-5", + usage: { + input: 20, + output: 10, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 30, + cost: { + input: 0.2, + output: 0.1, + cacheRead: 0, + cacheWrite: 0, + total: 0.3, + }, + }, + stopReason: "stop", + timestamp: abandonedResponseTimestamp, + } satisfies AgentMessage; + + async function openFixture(fromHook?: true) { + await writeLegacyV3Fixture([ + { + type: "message", + id: "branch-point", + parentId: null, + timestamp: new Date(branchPointTimestamp).toISOString(), + message: branchPointMessage, + }, + { + type: "message", + id: "abandoned-response", + parentId: "branch-point", + timestamp: new Date(abandonedResponseTimestamp).toISOString(), + message: abandonedResponse, + }, + { + type: "branch_summary", + id: "summary", + parentId: "branch-point", + timestamp: new Date(summaryTimestamp).toISOString(), + fromId: "branch-point", + summary: "Summary of the abandoned branch", + details, + usage, + ...(fromHook === undefined ? {} : { fromHook }), + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(3); + const [branchPoint, abandoned, branchSummary] = entries; + if (branchPoint === undefined || abandoned === undefined || branchSummary === undefined) { + throw new Error("Legacy branch summary chain was not imported"); + } + return { session, branchPoint, abandoned, branchSummary }; + } + + it("preserves payload and remaps references", async () => { + const { session, branchPoint, abandoned, branchSummary } = await openFixture(); + + expect(abandoned.parentId).toBe(branchPoint.id); + expect(branchSummary).toMatchObject({ + type: "branch_summary", + parentId: branchPoint.id, + seq: 3, + timestamp: summaryTimestamp, + fromId: branchPoint.id, + summary: "Summary of the abandoned branch", + details, + usage, + fromHook: false, + }); + expect(branchSummary.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + expect(uuidTimestamp(branchSummary.id)).toBe(summaryTimestamp); + expect(await mainTip(session)).toBe(branchSummary.id); + await session.close(BACKGROUND_CONTEXT); + }); + + it("preserves an explicit fromHook flag", async () => { + const { session, branchSummary } = await openFixture(true); + + expect(branchSummary).toMatchObject({ + type: "branch_summary", + fromHook: true, + }); + await session.close(BACKGROUND_CONTEXT); + }); + + it('normalizes fromId "root" to null', async () => { + await writeLegacyV3Fixture([ + { + type: "branch_summary", + id: "summary", + parentId: null, + timestamp: new Date(summaryTimestamp).toISOString(), + fromId: "root", + summary: "Summary from the root", + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(1); + expect(entries[0]).toMatchObject({ + type: "branch_summary", + fromId: null, + }); + await session.close(BACKGROUND_CONTEXT); + }); + + it("rejects a missing fromId", async () => { + await writeLegacyV3Fixture([ + { + type: "branch_summary", + id: "summary", + parentId: null, + timestamp: new Date(summaryTimestamp).toISOString(), + fromId: "missing-legacy-entry", + summary: "Summary from a missing source", + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + await expect(repo.open(metadata, BACKGROUND_CONTEXT)).rejects.toThrow( + "Missing legacy v3 entry reference: missing-legacy-entry", + ); + }); + + it("keeps fromId null when a discarded source has no retained ancestor", async () => { + await writeLegacyV3Fixture([ + { + type: "model_change", + id: "model-change", + parentId: null, + timestamp: new Date(branchPointTimestamp).toISOString(), + provider: "anthropic", + modelId: "claude-sonnet-4-5", + }, + { + type: "branch_summary", + id: "summary", + parentId: "model-change", + timestamp: new Date(summaryTimestamp).toISOString(), + fromId: "model-change", + summary: "Summary from the root", + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(1); + expect(entries[0]).toMatchObject({ + type: "branch_summary", + parentId: null, + fromId: null, + }); + await session.close(BACKGROUND_CONTEXT); + }); + }); + + describe("importing compactions", () => { + const excludedTimestamp = NOW + 1_000; + const retainedTimestamp = NOW + 2_000; + const compactionTimestamp = NOW + 3_000; + const excludedMessage = { + role: "user", + content: [{ type: "text", text: "old context" }], + timestamp: excludedTimestamp, + } satisfies AgentMessage; + const retainedMessage = { + role: "user", + content: [{ type: "text", text: "retain this context" }], + timestamp: retainedTimestamp, + } satisfies AgentMessage; + const details = { strategy: "default" }; + const usage = { + input: 120, + output: 30, + cacheRead: 10, + cacheWrite: 5, + totalTokens: 165, + cost: { + input: 1.2, + output: 0.3, + cacheRead: 0.1, + cacheWrite: 0.05, + total: 1.65, + }, + } satisfies Usage; + + async function openFixture(fromHook?: true) { + await writeLegacyV3Fixture([ + { + type: "message", + id: "excluded-message", + parentId: null, + timestamp: new Date(excludedTimestamp).toISOString(), + message: excludedMessage, + }, + { + type: "message", + id: "retained-message", + parentId: "excluded-message", + timestamp: new Date(retainedTimestamp).toISOString(), + message: retainedMessage, + }, + { + type: "compaction", + id: "compaction", + parentId: "retained-message", + timestamp: new Date(compactionTimestamp).toISOString(), + summary: "Summary of the earlier context", + firstKeptEntryId: "retained-message", + tokensBefore: 12_000, + details, + usage, + ...(fromHook === undefined ? {} : { fromHook }), + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(3); + const [excluded, retained, compaction] = entries; + if (excluded === undefined || retained === undefined || compaction === undefined) { + throw new Error("Legacy compaction chain was not imported"); + } + return { session, excluded, retained, compaction }; + } + + it("materializes the retained tail and preserves the payload", async () => { + const { session, excluded, retained, compaction } = await openFixture(); + + expect(retained).toMatchObject({ parentId: excluded.id, seq: 2 }); + expect(compaction).toMatchObject({ + type: "compaction", + parentId: retained.id, + seq: 3, + timestamp: compactionTimestamp, + summary: "Summary of the earlier context", + retainedTail: [retainedMessage], + tokensBefore: 12_000, + details, + usage, + fromHook: false, + }); + expect(compaction).not.toHaveProperty("firstKeptEntryId"); + expect(compaction.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + expect(uuidTimestamp(compaction.id)).toBe(compactionTimestamp); + expect(await mainTip(session)).toBe(compaction.id); + await session.close(BACKGROUND_CONTEXT); + }); + + it("builds the retained tail from the compaction branch rather than physical order", async () => { + const firstMainMessage = { + role: "user", + content: [{ type: "text", text: "first main-branch message" }], + timestamp: NOW + 10_000, + } satisfies AgentMessage; + const firstOtherBranchMessage = { + role: "user", + content: [{ type: "text", text: "first unrelated-branch message" }], + timestamp: NOW + 11_000, + } satisfies AgentMessage; + const secondMainMessage = { + role: "user", + content: [{ type: "text", text: "second main-branch message" }], + timestamp: NOW + 12_000, + } satisfies AgentMessage; + const secondOtherBranchMessage = { + role: "user", + content: [{ type: "text", text: "second unrelated-branch message" }], + timestamp: NOW + 13_000, + } satisfies AgentMessage; + await writeLegacyV3Fixture([ + { + type: "message", + id: "main-1", + parentId: null, + timestamp: new Date(NOW + 10_000).toISOString(), + message: firstMainMessage, + }, + { + type: "message", + id: "other-1", + parentId: "main-1", + timestamp: new Date(NOW + 11_000).toISOString(), + message: firstOtherBranchMessage, + }, + { + type: "message", + id: "main-2", + parentId: "main-1", + timestamp: new Date(NOW + 12_000).toISOString(), + message: secondMainMessage, + }, + { + type: "message", + id: "other-2", + parentId: "other-1", + timestamp: new Date(NOW + 13_000).toISOString(), + message: secondOtherBranchMessage, + }, + { + type: "compaction", + id: "compaction", + parentId: "main-2", + timestamp: new Date(NOW + 14_000).toISOString(), + summary: "Summary before the retained main branch", + firstKeptEntryId: "main-1", + tokensBefore: 8_000, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + const compaction = entries.find((entry) => entry.type === "compaction"); + + expect(compaction).toMatchObject({ + type: "compaction", + retainedTail: [firstMainMessage, secondMainMessage], + }); + await session.close(BACKGROUND_CONTEXT); + }); + + it("projects every supported legacy node in a retained tail", async () => { + const ordinaryTimestamp = NOW + 30_000; + const customMessageTimestamp = NOW + 31_000; + const customEntryTimestamp = NOW + 32_000; + const branchSummaryTimestamp = NOW + 33_000; + const olderCompactionTimestamp = NOW + 34_000; + const finalCompactionTimestamp = NOW + 35_000; + const ordinaryMessage = { + role: "user", + content: [{ type: "text", text: "ordinary retained message" }], + timestamp: ordinaryTimestamp, + } satisfies AgentMessage; + const customContent = [{ type: "text" as const, text: "custom retained message" }]; + const customDetails = { status: "complete" }; + await writeLegacyV3Fixture([ + { + type: "message", + id: "ordinary-message", + parentId: null, + timestamp: new Date(ordinaryTimestamp).toISOString(), + message: ordinaryMessage, + }, + { + type: "custom_message", + id: "custom-message", + parentId: "ordinary-message", + timestamp: new Date(customMessageTimestamp).toISOString(), + customType: "notice", + content: customContent, + details: customDetails, + display: false, + }, + { + type: "custom", + id: "plain-custom", + parentId: "custom-message", + timestamp: new Date(customEntryTimestamp).toISOString(), + customType: "checkpoint", + data: { ignored: true }, + }, + { + type: "branch_summary", + id: "branch-summary", + parentId: "plain-custom", + timestamp: new Date(branchSummaryTimestamp).toISOString(), + fromId: "ordinary-message", + summary: "Earlier branch work", + }, + { + type: "compaction", + id: "older-compaction", + parentId: "branch-summary", + timestamp: new Date(olderCompactionTimestamp).toISOString(), + summary: "Older compacted context", + firstKeptEntryId: "ordinary-message", + tokensBefore: 4_000, + }, + { + type: "compaction", + id: "final-compaction", + parentId: "older-compaction", + timestamp: new Date(finalCompactionTimestamp).toISOString(), + summary: "Final compacted context", + firstKeptEntryId: "ordinary-message", + tokensBefore: 8_000, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(6); + const ordinary = entries.at(0); + const finalCompaction = entries.at(-1); + if (ordinary === undefined || finalCompaction?.type !== "compaction") { + throw new Error("Legacy retained-tail fixture was not imported"); + } + + expect(uuidTimestamp(ordinary.id)).toBe(ordinaryTimestamp); + expect(finalCompaction.retainedTail).toEqual([ + ordinaryMessage, + { + role: "custom", + customType: "notice", + content: customContent, + details: customDetails, + display: false, + timestamp: customMessageTimestamp, + }, + { + role: "branchSummary", + summary: "Earlier branch work", + fromId: ordinary.id, + timestamp: branchSummaryTimestamp, + }, + { + role: "compactionSummary", + summary: "Older compacted context", + tokensBefore: 4_000, + timestamp: olderCompactionTimestamp, + }, + ]); + await session.close(BACKGROUND_CONTEXT); + }); + + it.each([ + { boundary: "missing", firstKeptEntryId: "missing-entry" }, + { boundary: "off-branch", firstKeptEntryId: "other-branch" }, + ])("rejects a $boundary firstKeptEntryId", async ({ firstKeptEntryId }) => { + await writeLegacyV3Fixture([ + { + type: "message", + id: "root", + parentId: null, + timestamp: new Date(NOW + 20_000).toISOString(), + message: excludedMessage, + }, + { + type: "message", + id: "main-branch", + parentId: "root", + timestamp: new Date(NOW + 21_000).toISOString(), + message: retainedMessage, + }, + { + type: "message", + id: "other-branch", + parentId: "root", + timestamp: new Date(NOW + 22_000).toISOString(), + message: excludedMessage, + }, + { + type: "compaction", + id: "compaction", + parentId: "main-branch", + timestamp: new Date(NOW + 23_000).toISOString(), + summary: "Summary before the retained main branch", + firstKeptEntryId, + tokensBefore: 8_000, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + await expect(repo.open(metadata, BACKGROUND_CONTEXT)).rejects.toThrow( + "firstKeptEntryId is not on its parent branch", + ); + }); + + it("preserves an explicit fromHook flag", async () => { + const { session, compaction } = await openFixture(true); + + expect(compaction).toMatchObject({ type: "compaction", fromHook: true }); + await session.close(BACKGROUND_CONTEXT); + }); + }); + + it("remaps a legacy message chain and exposes it through current APIs", async () => { + const firstTimestamp = NOW + 1_000; + const secondTimestamp = NOW + 2_000; + const firstMessage = { + role: "user", + content: [{ type: "text", text: "first" }], + timestamp: firstTimestamp, + } satisfies AgentMessage; + const secondMessage = { + role: "user", + content: [{ type: "text", text: "second" }], + timestamp: secondTimestamp, + } satisfies AgentMessage; + await writeLegacyV3Fixture([ + { + type: "message", + id: "message-1", + parentId: null, + timestamp: new Date(firstTimestamp).toISOString(), + message: firstMessage, + }, + { + type: "message", + id: "message-2", + parentId: "message-1", + timestamp: new Date(secondTimestamp).toISOString(), + message: secondMessage, + }, + ]); + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + + const session = await repo.open(metadata, BACKGROUND_CONTEXT); + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(2); + const [first, second] = entries; + if (first === undefined || second === undefined) throw new Error("Legacy message chain was not imported"); + expect(first).toMatchObject({ + parentId: null, + seq: 1, + timestamp: firstTimestamp, + message: firstMessage, + }); + expect(second).toMatchObject({ + parentId: first.id, + seq: 2, + timestamp: secondTimestamp, + message: secondMessage, + }); + expect(await mainTip(session)).toBe(second.id); + expect( + (await (await mainBranch(session)).findEntries({ order: "oldestFirst" }, BACKGROUND_CONTEXT)).map( + (entry) => entry.id, + ), + ).toEqual([first.id, second.id]); + expect((await session.getStats(BACKGROUND_CONTEXT)).messageCount).toBe(2); + await session.close(BACKGROUND_CONTEXT); + }); + + describe("opening a legacy v3 message session", () => { + const entryTimestamp = NOW + 1_234; + const message = { + role: "user", + content: [{ type: "text", text: "hello" }], + timestamp: NOW + 1_000, + } satisfies AgentMessage; + let session: Session; + let path: string; + let content: string; + let beforeMtime: number; + + beforeEach(async () => { + ({ path, content } = await writeLegacyV3Fixture([ + { + type: "message", + id: "message-1", + parentId: null, + timestamp: new Date(entryTimestamp).toISOString(), + message, + }, + ])); + beforeMtime = getOrThrow(await fileSystem.fileInfo(path, BACKGROUND_CONTEXT)).mtimeMs; + const [metadata] = await repo.list({ cwd: "/workspace" }, BACKGROUND_CONTEXT); + if (metadata === undefined) throw new Error("Legacy fixture was not discovered"); + session = await repo.open(metadata, BACKGROUND_CONTEXT); + }); + + afterEach(async () => { + await session?.close(BACKGROUND_CONTEXT); + }); + + async function importedEntry(): Promise { + const entries = await session.findEntries({ order: "asc" }, BACKGROUND_CONTEXT); + expect(entries).toHaveLength(1); + const [entry] = entries; + if (entry === undefined) throw new Error("Legacy message was not imported"); + return entry; + } + + it("exposes the legacy message through the current entry API", async () => { + expect(await importedEntry()).toMatchObject({ + type: "message", + parentId: null, + seq: 1, + timestamp: entryTimestamp, + message, + }); + }); + + it("remints the entry id as a UUIDv7 with the legacy timestamp", async () => { + const entry = await importedEntry(); + + expect(entry.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + expect(uuidTimestamp(entry.id)).toBe(entryTimestamp); + }); + + it("initializes a data-only main Branch at the imported entry", async () => { + const entry = await importedEntry(); + + expect(await mainTip(session)).toBe(entry.id); + expect(await session.getValue(storedValues.laneState("main"), BACKGROUND_CONTEXT)).toBeUndefined(); + expect(await session.getValue(storedValues.laneConfig("main"), BACKGROUND_CONTEXT)).toBeUndefined(); + }); + + it("leaves the legacy source untouched after open and close", async () => { + await session.close(BACKGROUND_CONTEXT); + + expect(getOrThrow(await fileSystem.readTextFile(path, BACKGROUND_CONTEXT))).toBe(content); + expect(getOrThrow(await fileSystem.fileInfo(path, BACKGROUND_CONTEXT)).mtimeMs).toBe(beforeMtime); + }); + }); +}); diff --git a/packages/agent/test/harness/jsonl-v3-stream.test.ts b/packages/agent/test/harness/jsonl-v3-stream.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d560f46b2adc73f5caec532290c46a88ee8ecb22 --- /dev/null +++ b/packages/agent/test/harness/jsonl-v3-stream.test.ts @@ -0,0 +1,161 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT, type Context } from "../../src/harness/context.ts"; +import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts"; +import type { CommittedEntryWrite, CommittedValueSetWrite } from "../../src/harness/session/commit.ts"; +import type { LegacyV3SessionHeader } from "../../src/harness/session/jsonl/codec.ts"; +import { LegacyV3Source } from "../../src/harness/session/jsonl/legacy-v3.ts"; +import { type FileError, getOrThrow, ok, type Result, type TextLineReader } from "../../src/harness/types.ts"; +import { createTempDir } from "./session-test-utils.ts"; + +const NOW = 1_700_000_000_000; +const HEADER: LegacyV3SessionHeader = { + type: "session", + version: 3, + id: "legacy", + timestamp: new Date(NOW).toISOString(), + cwd: "/workspace", +}; +type OutputWrite = CommittedEntryWrite | CommittedValueSetWrite; + +function entry(type: string, id: string, parentId: string | null, fields: Record = {}) { + return { type, id, parentId, timestamp: new Date(NOW).toISOString(), ...fields }; +} + +function message(id: string, parentId: string | null, content = id) { + return entry("message", id, parentId, { message: { role: "user", content, timestamp: NOW } }); +} + +async function collect(source: LegacyV3Source, selected?: (id: string) => boolean): Promise { + const writes: OutputWrite[] = []; + for await (const write of source.writes(BACKGROUND_CONTEXT, selected)) writes.push(write); + return writes; +} + +class ObservedEnv extends NodeExecutionEnv { + lineReads = 0; + opens = 0; + closes = 0; + + override async openTextLineReader(path: string, context: Context): Promise> { + const opened = await super.openTextLineReader(path, context); + if (!opened.ok) return opened; + this.opens++; + return ok({ + readLine: (readContext: Context) => { + this.lineReads++; + return opened.value.readLine(readContext); + }, + close: async (closeContext: Context) => { + this.closes++; + await opened.value.close(closeContext); + }, + }); + } +} + +describe("streaming legacy v3 normalization", () => { + let fileSystem: ObservedEnv; + let fixtureId = 0; + + beforeEach(() => { + fileSystem = new ObservedEnv({ cwd: createTempDir() }); + }); + + async function fixture(records: readonly unknown[], suffix = "") { + const path = `legacy-${fixtureId++}.jsonl`; + const content = `${[HEADER, ...records].map((record) => JSON.stringify(record)).join("\n")}\n${suffix}`; + getOrThrow(await fileSystem.writeFile(path, content, BACKGROUND_CONTEXT)); + return { + path, + content, + reader: fileSystem, + read: () => LegacyV3Source.read(fileSystem, path, BACKGROUND_CONTEXT), + }; + } + + it("materializes a selected compaction with its branch-local tail", async () => { + const { read, reader } = await fixture([ + message("before", null), + entry("session_info", "boundary", "before"), + message("kept", "boundary", "Unicode é漢字"), + message("other", "before", "not on this branch"), + entry("compaction", "selected", "kept", { + summary: "selected", + firstKeptEntryId: "boundary", + tokensBefore: 20, + fromHook: true, + details: { a: 2 }, + }), + ]); + const source = await read(); + const selectedId = [...source.entryStructures()].at(-1)!.id; + expect(await collect(source, () => false)).toEqual(source.values); + reader.lineReads = 0; + const writes = await collect(source, (id) => id === selectedId); + expect(writes).toHaveLength(2); + expect(writes[0]).toMatchObject({ + type: "compaction", + id: selectedId, + seq: 4, + fromHook: true, + details: { a: 2 }, + retainedTail: [{ role: "user", content: "Unicode é漢字", timestamp: NOW }], + }); + expect(reader.lineReads).toBe(6); // Header plus each captured physical record, read once. + }); + + it("reuses an earlier cached message in selected compaction tails on different branches", async () => { + const { read, reader } = await fixture([ + message("root", null), + message("left", "root"), + entry("compaction", "left-compaction", "left", { + summary: "left summary", + firstKeptEntryId: "root", + tokensBefore: 10, + }), + message("right", "root"), + entry("compaction", "right-compaction", "right", { + summary: "right summary", + firstKeptEntryId: "root", + tokensBefore: 20, + }), + ]); + const source = await read(); + const structures = [...source.entryStructures()]; + const selected = new Set([structures[2]!.id, structures[4]!.id]); + reader.lineReads = 0; + const writes = await collect(source, (id) => selected.has(id)); + expect(writes).toHaveLength(3); + expect(writes[0]).toMatchObject({ + type: "compaction", + summary: "left summary", + retainedTail: [ + { role: "user", content: "root", timestamp: NOW }, + { role: "user", content: "left", timestamp: NOW }, + ], + }); + expect(writes[1]).toMatchObject({ + type: "compaction", + summary: "right summary", + retainedTail: [ + { role: "user", content: "root", timestamp: NOW }, + { role: "user", content: "right", timestamp: NOW }, + ], + }); + expect(reader.lineReads).toBe(6); + expect(await collect(source, (id) => selected.has(id))).toEqual(writes); + }); + + it("ignores a torn tail and emits only the captured complete records after later appends", async () => { + const { path, read, reader } = await fixture([message("a", null)], JSON.stringify(message("torn", "a"))); + const source = await read(); + getOrThrow( + await fileSystem.appendFile(path, `\n${JSON.stringify(message("later", "torn"))}\n`, BACKGROUND_CONTEXT), + ); + reader.lineReads = 0; + const writes = await collect(source); + expect(writes).toHaveLength(2); + expect(reader.lineReads).toBe(2); // Header plus the single captured complete record. + expect(source.nextSeq).toBe(3); + }); +}); diff --git a/packages/agent/test/harness/memory-conformance.test.ts b/packages/agent/test/harness/memory-conformance.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a764d4dbf7dbef3983486be6b9fe3fc0291cd1d3 --- /dev/null +++ b/packages/agent/test/harness/memory-conformance.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import * as sessionWrites from "../../src/harness/session/commit.ts"; +import { MemorySessionRepo } from "../../src/harness/session/index.ts"; +import { MemoryStorage } from "../../src/harness/session/memory.ts"; +import { + type ConformanceCase, + createSessionRepoConformance, + createSessionRepoStreamingForkConformance, + createStorageConformance, + type StorageFixture, +} from "../../src/harness/session/testing/index.ts"; +import * as storedValues from "../../src/harness/session/values.ts"; + +const NOW = 1_700_000_000_000; + +function registerConformance(name: string, cases: readonly ConformanceCase[]): void { + describe(name, () => { + for (const group of new Set(cases.map((testCase) => testCase.group))) { + describe(group, () => { + for (const testCase of cases.filter((candidate) => candidate.group === group)) { + it(testCase.name, () => testCase.run()); + } + }); + } + }); +} + +registerConformance( + "MemoryStorage conformance", + createStorageConformance(() => { + const storage = new MemoryStorage({ now: () => NOW }); + return Promise.resolve({ + storage, + [Symbol.asyncDispose]: () => storage.close(BACKGROUND_CONTEXT), + }); + }), +); + +describe("MemoryStorage commit statistics", () => { + it("includes historical totals in the first commit after session reopen", async () => { + const repo = new MemorySessionRepo({ now: () => NOW }); + const session = await repo.create({}, BACKGROUND_CONTEXT); + const usage = { + input: 1, + output: 2, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 3, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }; + try { + await session.mutate( + (mutator) => + mutator.commit( + [ + sessionWrites.insertEntry({ + id: "history", + parentId: null, + type: "message", + message: { role: "user", content: "history", timestamp: NOW }, + }), + sessionWrites.insertUsage({ id: "usage", usage, adjustment: false }), + ], + BACKGROUND_CONTEXT, + ), + BACKGROUND_CONTEXT, + ); + await session.close(BACKGROUND_CONTEXT); + const reopened = await repo.open(session.metadata, BACKGROUND_CONTEXT); + const result = await reopened.mutate( + (mutator) => + mutator.commit([storedValues.setValue(storedValues.sessionName, "reopened")], BACKGROUND_CONTEXT), + BACKGROUND_CONTEXT, + ); + expect(result.stats).toEqual({ messageCount: 1, usage }); + expect(result.stats).toEqual(await reopened.getStats(BACKGROUND_CONTEXT)); + await reopened.close(BACKGROUND_CONTEXT); + } finally { + await repo.close(BACKGROUND_CONTEXT); + } + }); +}); + +let memoryRepo: MemorySessionRepo; +registerConformance("MemorySessionRepo conformance", [ + ...createSessionRepoConformance( + () => { + memoryRepo = new MemorySessionRepo({ now: () => NOW }); + return Promise.resolve(memoryRepo); + }, + () => memoryRepo.close(BACKGROUND_CONTEXT), + ), + ...createSessionRepoStreamingForkConformance( + () => { + memoryRepo = new MemorySessionRepo({ now: () => NOW }); + return Promise.resolve(memoryRepo); + }, + () => memoryRepo.close(BACKGROUND_CONTEXT), + ), +]); diff --git a/packages/agent/test/harness/memory-session-repo.test.ts b/packages/agent/test/harness/memory-session-repo.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef465cf68d24171a2b0d7260827e883c4ebf902a --- /dev/null +++ b/packages/agent/test/harness/memory-session-repo.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import { MemorySessionRepo } from "../../src/harness/session/index.ts"; + +const NOW = 1_700_000_000_000; +function uuidTimestamp(id: string): number { + return Number.parseInt(id.replaceAll("-", "").slice(0, 12), 16); +} + +describe("MemorySessionRepo metadata", () => { + it("uses its injected clock for generated session identity and metadata", async () => { + const repo = new MemorySessionRepo({ now: () => NOW }); + const session = await repo.create({}, BACKGROUND_CONTEXT); + + expect(session.metadata.createdAt).toBe(NOW); + expect(uuidTimestamp(session.metadata.id)).toBe(NOW); + await Promise.all([session.close(BACKGROUND_CONTEXT), repo.close(BACKGROUND_CONTEXT)]); + }); + + it("returns a fresh facade after close while retaining one session and storage", async () => { + const repo = new MemorySessionRepo({ now: () => NOW }); + const first = await repo.create({ id: "session" }, BACKGROUND_CONTEXT); + const firstBranch = await first.createBranch("main", null, BACKGROUND_CONTEXT); + const admittedWrite = first.setName("preserved", BACKGROUND_CONTEXT); + + await expect(repo.open(first.metadata, BACKGROUND_CONTEXT)).rejects.toThrow("already open"); + await Promise.all([admittedWrite, first.close(BACKGROUND_CONTEXT)]); + await expect(first.getName(BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed"); + await expect(first.scanBranch({ start: "entry" }, BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed"); + await expect(firstBranch.getTipId(BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed"); + + const second = await repo.open(first.metadata, BACKGROUND_CONTEXT); + expect(second).not.toBe(first); + expect(await second.getName(BACKGROUND_CONTEXT)).toBe("preserved"); + await second.close(BACKGROUND_CONTEXT); + await repo.close(BACKGROUND_CONTEXT); + }); + + it("waits for an explicit mutation before closing its facade", async () => { + const repo = new MemorySessionRepo({ now: () => NOW }); + const session = await repo.create({ id: "session" }, BACKGROUND_CONTEXT); + const mutation = await session.beginMutation(BACKGROUND_CONTEXT); + let closed = false; + const closing = session.close(BACKGROUND_CONTEXT).then(() => { + closed = true; + }); + + await Promise.resolve(); + expect(closed).toBe(false); + await mutation.end(BACKGROUND_CONTEXT); + await closing; + expect(closed).toBe(true); + + const reopened = await repo.open(session.metadata, BACKGROUND_CONTEXT); + await Promise.all([reopened.close(BACKGROUND_CONTEXT), repo.close(BACKGROUND_CONTEXT)]); + }); + + it("rejects an explicit scope that had not acquired before facade close", async () => { + const repo = new MemorySessionRepo({ now: () => NOW }); + const session = await repo.create({ id: "session" }, BACKGROUND_CONTEXT); + const first = await session.beginMutation(BACKGROUND_CONTEXT); + const secondPromise = session.beginMutation(BACKGROUND_CONTEXT); + void secondPromise.catch(() => {}); + let closed = false; + const closing = session.close(BACKGROUND_CONTEXT).then(() => { + closed = true; + }); + + await first.end(BACKGROUND_CONTEXT); + await expect(secondPromise).rejects.toThrow("Session is closed"); + await closing; + expect(closed).toBe(true); + + const reopened = await repo.open(session.metadata, BACKGROUND_CONTEXT); + await Promise.all([reopened.close(BACKGROUND_CONTEXT), repo.close(BACKGROUND_CONTEXT)]); + }); +}); diff --git a/packages/agent/test/harness/memory-storage.test.ts b/packages/agent/test/harness/memory-storage.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7fab23fef49a88e80e4c1f83a04ccbb7c851d8f --- /dev/null +++ b/packages/agent/test/harness/memory-storage.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import * as sessionWrites from "../../src/harness/session/commit.ts"; +import { MemoryStorage } from "../../src/harness/session/memory.ts"; +import * as storedValues from "../../src/harness/session/values.ts"; + +const NOW = 1_700_000_000_000; + +describe("MemoryStorage", () => { + it("uses the injected clock once per transaction", async () => { + let timestamp = NOW; + const storage = new MemoryStorage({ now: () => timestamp++ }); + + const first = await storage.commit( + [ + sessionWrites.insertEntry({ + id: "first", + parentId: null, + type: "custom", + customType: "note", + }), + storedValues.setValue(storedValues.sessionName, "first"), + ], + BACKGROUND_CONTEXT, + ); + const second = await storage.commit( + [storedValues.setValue(storedValues.sessionName, "second")], + BACKGROUND_CONTEXT, + ); + + expect(first.timestamp).toBe(NOW); + expect(second.timestamp).toBe(NOW + 1); + expect((await storage.getEntries(["first"], BACKGROUND_CONTEXT)).get("first")?.timestamp).toBe(first.timestamp); + await storage.close(BACKGROUND_CONTEXT); + }); +}); diff --git a/packages/agent/test/harness/mutation-line.test.ts b/packages/agent/test/harness/mutation-line.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..761e17808152786e4d8e2b141f5fa4fb69f2c44a --- /dev/null +++ b/packages/agent/test/harness/mutation-line.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from "vitest"; +import { MutationLine } from "../../src/harness/session/mutation-line.ts"; + +function deferred(): { promise: Promise; resolve(): void } { + let resolvePromise!: () => void; + const promise = new Promise((resolve) => { + resolvePromise = resolve; + }); + return { promise, resolve: resolvePromise }; +} + +describe("MutationLine", () => { + it("serializes every Session mutation", async () => { + const line = new MutationLine(); + const gate = deferred(); + const order: string[] = []; + const first = line.run(async () => { + order.push("first:start"); + await gate.promise; + order.push("first:end"); + return "first"; + }); + const second = line.run(() => { + order.push("second"); + return "second"; + }); + + await Promise.resolve(); + expect(order).toEqual(["first:start"]); + gate.resolve(); + await expect(first).resolves.toBe("first"); + await expect(second).resolves.toBe("second"); + expect(order).toEqual(["first:start", "first:end", "second"]); + }); + + it("continues after a failed job while preserving the original failure", async () => { + const line = new MutationLine(); + const rejection = new Error("mutation failed"); + + await expect( + line.run(() => { + throw rejection; + }), + ).rejects.toBe(rejection); + await expect(line.run(() => "next")).resolves.toBe("next"); + }); + + it("seals queued and future jobs while draining the running job", async () => { + const line = new MutationLine(); + const gate = deferred(); + const running = line.run(async () => { + await gate.promise; + return "running"; + }); + await Promise.resolve(); + const queued = line.run(() => "queued"); + const closed = new Error("closed"); + + const drained = line.seal(closed); + await expect(line.run(() => "late")).rejects.toBe(closed); + gate.resolve(); + await expect(running).resolves.toBe("running"); + await expect(queued).rejects.toBe(closed); + await drained; + }); +}); diff --git a/packages/agent/test/harness/nodejs-env.test.ts b/packages/agent/test/harness/nodejs-env.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7cf8f0ac7081e57555ece7e59d29d4c967250bdb --- /dev/null +++ b/packages/agent/test/harness/nodejs-env.test.ts @@ -0,0 +1,706 @@ +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { access, chmod, realpath, symlink } from "node:fs/promises"; +import { homedir } from "node:os"; +import { delimiter, join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { afterEach, describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT, withAbortSignal } from "../../src/harness/context.ts"; +import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts"; +import { FileError, getOrThrow, type ShellExecOptions, type ShellOutputView } from "../../src/harness/types.ts"; +import { applyShellOutputUpdate } from "../../src/harness/utils/output-capture.ts"; +import { executeShellWithCapture } from "../../src/harness/utils/shell-output.ts"; +import { createTempDir } from "./session-test-utils.ts"; + +const chmodRestorePaths: string[] = []; + +function withTimeout(promise: Promise, ms: number, onTimeout?: () => void): Promise { + return new Promise((resolve, reject) => { + const timeoutId = setTimeout(() => { + onTimeout?.(); + reject(new Error(`Timed out after ${ms}ms`)); + }, ms); + promise.then( + (value) => { + clearTimeout(timeoutId); + resolve(value); + }, + (error: unknown) => { + clearTimeout(timeoutId); + reject(error); + }, + ); + }); +} + +async function collectShellOutput( + env: NodeExecutionEnv, + command: string, + options: ShellExecOptions | undefined, + context: Parameters[2], +): Promise<{ result: Awaited>; output: ShellOutputView | undefined }> { + let output: ShellOutputView | undefined; + const result = await env.exec( + command, + { + ...options, + onUpdate: (update) => { + output = applyShellOutputUpdate(output, update); + }, + }, + context, + ); + return { result, output }; +} + +function toBashSingleQuotedArg(value: string): string { + return `'${value.replace(/\\/g, "/").replace(/'/g, `'"'"'`)}'`; +} + +function createInheritedStdioCommand(pidFile: string): string { + return ( + 'node -e "' + + "const fs=require('fs');" + + "const {spawn}=require('child_process');" + + "const child=spawn(process.execPath,['-e','setTimeout(()=>{},60000)'],{stdio:'inherit',detached:true});" + + "fs.writeFileSync(process.argv[1], String(child.pid));" + + "child.unref();" + + "console.log('child-exiting');" + + '" ' + + toBashSingleQuotedArg(pidFile) + ); +} + +function cleanupDetachedChild(pidFile: string): void { + if (!existsSync(pidFile)) return; + const pid = Number.parseInt(readFileSync(pidFile, "utf8").trim(), 10); + if (!Number.isFinite(pid) || pid <= 0) return; + try { + execFileSync("taskkill", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore" }); + } catch {} +} + +class FailingSpillExecutionEnv extends NodeExecutionEnv { + override async createTempFile( + options: Parameters[0], + context: Parameters[1], + ) { + if (options?.prefix === "pi-output-") { + return { ok: true as const, value: join(this.cwd, "missing", "spill.log") }; + } + return super.createTempFile(options, context); + } +} + +afterEach(async () => { + for (const path of chmodRestorePaths.splice(0)) { + try { + await access(path); + await chmod(path, 0o700); + } catch {} + } +}); + +describe("NodeExecutionEnv", () => { + it("reads, writes, lists, and removes files and directories", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + expect(getOrThrow(await env.absolutePath("nested/child", BACKGROUND_CONTEXT))).toBe(join(root, "nested/child")); + expect(getOrThrow(await env.joinPath([root, "nested", "child"], BACKGROUND_CONTEXT))).toBe( + join(root, "nested", "child"), + ); + getOrThrow(await env.createDir("nested/child", undefined, BACKGROUND_CONTEXT)); + getOrThrow(await env.writeFile("nested/child/file.txt", "hel", BACKGROUND_CONTEXT)); + getOrThrow(await env.appendFile("nested/child/file.txt", "lo", BACKGROUND_CONTEXT)); + expect(getOrThrow(await env.readTextFile("nested/child/file.txt", BACKGROUND_CONTEXT))).toBe("hello"); + expect(getOrThrow(await env.readTextLines("nested/child/file.txt", { maxLines: 1 }, BACKGROUND_CONTEXT))).toEqual( + ["hello"], + ); + expect( + Buffer.from(getOrThrow(await env.readBinaryFile("nested/child/file.txt", BACKGROUND_CONTEXT))).toString( + "utf8", + ), + ).toBe("hello"); + + const entries = getOrThrow(await env.listDir("nested/child", BACKGROUND_CONTEXT)); + expect(entries).toHaveLength(1); + expect(entries[0]).toMatchObject({ + name: "file.txt", + path: join(root, "nested/child/file.txt"), + kind: "file", + size: 5, + }); + expect(typeof entries[0]!.mtimeMs).toBe("number"); + + expect(getOrThrow(await env.exists("nested/child/file.txt", BACKGROUND_CONTEXT))).toBe(true); + getOrThrow(await env.remove("nested/child/file.txt", undefined, BACKGROUND_CONTEXT)); + expect(getOrThrow(await env.exists("nested/child/file.txt", BACKGROUND_CONTEXT))).toBe(false); + }); + + it("expands home-relative paths and file URLs", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + expect(getOrThrow(await env.absolutePath("~/pi-node-env-test", BACKGROUND_CONTEXT))).toBe( + join(homedir(), "pi-node-env-test"), + ); + const filePath = join(root, "file with spaces.txt"); + expect(getOrThrow(await env.absolutePath(pathToFileURL(filePath).href, BACKGROUND_CONTEXT))).toBe(filePath); + }); + + it("returns fileInfo for files, directories, and symlinks without following symlinks", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + getOrThrow(await env.createDir("dir", { recursive: true }, BACKGROUND_CONTEXT)); + getOrThrow(await env.writeFile("dir/file.txt", "hello", BACKGROUND_CONTEXT)); + await symlink(join(root, "dir/file.txt"), join(root, "file-link")); + await symlink(join(root, "dir"), join(root, "dir-link")); + + expect(getOrThrow(await env.fileInfo("dir", BACKGROUND_CONTEXT))).toMatchObject({ + name: "dir", + path: join(root, "dir"), + kind: "directory", + }); + expect(getOrThrow(await env.fileInfo("dir/file.txt", BACKGROUND_CONTEXT))).toMatchObject({ + name: "file.txt", + path: join(root, "dir/file.txt"), + kind: "file", + size: 5, + }); + expect(getOrThrow(await env.fileInfo("file-link", BACKGROUND_CONTEXT))).toMatchObject({ + name: "file-link", + path: join(root, "file-link"), + kind: "symlink", + }); + expect(getOrThrow(await env.fileInfo("dir-link", BACKGROUND_CONTEXT))).toMatchObject({ + name: "dir-link", + path: join(root, "dir-link"), + kind: "symlink", + }); + expect(getOrThrow(await env.canonicalPath("file-link", BACKGROUND_CONTEXT))).toBe( + await realpath(join(root, "dir/file.txt")), + ); + }); + + it("lists symlinks as symlinks", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + getOrThrow(await env.writeFile("target.txt", "hello", BACKGROUND_CONTEXT)); + await symlink(join(root, "target.txt"), join(root, "link.txt")); + + const entries = getOrThrow(await env.listDir(".", BACKGROUND_CONTEXT)); + expect( + entries.map((entry) => ({ name: entry.name, kind: entry.kind })).sort((a, b) => a.name.localeCompare(b.name)), + ).toEqual([ + { name: "link.txt", kind: "symlink" }, + { name: "target.txt", kind: "file" }, + ]); + }); + + it("stops reading text lines at the requested limit", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + getOrThrow(await env.writeFile("file.txt", "one\ntwo\nthree", BACKGROUND_CONTEXT)); + expect(getOrThrow(await env.readTextLines("file.txt", { maxLines: 1 }, BACKGROUND_CONTEXT))).toEqual(["one"]); + }); + + it("returns FileError for missing paths and keeps exists false for missing paths", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const info = await env.fileInfo("missing.txt", BACKGROUND_CONTEXT); + expect(info.ok).toBe(false); + if (!info.ok) { + expect(info.error).toBeInstanceOf(FileError); + expect(info.error).toMatchObject({ + name: "FileError", + code: "not_found", + path: join(root, "missing.txt"), + }); + } + expect(getOrThrow(await env.exists("missing.txt", BACKGROUND_CONTEXT))).toBe(false); + }); + + it("returns FileError for listing non-directories", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + getOrThrow(await env.writeFile("file.txt", "hello", BACKGROUND_CONTEXT)); + const result = await env.listDir("file.txt", BACKGROUND_CONTEXT); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toBeInstanceOf(FileError); + expect(result.error).toMatchObject({ code: "not_directory" }); + } + }); + + it("appends to new files and creates parent directories", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + getOrThrow(await env.appendFile("new/nested/file.txt", "a", BACKGROUND_CONTEXT)); + getOrThrow(await env.appendFile("new/nested/file.txt", "b", BACKGROUND_CONTEXT)); + expect(getOrThrow(await env.readTextFile("new/nested/file.txt", BACKGROUND_CONTEXT))).toBe("ab"); + }); + + it("atomically renames a file and replaces the destination", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + getOrThrow(await env.writeFile("source.txt", "new", BACKGROUND_CONTEXT)); + getOrThrow(await env.writeFile("destination.txt", "old", BACKGROUND_CONTEXT)); + + getOrThrow(await env.renameFile("source.txt", "destination.txt", BACKGROUND_CONTEXT)); + + expect(getOrThrow(await env.exists("source.txt", BACKGROUND_CONTEXT))).toBe(false); + expect(getOrThrow(await env.readTextFile("destination.txt", BACKGROUND_CONTEXT))).toBe("new"); + }); + + it("reports the source path when rename fails because the source is missing", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + getOrThrow(await env.writeFile("destination.txt", "unchanged", BACKGROUND_CONTEXT)); + + const result = await env.renameFile("missing-source.txt", "destination.txt", BACKGROUND_CONTEXT); + + expect(result).toMatchObject({ + ok: false, + error: { + code: "not_found", + path: join(root, "missing-source.txt"), + }, + }); + expect(getOrThrow(await env.readTextFile("destination.txt", BACKGROUND_CONTEXT))).toBe("unchanged"); + }); + + it("creates temporary directories and files", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const tempDir = getOrThrow(await env.createTempDir("node-env-test-", BACKGROUND_CONTEXT)); + await expect(access(tempDir)).resolves.toBeUndefined(); + const tempFile = getOrThrow(await env.createTempFile({ prefix: "prefix-", suffix: ".txt" }, BACKGROUND_CONTEXT)); + await expect(access(tempFile)).resolves.toBeUndefined(); + expect(tempFile.endsWith(".txt")).toBe(true); + }); + + it("honors createDir recursive false and remove recursive/force options", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const createResult = await env.createDir("missing/child", { recursive: false }, BACKGROUND_CONTEXT); + expect(createResult.ok).toBe(false); + if (!createResult.ok) expect(createResult.error).toMatchObject({ code: "not_found" }); + + getOrThrow(await env.writeFile("dir/child/file.txt", "hello", BACKGROUND_CONTEXT)); + const removeDirectory = await env.remove("dir", { recursive: false }, BACKGROUND_CONTEXT); + expect(removeDirectory.ok).toBe(false); + getOrThrow(await env.remove("dir", { recursive: true }, BACKGROUND_CONTEXT)); + expect(getOrThrow(await env.exists("dir", BACKGROUND_CONTEXT))).toBe(false); + + const removeMissing = await env.remove("missing", { force: false }, BACKGROUND_CONTEXT); + expect(removeMissing.ok).toBe(false); + getOrThrow(await env.remove("missing", { force: true }, BACKGROUND_CONTEXT)); + }); + + it("returns aborted results for pre-aborted cancellable file operations", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + getOrThrow(await env.writeFile("file.txt", "hello", BACKGROUND_CONTEXT)); + const controller = new AbortController(); + controller.abort(); + const context = withAbortSignal(controller.signal, BACKGROUND_CONTEXT); + + const results = await Promise.all([ + env.readTextFile("file.txt", context), + env.readTextLines("file.txt", undefined, context), + env.readBinaryFile("file.txt", context), + env.writeFile("other.txt", "hello", context), + env.renameFile("file.txt", "renamed.txt", context), + env.listDir(".", context), + ]); + for (const result of results) { + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ code: "aborted" }); + } + }); + + it("cleanup is best-effort", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + await expect(env.cleanup(BACKGROUND_CONTEXT)).resolves.toBeUndefined(); + }); + + it("executes commands in cwd with env overrides", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const collected = await collectShellOutput( + env, + 'printf \'%s:%s\' "$PWD" "$NODE_ENV_TEST"', + { env: { NODE_ENV_TEST: "ok" } }, + BACKGROUND_CONTEXT, + ); + const result = getOrThrow(collected.result); + expect(collected.output?.text).toBe(`${await realpath(root)}:ok`); + expect(result.exitCode).toBe(0); + }); + + it.each([ + ["a missing override preserves the base value", undefined, "x:/stale/parent.jsonl"], + ["an empty override shadows the base value", { PI_SESSION_FILE: "" }, "x:"], + [ + "a string override replaces the base value", + { PI_SESSION_FILE: "/sessions/current.jsonl" }, + "x:/sessions/current.jsonl", + ], + ] as const)( + "applies string shell environment overrides when %s", + async (_description, overrides, expectedSessionFile) => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ + cwd: root, + shellEnv: { + PI_SESSION_FILE: "/stale/parent.jsonl", + PI_CODING_AGENT: "true", + PI_NODE_ENV_PRESERVED_TEST: "preserved", + }, + }); + const collected = await collectShellOutput( + env, + `printf '%s:%s|%s|%s' "\${PI_SESSION_FILE+x}" "\${PI_SESSION_FILE-}" "$PI_CODING_AGENT" "$PI_NODE_ENV_PRESERVED_TEST"`, + { env: overrides }, + BACKGROUND_CONTEXT, + ); + getOrThrow(collected.result); + expect(collected.output?.text).toBe(`${expectedSessionFile}|true|preserved`); + }, + ); + + it("can replace rather than inherit the default shell environment", async () => { + const root = createTempDir(); + const inheritedKey = "PI_NODE_ENV_INHERITED_TEST"; + const configuredKey = "PI_NODE_ENV_CONFIGURED_TEST"; + const explicitKey = "PI_NODE_ENV_EXPLICIT_TEST"; + const previousInherited = process.env[inheritedKey]; + process.env[inheritedKey] = "host"; + try { + const env = new NodeExecutionEnv({ cwd: root, shellEnv: { [configuredKey]: "configured" } }); + const collected = await collectShellOutput( + env, + `printf '%s:%s:%s' "\${${inheritedKey}-}" "\${${configuredKey}-}" "\${${explicitKey}-}"`, + { inheritEnv: false, env: { [explicitKey]: "explicit" } }, + BACKGROUND_CONTEXT, + ); + getOrThrow(collected.result); + expect(collected.output?.text).toBe("::explicit"); + } finally { + if (previousInherited === undefined) delete process.env[inheritedKey]; + else process.env[inheritedKey] = previousInherited; + } + }); + + it("uses stdin command transport for legacy WSL bash paths", async () => { + if (process.platform === "win32") return; + const root = createTempDir(); + const shellPath = "C:\\Windows\\System32\\bash.exe"; + const env = new NodeExecutionEnv({ cwd: root }); + getOrThrow( + await env.writeFile( + shellPath, + '#!/bin/sh\nprintf \'args:%s\\n\' "$*" >&2\nexec /bin/bash "$@"\n', + BACKGROUND_CONTEXT, + ), + ); + await chmod(join(root, shellPath), 0o755); + + const originalCwd = process.cwd(); + const originalPath = process.env.PATH; + const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform"); + try { + process.chdir(root); + process.env.PATH = `${root}${delimiter}${originalPath ?? ""}`; + Object.defineProperty(process, "platform", { + configurable: true, + value: "win32", + }); + + const wslEnv = new NodeExecutionEnv({ cwd: root, shellPath }); + const nameExpansion = "$" + "{name}"; + const collected = await collectShellOutput( + wslEnv, + `name='World'; echo "Hello, ${nameExpansion}!"`, + undefined, + BACKGROUND_CONTEXT, + ); + const result = getOrThrow(collected.result); + expect(collected.output?.text).toContain("Hello, World!"); + expect(collected.output?.text).toContain("args:-s"); + expect(result.exitCode).toBe(0); + } finally { + process.chdir(originalCwd); + process.env.PATH = originalPath; + if (platformDescriptor) { + Object.defineProperty(process, "platform", platformDescriptor); + } + } + }); + + it.skipIf(process.platform !== "win32")( + "settles after the shell exits when a detached descendant retains inherited stdio", + async () => { + const root = createTempDir(); + const pidFile = join(root, "grandchild.pid"); + const env = new NodeExecutionEnv({ cwd: root }); + const controller = new AbortController(); + try { + const collected = await withTimeout( + collectShellOutput( + env, + createInheritedStdioCommand(pidFile), + undefined, + withAbortSignal(controller.signal, BACKGROUND_CONTEXT), + ), + 3000, + () => controller.abort(), + ); + getOrThrow(collected.result); + expect(collected.output?.text).toContain("child-exiting"); + } finally { + controller.abort(); + cleanupDetachedChild(pidFile); + } + }, + ); + + it("cleanup terminates active shell processes", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const execution = env.exec("touch started; sleep 60", undefined, BACKGROUND_CONTEXT); + for (let attempt = 0; attempt < 100 && !getOrThrow(await env.exists("started", BACKGROUND_CONTEXT)); attempt++) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + expect(getOrThrow(await env.exists("started", BACKGROUND_CONTEXT))).toBe(true); + await env.cleanup(BACKGROUND_CONTEXT); + await expect(withTimeout(execution, 3000)).resolves.toMatchObject({ ok: true }); + }); + + it("combines stdout and stderr into one bounded view", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const updates: string[] = []; + let output: ShellOutputView | undefined; + const result = getOrThrow( + await env.exec( + "printf out; printf err >&2", + { + onUpdate: (update) => { + updates.push(update.kind); + output = applyShellOutputUpdate(output, update); + }, + }, + BACKGROUND_CONTEXT, + ), + ); + expect(result.exitCode).toBe(0); + expect(output?.text).toContain("out"); + expect(output?.text).toContain("err"); + expect(updates[0]).toBe("replace"); + }); + + it("reports a missing working directory before spawning", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: join(root, "missing") }); + const result = await env.exec("printf ok", undefined, BACKGROUND_CONTEXT); + + expect(result).toMatchObject({ + ok: false, + error: { code: "spawn_error", message: expect.stringContaining("Working directory does not exist") }, + }); + }); + + it("returns non-zero command exit codes as successful execution results", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const result = getOrThrow(await env.exec("exit 7", undefined, BACKGROUND_CONTEXT)); + expect(result.exitCode).toBe(7); + expect(result.truncation.totalBytes).toBe(0); + }); + + // Regression test for https://github.com/earendil-works/pi/issues/8992 + it.skipIf(process.platform === "win32")("maps signal-killed processes to a non-zero exit code", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const result = getOrThrow(await env.exec("kill -9 $$", undefined, BACKGROUND_CONTEXT)); + expect(result.exitCode).toBe(128 + 9); + }); + + it("returns timeout errors for commands exceeding the timeout", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const result = await env.exec("sleep 5", { timeout: 0.01 }, BACKGROUND_CONTEXT); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ code: "timeout" }); + }); + + it("returns callback errors from exec stream handlers", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const result = await env.exec( + "printf out", + { + onUpdate: () => { + throw new Error("callback failed"); + }, + }, + BACKGROUND_CONTEXT, + ); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ code: "callback_error", message: "callback failed" }); + }); + + it("returns shell unavailable and spawn errors", async () => { + const root = createTempDir(); + const missingShellEnv = new NodeExecutionEnv({ cwd: root, shellPath: join(root, "missing-shell") }); + const missingShell = await missingShellEnv.exec("printf ok", undefined, BACKGROUND_CONTEXT); + expect(missingShell.ok).toBe(false); + if (!missingShell.ok) expect(missingShell.error).toMatchObject({ code: "shell_unavailable" }); + + const shellPath = join(root, "not-executable-shell"); + const env = new NodeExecutionEnv({ cwd: root }); + getOrThrow(await env.writeFile(shellPath, "not executable", BACKGROUND_CONTEXT)); + const spawnErrorEnv = new NodeExecutionEnv({ cwd: root, shellPath }); + const spawnError = await spawnErrorEnv.exec("printf ok", undefined, BACKGROUND_CONTEXT); + expect(spawnError.ok).toBe(false); + if (!spawnError.ok) expect(spawnError.error).toMatchObject({ code: "spawn_error" }); + }); + + it("returns an aborted result for aborted commands", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const controller = new AbortController(); + const promise = env.exec("sleep 5", undefined, withAbortSignal(controller.signal, BACKGROUND_CONTEXT)); + controller.abort(); + const result = await promise; + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ code: "aborted" }); + }); + + it.skipIf(process.platform === "win32")("ignores asynchronous taskkill spawn errors during abort", async () => { + const root = createTempDir(); + const pidFile = join(root, "shell.pid"); + const controller = new AbortController(); + const env = new NodeExecutionEnv({ cwd: root, shellPath: "/bin/bash" }); + const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform"); + const previousSystemRoot = process.env.SystemRoot; + process.env.SystemRoot = "/definitely/missing/windows"; + Object.defineProperty(process, "platform", { configurable: true, value: "win32" }); + + let pid: number | undefined; + try { + const execution = env.exec( + `echo $$ > ${toBashSingleQuotedArg(pidFile)}; exec sleep 60`, + undefined, + withAbortSignal(controller.signal, BACKGROUND_CONTEXT), + ); + for (let attempt = 0; attempt < 100 && !existsSync(pidFile); attempt++) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + expect(existsSync(pidFile)).toBe(true); + + controller.abort(); + await new Promise((resolve) => setTimeout(resolve, 0)); + pid = Number.parseInt(readFileSync(pidFile, "utf8"), 10); + process.kill(pid, "SIGKILL"); + + const result = await execution; + expect(result).toMatchObject({ ok: false, error: { code: "aborted" } }); + } finally { + if (pid === undefined && existsSync(pidFile)) { + pid = Number.parseInt(readFileSync(pidFile, "utf8"), 10); + } + if (pid !== undefined && Number.isFinite(pid)) { + try { + process.kill(pid, "SIGKILL"); + } catch {} + } + if (previousSystemRoot === undefined) delete process.env.SystemRoot; + else process.env.SystemRoot = previousSystemRoot; + if (platformDescriptor) Object.defineProperty(process, "platform", platformDescriptor); + } + }); + + it("does not create a spill before bounded output crosses its limits", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const result = getOrThrow( + await env.exec( + "printf short", + { + capture: { limits: { maxBytes: 100, maxLines: 10, retain: "tail" }, spill: true }, + onUpdate: () => {}, + }, + BACKGROUND_CONTEXT, + ), + ); + expect(result.spillPath).toBeUndefined(); + }); + + it("preserves exact raw bytes in the spill while decoding a bounded text view", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const expected = [0x66, 0x80, 0x00, 0x6f]; + const result = getOrThrow( + await env.exec( + `${JSON.stringify(process.execPath)} -e "process.stdout.write(Buffer.from([${expected.join(",")}]))"`, + { + capture: { limits: { maxBytes: 1, maxLines: 10, retain: "tail" }, spill: true }, + onUpdate: () => {}, + }, + BACKGROUND_CONTEXT, + ), + ); + expect(result.spillPath).toBeDefined(); + expect([...getOrThrow(await env.readBinaryFile(result.spillPath!, BACKGROUND_CONTEXT))]).toEqual(expected); + }); + + it("fails rather than silently losing a requested spill", async () => { + const root = createTempDir(); + const env = new FailingSpillExecutionEnv({ cwd: root }); + const result = await env.exec( + "printf 12345678901234567890", + { + capture: { limits: { maxBytes: 10, maxLines: 10, retain: "tail" }, spill: true }, + onUpdate: () => {}, + }, + BACKGROUND_CONTEXT, + ); + expect(result).toMatchObject({ + ok: false, + error: { code: "unknown", message: expect.stringContaining("Failed to preserve complete shell output") }, + }); + }); + + it("preserves complete output when spill-stream backpressure pauses a process that exits quickly", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const size = 500_000; + const result = getOrThrow( + await env.exec( + `${JSON.stringify(process.execPath)} -e "process.stdout.write('x'.repeat(${size}))"`, + { + capture: { limits: { maxBytes: 10, maxLines: 10, retain: "tail" }, spill: true }, + onUpdate: () => {}, + }, + BACKGROUND_CONTEXT, + ), + ); + expect(result.spillPath).toBeDefined(); + expect(getOrThrow(await env.readTextFile(result.spillPath!, BACKGROUND_CONTEXT))).toHaveLength(size); + }); + + it("captures large shell output to a full output file through the execution env", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + const result = getOrThrow( + await executeShellWithCapture(env, "yes line | head -n 15000", undefined, BACKGROUND_CONTEXT), + ); + expect(result.truncated).toBe(true); + expect(result.fullOutputPath).toBeDefined(); + const fullOutput = getOrThrow(await env.readTextFile(result.fullOutputPath!, BACKGROUND_CONTEXT)); + expect(fullOutput.split("\n").length).toBeGreaterThan(10000); + expect(result.output.length).toBeLessThan(fullOutput.length); + }); +}); diff --git a/packages/agent/test/harness/output-capture.test.ts b/packages/agent/test/harness/output-capture.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a0834cb45d94b24492d83cd4deaece16c638177 --- /dev/null +++ b/packages/agent/test/harness/output-capture.test.ts @@ -0,0 +1,151 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import type { ShellOutputUpdate, ShellOutputView } from "../../src/harness/types.ts"; +import { applyShellOutputUpdate, OutputCapture, sanitizeShellOutput } from "../../src/harness/utils/output-capture.ts"; + +function createCapture(options?: { maxBytes?: number; maxLines?: number; retain?: "head" | "tail" }) { + const updates: ShellOutputUpdate[] = []; + const errors: unknown[] = []; + const capture = new OutputCapture( + { + limits: { + maxBytes: options?.maxBytes ?? 50, + maxLines: options?.maxLines ?? 100, + retain: options?.retain ?? "tail", + }, + }, + BACKGROUND_CONTEXT, + { + onUpdate: (update) => updates.push(update), + onError: (error) => errors.push(error), + }, + ); + return { capture, updates, errors }; +} + +function fold(updates: ShellOutputUpdate[]): ShellOutputView | undefined { + let output: ShellOutputView | undefined; + for (const update of updates) output = applyShellOutputUpdate(output, update); + return output; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("OutputCapture", () => { + it("removes invalid control characters without changing text or line boundaries", () => { + const input = "a\0b\tc\nd\re\u0007f\ufff9g\ufffbh😀"; + expect(sanitizeShellOutput(input)).toBe("ab\tc\ndefgh😀"); + const { capture } = createCapture(); + capture.push(input); + expect(capture.snapshot().text).toBe("ab\tc\ndefgh😀"); + }); + it("decodes UTF-8 split across raw process chunks", () => { + const { capture } = createCapture(); + const bytes = new TextEncoder().encode("😀"); + capture.push(bytes.subarray(0, 2)); + expect(capture.snapshot().text).toBe(""); + capture.push(bytes.subarray(2)); + capture.finish(); + expect(capture.snapshot().text).toBe("😀"); + }); + + it("publishes the first bounded view immediately and trickling appends responsively", () => { + vi.useFakeTimers(); + vi.setSystemTime(0); + const { capture, updates } = createCapture(); + + capture.push("one"); + expect(updates).toHaveLength(1); + expect(updates[0]?.kind).toBe("replace"); + + vi.advanceTimersByTime(150); + capture.push(" two"); + expect(updates).toHaveLength(2); + expect(updates[1]).toMatchObject({ kind: "append", text: " two" }); + expect(fold(updates)?.text).toBe("one two"); + }); + + it("collapses a burst into one trailing update", () => { + vi.useFakeTimers(); + vi.setSystemTime(0); + const { capture, updates } = createCapture(); + capture.push("a"); + capture.push("b"); + capture.push("c"); + expect(updates).toHaveLength(1); + + vi.advanceTimersByTime(100); + expect(updates).toHaveLength(2); + expect(updates[1]).toMatchObject({ kind: "append", text: "bc" }); + expect(fold(updates)?.text).toBe("abc"); + }); + + it("publishes a small slide for post-cap trickle", () => { + vi.useFakeTimers(); + vi.setSystemTime(0); + const { capture, updates } = createCapture({ maxBytes: 10 }); + capture.push("abcdefghij"); + vi.advanceTimersByTime(150); + capture.push("k"); + + expect(updates[1]).toMatchObject({ kind: "slide", drop: 1, text: "k" }); + expect(fold(updates)?.text).toBe("bcdefghijk"); + expect(fold(updates)?.truncation.totalBytes).toBe(11); + }); + + it("keeps the exact byte count for a single line larger than its working buffer", () => { + vi.useFakeTimers(); + const { capture } = createCapture({ maxBytes: 10 }); + capture.push("x".repeat(100)); + expect(capture.snapshot()).toMatchObject({ + text: "x".repeat(10), + lastLineBytes: 100, + truncation: { lastLinePartial: true }, + }); + }); + + it("uses a cap-bounded replacement after complete turnover", () => { + vi.useFakeTimers(); + vi.setSystemTime(0); + const { capture, updates } = createCapture({ maxBytes: 10 }); + capture.push("abcdefghij"); + capture.push("x".repeat(100)); + vi.advanceTimersByTime(100); + + expect(updates[1]?.kind).toBe("replace"); + expect(fold(updates)?.text).toHaveLength(10); + expect(fold(updates)?.truncation.totalBytes).toBe(110); + }); + + it("forces held state and cancels its trailing timer on dispose", () => { + vi.useFakeTimers(); + vi.setSystemTime(0); + const { capture, updates } = createCapture(); + capture.push("a"); + capture.push("b"); + capture.flush(); + expect(fold(updates)?.text).toBe("ab"); + capture.dispose(); + vi.advanceTimersByTime(1_000); + expect(updates).toHaveLength(2); + }); + + it("preserves the original head after its raw guard is crossed", () => { + vi.useFakeTimers(); + const { capture } = createCapture({ maxBytes: 100, maxLines: 2, retain: "head" }); + capture.push(`first\nsecond\n${"tail".repeat(100)}`); + expect(capture.snapshot().text).toBe("first\nsecond"); + }); + + it("publishes spill metadata without resending text", () => { + vi.useFakeTimers(); + const { capture, updates, errors } = createCapture(); + capture.push("output"); + capture.setSpillPath("/tmp/output.log"); + expect(updates.at(-1)).toMatchObject({ kind: "metadata", metadata: { spillPath: "/tmp/output.log" } }); + expect(fold(updates)?.spillPath).toBe("/tmp/output.log"); + expect(errors).toEqual([]); + }); +}); diff --git a/packages/agent/test/harness/resource-formatting.test.ts b/packages/agent/test/harness/resource-formatting.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..45d4553f9df4107f048da0927e193bf5efe00f66 --- /dev/null +++ b/packages/agent/test/harness/resource-formatting.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; +import { formatPromptTemplateInvocation } from "../../src/harness/prompt-templates.ts"; +import { formatSkillInvocation } from "../../src/harness/skills.ts"; + +describe("resource formatting helpers", () => { + it("formats skill invocations with additional instructions", () => { + const skill = { + name: "inspect", + description: "Inspect things", + content: "Use inspection tools.", + filePath: "/project/.pi/skills/inspect/SKILL.md", + }; + + expect(formatSkillInvocation(skill, "Check errors.")).toBe( + '\nReferences are relative to /project/.pi/skills/inspect.\n\nUse inspection tools.\n\n\nCheck errors.', + ); + }); + + it("formats prompt template invocations with positional arguments", () => { + expect( + formatPromptTemplateInvocation({ name: "review", content: "Review $1 with $ARGUMENTS" }, ["a.ts", "care"]), + ).toBe("Review a.ts with a.ts care"); + }); +}); diff --git a/packages/agent/test/harness/session-context.test.ts b/packages/agent/test/harness/session-context.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..87c4efdb4ca1fc46edd711de7612eabb0113dc88 --- /dev/null +++ b/packages/agent/test/harness/session-context.test.ts @@ -0,0 +1,260 @@ +import type { AssistantMessage } from "@earendil-works/pi-ai"; +import { describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import { buildSessionContext } from "../../src/harness/session/context.ts"; +import type { + BranchSummaryEntry, + CompactionEntry, + CustomEntry, + MessageEntry, +} from "../../src/harness/session/types.ts"; +import type { AgentMessage } from "../../src/types.ts"; + +const NOW = 1_700_000_000_000; +const usage = { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, +}; + +function userMessage(text: string): AgentMessage { + return { role: "user", content: [{ type: "text", text }], timestamp: NOW }; +} + +function assistantMessage(stopReason: AssistantMessage["stopReason"], text: string): AssistantMessage { + return { + role: "assistant", + content: + stopReason === "toolUse" + ? [{ type: "toolCall", id: "call", name: "read", arguments: {} }] + : [{ type: "text", text }], + api: "anthropic-messages", + provider: "anthropic", + model: "claude-sonnet-4-5", + usage, + stopReason, + ...(stopReason === "deferred" + ? { deferred: { provider: "anthropic", modelId: "claude-sonnet-4-5", api: "anthropic-messages", id: "job" } } + : {}), + timestamp: NOW, + }; +} + +function messageEntry(id: string, parentId: string | null, seq: number, message: AgentMessage): MessageEntry { + return { id, parentId, seq, timestamp: NOW, type: "message", message }; +} + +describe("session context projection", () => { + it("filters non-context assistant response entries while preserving valid messages", async () => { + const user = userMessage("question"); + const stopped = assistantMessage("stop", "answer"); + const length = assistantMessage("length", "truncated answer"); + const toolUse = assistantMessage("toolUse", ""); + const failed = assistantMessage("error", "failed"); + const aborted = assistantMessage("aborted", "aborted"); + const deferred = assistantMessage("deferred", ""); + const entries = [ + messageEntry("user", null, 1, user), + messageEntry("failed", "user", 2, failed), + messageEntry("stopped", "failed", 3, stopped), + messageEntry("aborted", "stopped", 4, aborted), + messageEntry("tool-use", "aborted", 5, toolUse), + messageEntry("deferred", "tool-use", 6, deferred), + messageEntry("length", "deferred", 7, length), + ]; + + expect(await buildSessionContext(entries, undefined, BACKGROUND_CONTEXT)).toEqual([ + user, + stopped, + toolUse, + length, + ]); + }); + + it("projects branch summaries in branch order", async () => { + const before = messageEntry("before", null, 1, userMessage("before summary")); + const summary: BranchSummaryEntry = { + id: "branch-summary", + parentId: before.id, + seq: 2, + timestamp: NOW, + type: "branch_summary", + fromId: "source-leaf", + summary: "work on the abandoned branch", + fromHook: false, + }; + const after = messageEntry("after", summary.id, 3, userMessage("after summary")); + + expect(await buildSessionContext([before, summary, after], undefined, BACKGROUND_CONTEXT)).toEqual([ + userMessage("before summary"), + { + role: "branchSummary", + summary: "work on the abandoned branch", + fromId: "source-leaf", + timestamp: NOW, + }, + userMessage("after summary"), + ]); + }); + + it("filters retained-tail responses without hiding the compaction summary", async () => { + const user = userMessage("kept user"); + const stopped = assistantMessage("stop", "kept answer"); + const toolUse = assistantMessage("toolUse", ""); + const length = assistantMessage("length", "kept truncated answer"); + const failed = assistantMessage("error", "failed"); + const aborted = assistantMessage("aborted", "aborted"); + const deferred = assistantMessage("deferred", ""); + const compaction: CompactionEntry = { + id: "compaction", + parentId: null, + seq: 1, + timestamp: NOW, + type: "compaction", + summary: "summary", + retainedTail: [failed, user, aborted, stopped, deferred, toolUse, length], + tokensBefore: 100, + fromHook: false, + }; + + expect(await buildSessionContext([compaction], undefined, BACKGROUND_CONTEXT)).toEqual([ + { role: "compactionSummary", summary: "summary", tokensBefore: 100, timestamp: NOW }, + user, + stopped, + toolUse, + length, + ]); + }); + it("uses only the latest compaction checkpoint and entries after it", async () => { + const beforeFirst = messageEntry("before-first", null, 1, userMessage("before first")); + const first: CompactionEntry = { + id: "first-compaction", + parentId: beforeFirst.id, + seq: 2, + timestamp: NOW, + type: "compaction", + summary: "stale summary", + retainedTail: [userMessage("stale tail")], + tokensBefore: 100, + fromHook: false, + }; + const between = messageEntry("between", first.id, 3, userMessage("between compactions")); + const latest: CompactionEntry = { + id: "latest-compaction", + parentId: between.id, + seq: 4, + timestamp: NOW, + type: "compaction", + summary: "latest summary", + retainedTail: [userMessage("latest tail")], + tokensBefore: 200, + fromHook: false, + }; + const after = messageEntry("after", latest.id, 5, userMessage("after latest")); + + expect( + await buildSessionContext([beforeFirst, first, between, latest, after], undefined, BACKGROUND_CONTEXT), + ).toEqual([ + { role: "compactionSummary", summary: "latest summary", tokensBefore: 200, timestamp: NOW }, + userMessage("latest tail"), + userMessage("after latest"), + ]); + }); + + it("projects custom entries through synchronous and asynchronous canonical projectors in branch order", async () => { + const oldCustom: CustomEntry = { + id: "old-custom", + parentId: null, + seq: 1, + timestamp: NOW, + type: "custom", + customType: "sync", + }; + const compaction: CompactionEntry = { + id: "compaction", + parentId: oldCustom.id, + seq: 2, + timestamp: NOW, + type: "compaction", + summary: "summary", + retainedTail: [], + tokensBefore: 100, + fromHook: false, + }; + const syncCustom: CustomEntry = { + id: "sync-custom", + parentId: compaction.id, + seq: 3, + timestamp: NOW, + type: "custom", + customType: "sync", + }; + const omittedCustom: CustomEntry = { + id: "omitted-custom", + parentId: syncCustom.id, + seq: 4, + timestamp: NOW, + type: "custom", + customType: "omitted", + }; + const asyncCustom: CustomEntry = { + id: "async-custom", + parentId: omittedCustom.id, + seq: 5, + timestamp: NOW, + type: "custom", + customType: "async", + }; + const projectedIds: string[] = []; + + const messages = await buildSessionContext( + [oldCustom, compaction, syncCustom, omittedCustom, asyncCustom], + { + entryProjectors: { + sync: (entry) => { + projectedIds.push(entry.id); + return [userMessage(`projected:${entry.id}`)]; + }, + async: async (entry) => { + await Promise.resolve(); + projectedIds.push(entry.id); + return [userMessage(`projected:${entry.id}`)]; + }, + }, + }, + BACKGROUND_CONTEXT, + ); + + expect(projectedIds).toEqual([syncCustom.id, asyncCustom.id]); + expect(messages).toEqual([ + { role: "compactionSummary", summary: "summary", tokensBefore: 100, timestamp: NOW }, + userMessage(`projected:${syncCustom.id}`), + userMessage(`projected:${asyncCustom.id}`), + ]); + }); + + it("propagates custom projector failures", async () => { + const custom: CustomEntry = { + id: "custom", + parentId: null, + seq: 1, + timestamp: NOW, + type: "custom", + customType: "broken", + }; + const failure = new Error("projector failed"); + + await expect( + buildSessionContext( + [custom], + { + entryProjectors: { broken: async () => Promise.reject(failure) }, + }, + BACKGROUND_CONTEXT, + ), + ).rejects.toBe(failure); + }); +}); diff --git a/packages/agent/test/harness/session-test-utils.ts b/packages/agent/test/harness/session-test-utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..5634abb9611ee5e3fc6332e2dd905c5e5e7cbcfe --- /dev/null +++ b/packages/agent/test/harness/session-test-utils.ts @@ -0,0 +1,20 @@ +import { existsSync, mkdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach } from "vitest"; + +const tempDirs: string[] = []; + +export function createTempDir(): string { + const dir = join(tmpdir(), `pi-agent-session-${Date.now()}-${Math.random().toString(36).slice(2)}`); + mkdirSync(dir, { recursive: true }); + tempDirs.push(dir); + return dir; +} + +afterEach(() => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop()!; + if (existsSync(dir)) rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/packages/agent/test/harness/skills.test.ts b/packages/agent/test/harness/skills.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..acdcba5b81f6488caccf5e342d94164acca3848e --- /dev/null +++ b/packages/agent/test/harness/skills.test.ts @@ -0,0 +1,150 @@ +import { symlink } from "node:fs/promises"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts"; +import { loadSkills, loadSourcedSkills } from "../../src/harness/skills.ts"; +import { createTempDir } from "./session-test-utils.ts"; + +describe("loadSkills", () => { + it("loads SKILL.md files through the execution environment", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + await env.createDir(".agents/skills/example", { recursive: true }, BACKGROUND_CONTEXT); + await env.writeFile( + ".agents/skills/example/SKILL.md", + `--- +name: example +description: Example skill +disable-model-invocation: true +--- +Use this skill. +`, + BACKGROUND_CONTEXT, + ); + + const { skills, diagnostics } = await loadSkills(env, ".agents/skills", BACKGROUND_CONTEXT); + + expect(diagnostics).toEqual([]); + expect(skills).toEqual([ + { + name: "example", + description: "Example skill", + content: "Use this skill.", + filePath: join(root, ".agents/skills/example/SKILL.md"), + disableModelInvocation: true, + }, + ]); + }); + + it("loads skills through symlinked directories", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + await env.createDir("actual/example", { recursive: true }, BACKGROUND_CONTEXT); + await env.writeFile( + "actual/example/SKILL.md", + "---\nname: example\ndescription: Example skill\n---\nUse this skill.", + BACKGROUND_CONTEXT, + ); + await symlink(join(root, "actual"), join(root, "skills-link")); + + const { skills } = await loadSkills(env, "skills-link", BACKGROUND_CONTEXT); + + expect(skills.map((skill) => skill.name)).toEqual(["example"]); + expect(skills[0]?.filePath).toBe(join(root, "skills-link/example/SKILL.md")); + }); + + it("preserves source info for sourced skills", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + await env.createDir("user/example", { recursive: true }, BACKGROUND_CONTEXT); + await env.writeFile( + "user/example/SKILL.md", + "---\nname: example\ndescription: Example skill\n---\nUse this skill.", + BACKGROUND_CONTEXT, + ); + + const { skills, diagnostics } = await loadSourcedSkills( + env, + [{ path: "user", source: { type: "user" as const } }], + undefined, + BACKGROUND_CONTEXT, + ); + + expect(diagnostics).toEqual([]); + expect(skills).toEqual([ + { + skill: { + name: "example", + description: "Example skill", + content: "Use this skill.", + filePath: join(root, "user/example/SKILL.md"), + disableModelInvocation: false, + }, + source: { type: "user" }, + }, + ]); + }); + + it("attaches source info to diagnostics", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + await env.createDir("user/broken", { recursive: true }, BACKGROUND_CONTEXT); + await env.writeFile("user/broken/SKILL.md", "---\nname: broken\n---\nMissing description.", BACKGROUND_CONTEXT); + + const { skills, diagnostics } = await loadSourcedSkills( + env, + [{ path: "user", source: { type: "user" as const } }], + undefined, + BACKGROUND_CONTEXT, + ); + + expect(skills).toEqual([]); + expect(diagnostics).toEqual([ + { + type: "warning", + code: "invalid_metadata", + message: "description is required", + path: join(root, "user/broken/SKILL.md"), + source: { type: "user" }, + }, + ]); + }); + + it("loads direct markdown children only from the root directory", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + await env.createDir("skills/nested", { recursive: true }, BACKGROUND_CONTEXT); + await env.writeFile("skills/root.md", "---\ndescription: Root skill\n---\nRoot content", BACKGROUND_CONTEXT); + await env.writeFile( + "skills/nested/ignored.md", + "---\ndescription: Ignored\n---\nIgnored content", + BACKGROUND_CONTEXT, + ); + + const { skills } = await loadSkills(env, "skills", BACKGROUND_CONTEXT); + + expect(skills.map((skill) => skill.name)).toEqual(["skills"]); + expect(skills[0]?.content).toBe("Root content"); + }); + + it("ignores root markdown docs that do not declare skills", async () => { + const root = createTempDir(); + const env = new NodeExecutionEnv({ cwd: root }); + await env.createDir("skills/nested-skill", { recursive: true }, BACKGROUND_CONTEXT); + await env.writeFile("skills/README.md", "# Shared skills\n\nDocumentation.", BACKGROUND_CONTEXT); + await env.writeFile("skills/AGENTS.md", "# Agent notes\n\nDocumentation.", BACKGROUND_CONTEXT); + await env.writeFile("skills/CLAUDE.md", "---\ndescription: [invalid\n---\n\nDocumentation.", BACKGROUND_CONTEXT); + await env.writeFile("skills/root.md", "---\ndescription: Root skill\n---\nRoot content", BACKGROUND_CONTEXT); + await env.writeFile( + "skills/nested-skill/SKILL.md", + "---\nname: nested-skill\ndescription: Nested skill\n---\nNested content", + BACKGROUND_CONTEXT, + ); + + const { skills, diagnostics } = await loadSkills(env, "skills", BACKGROUND_CONTEXT); + + expect(diagnostics).toEqual([]); + expect(skills.map((skill) => skill.name).sort()).toEqual(["nested-skill", "skills"]); + }); +}); diff --git a/packages/agent/test/harness/storage-backed-session.test.ts b/packages/agent/test/harness/storage-backed-session.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6ceeac147eea9133abdd57a9156ed45d7d4fc4f --- /dev/null +++ b/packages/agent/test/harness/storage-backed-session.test.ts @@ -0,0 +1,397 @@ +import type { AssistantMessage } from "@earendil-works/pi-ai"; +import { describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import type { CustomMessage } from "../../src/harness/messages.ts"; +import * as sessionWrites from "../../src/harness/session/commit.ts"; +import { MemoryStorage } from "../../src/harness/session/memory.ts"; +import { StorageBackedSession } from "../../src/harness/session/session.ts"; +import { GatingStorage, InstrumentedStorage } from "../../src/harness/session/testing/index.ts"; +import type { + MessageEntry, + NewEntry, + Session, + SessionMetadata, + SessionMutator, + Write, +} from "../../src/harness/session/types.ts"; +import * as storedValues from "../../src/harness/session/values.ts"; +import { deferred } from "./runtime/test-utils.ts"; + +const NOW = 1_700_000_000_000; +const ENTRY_ID = "00000000-0000-7000-8000-000000000001"; +const metadata = { + id: "session", + createdAt: NOW, + storageVersion: 1, + cwd: "/workspace", +} satisfies SessionMetadata; + +function commitSession(session: Session, transaction: Write[]) { + return session.mutate((mutator) => mutator.commit(transaction, BACKGROUND_CONTEXT), BACKGROUND_CONTEXT); +} + +describe("StorageBackedSession", () => { + it("delegates typed values directly without validation or cloning", async () => { + const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW })); + const session = new StorageBackedSession(metadata, storage); + const data = { nested: ["original"] }; + const transaction: Write[] = [ + sessionWrites.insertEntry({ id: ENTRY_ID, parentId: null, type: "custom", customType: "note", data }), + storedValues.setValue(storedValues.value("test.value", "state"), data), + ]; + + const result = await commitSession(session, transaction); + + expect(storage.getCommitAttempts()[0]).toBe(transaction); + const entry = (await session.getEntries([ENTRY_ID], BACKGROUND_CONTEXT)).get(ENTRY_ID); + expect(entry).toMatchObject({ seq: result.seqs[0], timestamp: NOW }); + if (entry?.type !== "custom") throw new Error("Expected custom entry"); + expect(entry.data).toBe(data); + expect( + (await session.getValue(storedValues.value("test.value", "state"), BACKGROUND_CONTEXT))?.value, + ).toBe(data); + await session.close(BACKGROUND_CONTEXT); + }); + + it("composes bound values and lists atomically with entries and usage", async () => { + const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW })); + const session = new StorageBackedSession(metadata, storage); + const scalar = storedValues.value("test.application.scalar"); + const events = storedValues.list("test.application.events"); + + const result = await session.mutate( + (mutator) => + mutator.commit( + [ + sessionWrites.insertEntry({ id: ENTRY_ID, parentId: null, type: "custom", customType: "note" }), + storedValues.setValue(scalar, "state"), + storedValues.appendList(events, "event"), + sessionWrites.insertUsage({ + id: "usage", + adjustment: false, + usage: { + input: 1, + output: 1, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 2, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + }), + ], + BACKGROUND_CONTEXT, + ), + BACKGROUND_CONTEXT, + ); + + expect(result.seqs).toHaveLength(4); + expect((await session.getValue(scalar, BACKGROUND_CONTEXT))?.seq).toBe(result.seqs[1]); + expect(await session.readList(events, undefined, BACKGROUND_CONTEXT)).toEqual([ + { seq: result.seqs[2], value: "event" }, + ]); + expect(storage.getCommitAttempts()).toHaveLength(1); + await session.close(BACKGROUND_CONTEXT); + }); + + it("serializes read-modify-write callbacks on the single Session line", async () => { + const session = new StorageBackedSession(metadata, new MemoryStorage({ now: () => NOW })); + const counter = storedValues.value("test.counter"); + const increment = () => + session.mutate(async (mutator) => { + const next = ((await mutator.getValue(counter, BACKGROUND_CONTEXT))?.value ?? 0) + 1; + await mutator.commit([storedValues.setValue(counter, next)], BACKGROUND_CONTEXT); + return next; + }, BACKGROUND_CONTEXT); + + await expect(Promise.all([increment(), increment()])).resolves.toEqual([1, 2]); + expect((await session.getValue(counter, BACKGROUND_CONTEXT))?.value).toBe(2); + await session.close(BACKGROUND_CONTEXT); + }); + + it("keeps separate direct reads and writes deliberately non-atomic", async () => { + const session = new StorageBackedSession(metadata, new MemoryStorage({ now: () => NOW })); + const counter = storedValues.value("test.counter"); + const bothRead = deferred(); + let readers = 0; + const increment = async () => { + const next = ((await session.getValue(counter, BACKGROUND_CONTEXT))?.value ?? 0) + 1; + readers++; + if (readers === 2) bothRead.resolve(); + await bothRead.promise; + await session.setValue(counter, next, BACKGROUND_CONTEXT); + }; + + await Promise.all([increment(), increment()]); + expect((await session.getValue(counter, BACKGROUND_CONTEXT))?.value).toBe(1); + await session.close(BACKGROUND_CONTEXT); + }); + + it("queues a nested public writer until its owning callback returns", async () => { + const session = new StorageBackedSession(metadata, new MemoryStorage({ now: () => NOW })); + let nested: Promise | undefined; + await session.mutate(async () => { + nested = session.setValue(storedValues.sessionName, "nested", BACKGROUND_CONTEXT); + let settled = false; + void nested.finally(() => { + settled = true; + }); + await Promise.resolve(); + expect(settled).toBe(false); + }, BACKGROUND_CONTEXT); + if (nested === undefined) throw new Error("Expected nested writer"); + await nested; + expect(await session.getName(BACKGROUND_CONTEXT)).toBe("nested"); + await session.close(BACKGROUND_CONTEXT); + }); + + it("exposes either side of an atomic multi-write commit to direct reads", async () => { + const first = storedValues.value("test.atomic", "first"); + const second = storedValues.value("test.atomic", "second"); + const storage = new GatingStorage(new MemoryStorage({ now: () => NOW })); + await storage.commit( + [storedValues.setValue(first, "old"), storedValues.setValue(second, "old")], + BACKGROUND_CONTEXT, + ); + storage.arm(); + const session = new StorageBackedSession(metadata, storage); + const committing = commitSession(session, [ + storedValues.setValue(first, "new"), + storedValues.setValue(second, "new"), + ]); + await storage.waitPending(); + + expect((await session.getValue(first, BACKGROUND_CONTEXT))?.value).toBe("old"); + expect((await session.getValue(second, BACKGROUND_CONTEXT))?.value).toBe("old"); + await storage.next(); + await committing; + expect((await session.getValue(first, BACKGROUND_CONTEXT))?.value).toBe("new"); + expect((await session.getValue(second, BACKGROUND_CONTEXT))?.value).toBe("new"); + await session.close(BACKGROUND_CONTEXT); + }); + + it("holds the explicit Session barrier through commit until end", async () => { + const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW })); + const session = new StorageBackedSession(metadata, storage); + const mutation = await session.beginMutation(BACKGROUND_CONTEXT); + let queuedStarted = false; + const queued = session.mutate(() => { + queuedStarted = true; + }, BACKGROUND_CONTEXT); + + await Promise.resolve(); + expect(queuedStarted).toBe(false); + expect(await mutation.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toBeUndefined(); + const result = await mutation.commit([], BACKGROUND_CONTEXT); + expect(result.seqs).toEqual([]); + expect(queuedStarted).toBe(false); + expect(await mutation.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toBeUndefined(); + await mutation.end(BACKGROUND_CONTEXT); + await queued; + expect(queuedStarted).toBe(true); + expect(storage.getCommitAttempts()).toEqual([[]]); + expect(() => mutation.getEntries([], BACKGROUND_CONTEXT)).toThrow("outside its mutation callback"); + expect(() => mutation.commit([], BACKGROUND_CONTEXT)).toThrow("outside its mutation callback"); + await expect(mutation.end(BACKGROUND_CONTEXT)).resolves.toBeUndefined(); + await session.close(BACKGROUND_CONTEXT); + }); + + it("allows direct reads to observe a committed value before the mutation scope ends", async () => { + const session = new StorageBackedSession(metadata, new MemoryStorage({ now: () => NOW })); + const mutation = await session.beginMutation(BACKGROUND_CONTEXT); + expect(await session.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toBeUndefined(); + await mutation.commit([storedValues.setValue(storedValues.sessionName, "visible")], BACKGROUND_CONTEXT); + let queuedStarted = false; + const queued = session.mutate(() => { + queuedStarted = true; + }, BACKGROUND_CONTEXT); + + expect((await session.getValue(storedValues.sessionName, BACKGROUND_CONTEXT))?.value).toBe("visible"); + expect(queuedStarted).toBe(false); + await mutation.end(BACKGROUND_CONTEXT); + await queued; + expect(queuedStarted).toBe(true); + await session.close(BACKGROUND_CONTEXT); + }); + + it("ends an explicit mutation without committing and lets close finish", async () => { + const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW })); + const session = new StorageBackedSession(metadata, storage); + const mutation = await session.beginMutation(BACKGROUND_CONTEXT); + let closed = false; + const closing = session.close(BACKGROUND_CONTEXT).then(() => { + closed = true; + }); + + await Promise.resolve(); + expect(closed).toBe(false); + await mutation.end(BACKGROUND_CONTEXT); + await closing; + expect(closed).toBe(true); + expect(storage.getCommitAttempts()).toEqual([]); + }); + + it("exposes explicit branch scans through the Session and callback-scoped mutator", async () => { + const storage = new MemoryStorage({ now: () => NOW }); + const session = new StorageBackedSession(metadata, storage); + const childId = "00000000-0000-7000-8000-000000000002"; + await commitSession(session, [ + sessionWrites.insertEntry({ id: ENTRY_ID, parentId: null, type: "custom", customType: "root" }), + sessionWrites.insertEntry({ id: childId, parentId: ENTRY_ID, type: "custom", customType: "child" }), + ]); + + await expect( + session.scanBranch({ start: childId, order: "oldestFirst" }, BACKGROUND_CONTEXT), + ).resolves.toMatchObject([{ id: ENTRY_ID }, { id: childId }]); + let captured: SessionMutator | undefined; + await session.mutate(async (mutator) => { + captured = mutator; + await expect(mutator.scanBranch({ start: childId, limit: 1 }, BACKGROUND_CONTEXT)).resolves.toMatchObject([ + { id: childId }, + ]); + }, BACKGROUND_CONTEXT); + const invalidated = captured; + if (invalidated === undefined) throw new Error("Expected captured mutator"); + expect(() => invalidated.scanBranch({ start: childId }, BACKGROUND_CONTEXT)).toThrow( + "outside its mutation callback", + ); + await session.close(BACKGROUND_CONTEXT); + }); + + it("rejects pending assistant entries at the durable session write boundary", async () => { + const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW })); + const session = new StorageBackedSession(metadata, storage); + const pending: AssistantMessage = { + role: "assistant", + content: [], + api: "anthropic-messages", + provider: "anthropic", + model: "claude-sonnet-4-5", + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "pending", + timestamp: NOW, + }; + + await expect( + commitSession(session, [ + sessionWrites.insertEntry({ id: ENTRY_ID, parentId: null, type: "message", message: pending }), + ]), + ).rejects.toThrow("Cannot persist a pending assistant message"); + expect(storage.getCommitAttempts()).toEqual([]); + expect(await session.getEntries([ENTRY_ID], BACKGROUND_CONTEXT)).toEqual(new Map()); + await session.close(BACKGROUND_CONTEXT); + }); + + it("trusts typed custom messages without repository schema registration", async () => { + const storage = new MemoryStorage({ now: () => NOW }); + const session = new StorageBackedSession(metadata, storage); + const message: CustomMessage = { + role: "custom", + customType: "notice", + content: "maintenance", + display: true, + timestamp: NOW, + }; + const entry: NewEntry = { id: ENTRY_ID, parentId: null, type: "message", message }; + + const result = await commitSession(session, [sessionWrites.insertEntry(entry)]); + + expect((await session.getEntries([ENTRY_ID], BACKGROUND_CONTEXT)).get(ENTRY_ID)).toEqual({ + ...entry, + seq: result.firstSeq, + timestamp: result.timestamp, + }); + await session.close(BACKGROUND_CONTEXT); + }); + + it("serializes mutations, permits one commit attempt, and invalidates the mutator", async () => { + const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW })); + const session = new StorageBackedSession(metadata, storage); + let captured: SessionMutator | undefined; + + await session.mutate(async (mutator) => { + captured = mutator; + expect(await mutator.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).toBeUndefined(); + await mutator.commit([storedValues.setValue(storedValues.sessionName, "committed")], BACKGROUND_CONTEXT); + await expect(mutator.commit([], BACKGROUND_CONTEXT)).rejects.toThrow("commit already attempted"); + }, BACKGROUND_CONTEXT); + + expect(storage.getCommitAttempts()).toHaveLength(1); + expect(await session.getName(BACKGROUND_CONTEXT)).toBe("committed"); + const invalidated = captured; + if (invalidated === undefined) throw new Error("Expected captured mutator"); + expect(() => invalidated.getEntries([], BACKGROUND_CONTEXT)).toThrow("outside its mutation callback"); + await session.close(BACKGROUND_CONTEXT); + }); + + it("consumes the commit guard when the first commit fails", async () => { + const storage = new InstrumentedStorage(new MemoryStorage({ now: () => NOW })); + const session = new StorageBackedSession(metadata, storage); + const transaction = [ + sessionWrites.insertEntry({ id: ENTRY_ID, parentId: "missing", type: "custom", customType: "note" }), + ] satisfies Write[]; + + await expect( + session.mutate(async (mutator) => { + await expect(mutator.commit(transaction, BACKGROUND_CONTEXT)).rejects.toThrow("Missing parent entry"); + await expect(mutator.commit([], BACKGROUND_CONTEXT)).rejects.toThrow("commit already attempted"); + }, BACKGROUND_CONTEXT), + ).resolves.toBeUndefined(); + expect(storage.getCommitAttempts()).toHaveLength(1); + await session.close(BACKGROUND_CONTEXT); + }); + + it("mints distinct follower ids with the leader timestamp", async () => { + const session = new StorageBackedSession(metadata, new MemoryStorage({ now: () => NOW })); + const leaderTimestamp = 0x0123456789ab; + const leader = session.idGenerator.next(leaderTimestamp); + const followers = [session.idGenerator.next(leaderTimestamp), session.idGenerator.next(leaderTimestamp)]; + const decodeTimestamp = (id: string): number => Number.parseInt(id.replaceAll("-", "").slice(0, 12), 16); + + expect([leader, ...followers].map(decodeTimestamp)).toEqual([leaderTimestamp, leaderTimestamp, leaderTimestamp]); + expect(new Set([leader, ...followers])).toHaveLength(3); + await session.close(BACKGROUND_CONTEXT); + }); + + it("accepts an injected id generator for deterministic execution tests", async () => { + let next = 0; + const idGenerator = { next: (timestampMs?: number) => `${timestampMs ?? "now"}:${++next}` }; + const session = new StorageBackedSession(metadata, new MemoryStorage({ now: () => NOW }), { idGenerator }); + + expect(session.idGenerator).toBe(idGenerator); + expect(session.idGenerator.next(7)).toBe("7:1"); + expect(session.idGenerator.next()).toBe("now:2"); + await session.close(BACKGROUND_CONTEXT); + }); + + it("exposes metadata directly and the shared UUIDv7 id generator", async () => { + const sourceMetadata = { ...metadata }; + const session = new StorageBackedSession(sourceMetadata, new MemoryStorage({ now: () => NOW })); + + expect(session.metadata).toBe(sourceMetadata); + expect(session.idGenerator.next()).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, + ); + await session.close(BACKGROUND_CONTEXT); + }); + + it("closes idempotently and rejects operations not admitted before close", async () => { + const storage = new MemoryStorage({ now: () => NOW }); + const session = new StorageBackedSession(metadata, storage); + + await Promise.all([session.close(BACKGROUND_CONTEXT), session.close(BACKGROUND_CONTEXT)]); + await expect(session.mutate(() => undefined, BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed"); + await expect(session.getEntries([], BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed"); + await expect(session.getValue(storedValues.sessionName, BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed"); + await expect(session.scanValues(storedValues.sessionName, BACKGROUND_CONTEXT)).rejects.toThrow( + "Session is closed", + ); + await expect(session.scanBranch({ start: ENTRY_ID }, BACKGROUND_CONTEXT)).rejects.toThrow("Session is closed"); + }); +}); diff --git a/packages/agent/test/harness/system-prompt.test.ts b/packages/agent/test/harness/system-prompt.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f20fbd16603b3baccd721d085abfa733f7f8ab7f --- /dev/null +++ b/packages/agent/test/harness/system-prompt.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from "vitest"; +import { formatSkillsForSystemPrompt } from "../../src/harness/system-prompt.ts"; + +const visibleSkill = { + name: "visible", + description: "Use & that", + content: "visible content", + filePath: "/skills/visible/SKILL.md", +}; + +const secondSkill = { + name: "second", + description: "Second skill", + content: "second content", + filePath: "/skills/second/SKILL.md", +}; + +const disabledSkill = { + name: "hidden", + description: "Hidden", + content: "hidden content", + filePath: "/skills/hidden/SKILL.md", + disableModelInvocation: true, +}; + +describe("formatSkillsForSystemPrompt", () => { + it("formats visible skills in order and skips model-disabled skills", () => { + expect(formatSkillsForSystemPrompt([visibleSkill, disabledSkill, secondSkill])).toBe( + `The following skills provide specialized instructions for specific tasks. +Read the full skill file when the task matches its description. +When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands. + + + + visible + Use <this> & that + /skills/visible/SKILL.md + + + second + Second skill + /skills/second/SKILL.md + +`, + ); + }); + + it("returns an empty string when no skills are model-visible", () => { + expect(formatSkillsForSystemPrompt([disabledSkill])).toBe(""); + }); + + it("escapes XML in all model-visible skill fields", () => { + expect( + formatSkillsForSystemPrompt([ + { + name: "a&b", + description: `Quote "double" and 'single'`, + content: "content", + filePath: '/skills/&"quote"/SKILL.md', + }, + ]), + ).toContain( + "a&b\n Quote "double" and 'single'\n /skills/<bad>&"quote"/SKILL.md", + ); + }); +}); diff --git a/packages/agent/test/harness/telemetry.test.ts b/packages/agent/test/harness/telemetry.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a5c036a097b5dcc307fa7031d4d073b1f38ce3f --- /dev/null +++ b/packages/agent/test/harness/telemetry.test.ts @@ -0,0 +1,204 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { createTypedSpanStarter, NOOP_TELEMETRY_CONTEXT, type TelemetryContext } from "@earendil-works/pi-telemetry"; +import { describe, expect, expectTypeOf, it } from "vitest"; +import { renderAgentTelemetrySchemaMarkdown } from "../../scripts/generate-telemetry-docs.ts"; +import { BACKGROUND_CONTEXT, withTelemetryContext } from "../../src/harness/context.ts"; +import { + AGENT_TELEMETRY_SCHEMAS, + AI_TELEMETRY_SCHEMA, + type AiSpanEndAttributes, + type AiSpanStartAttributes, + HARNESS_TELEMETRY_SCHEMA, + type HarnessSpanEndAttributes, + type HarnessSpanStartAttributes, + startAiSpan, + startHarnessSpan, +} from "../../src/harness/telemetry.ts"; + +describe("agent telemetry schemas", () => { + it("serializes both schemas and generates the checked-in reference", () => { + expect(() => JSON.stringify(AI_TELEMETRY_SCHEMA)).not.toThrow(); + expect(() => JSON.stringify(HARNESS_TELEMETRY_SCHEMA)).not.toThrow(); + expect(AGENT_TELEMETRY_SCHEMAS).toEqual([AI_TELEMETRY_SCHEMA, HARNESS_TELEMETRY_SCHEMA]); + expect(Object.keys(HARNESS_TELEMETRY_SCHEMA.spans)).toEqual([ + "pi.harness.run", + "pi.harness.compaction", + "pi.harness.navigation", + "pi.harness.checkpoint", + "pi.harness.turn", + "pi.harness.step", + "pi.harness.tool", + "pi.harness.hook", + "pi.harness.sleep", + "pi.harness.event_handler", + "pi.session.write", + ]); + const actual = readFileSync(resolve(import.meta.dirname, "../../docs/telemetry-schema.md"), "utf8"); + expect(actual).toBe(renderAgentTelemetrySchemaMarkdown()); + }); + + it("starts AI-request and harness spans through one composed typed starter", async () => { + const startSpan = createTypedSpanStarter(NOOP_TELEMETRY_CONTEXT, AGENT_TELEMETRY_SCHEMAS); + await startSpan( + "pi.harness.step", + { + "pi.lane.name": "main", + "pi.operation.id": "operation", + "pi.step.kind": "assistant", + "pi.step.attempt": 1, + }, + async (stepSpan, startChildSpan) => { + stepSpan.setAttributes({ "pi.step.outcome": "succeeded" }); + await startChildSpan( + "pi.ai.request", + { + "pi.ai.operation": "stream", + "pi.ai.provider": "provider", + "pi.ai.model": "model", + "pi.ai.api": "api", + "pi.ai.streaming": true, + }, + (requestSpan) => { + requestSpan.setAttributes({ "pi.ai.response.stop_reason": "stop" }); + }, + ); + }, + ); + }); + + it("infers exact AI start and optional end attributes", async () => { + type Start = AiSpanStartAttributes<"pi.ai.request">; + type End = AiSpanEndAttributes<"pi.ai.request">; + expectTypeOf().toMatchTypeOf<{ + "pi.ai.operation": "stream" | "fetch_deferred" | "cancel_deferred" | "generate_images"; + "pi.ai.provider": string; + "pi.ai.model": string; + "pi.ai.api": string; + "pi.ai.streaming": boolean; + "pi.ai.deferred"?: boolean; + }>(); + expectTypeOf().toEqualTypeOf< + "stop" | "length" | "tool_use" | "error" | "aborted" | "deferred" | undefined + >(); + + const telemetryContext: TelemetryContext = NOOP_TELEMETRY_CONTEXT; + const context = withTelemetryContext(telemetryContext, BACKGROUND_CONTEXT); + await startAiSpan( + "pi.ai.request", + { + "pi.ai.operation": "stream", + "pi.ai.provider": "provider", + "pi.ai.model": "model", + "pi.ai.api": "api", + "pi.ai.streaming": true, + }, + (span) => { + span.setAttributes({ "pi.ai.response.stop_reason": "tool_use" }); + // @ts-expect-error pi.ai.request declares no span events + span.addEvent("chunk"); + }, + context, + ); + + const compileTimeFailures = () => { + const extraAttributes = { + "pi.ai.operation": "stream", + "pi.ai.provider": "provider", + "pi.ai.model": "model", + "pi.ai.api": "api", + "pi.ai.streaming": true, + "pi.ai.unknown": true, + } as const; + // @ts-expect-error variables with unknown attributes are rejected + void startAiSpan("pi.ai.request", extraAttributes, () => {}, context); + // @ts-expect-error missing required start attributes + void startAiSpan("pi.ai.request", { "pi.ai.operation": "stream" }, () => {}, context); + }; + expectTypeOf(compileTimeFailures).toBeFunction(); + }); + + it("infers per-span harness literals and optional completion enrichment", async () => { + type RunStart = HarnessSpanStartAttributes<"pi.harness.run">; + type RunEnd = HarnessSpanEndAttributes<"pi.harness.run">; + type WriteStart = HarnessSpanStartAttributes<"pi.session.write">; + type WriteEnd = HarnessSpanEndAttributes<"pi.session.write">; + expectTypeOf().toEqualTypeOf<"run">(); + expectTypeOf().toEqualTypeOf< + "completed" | "aborted" | "failed" | "suspended" | undefined + >(); + const writeStart = { + "pi.session.id": "session", + "pi.session.item_count": 2, + "pi.session.item_kinds": ["entry", "value", "list"], + } satisfies WriteStart; + const writeEnd = { + "pi.session.first_seq": 1, + "pi.session.last_seq": 2, + } satisfies WriteEnd; + expectTypeOf(writeStart["pi.session.item_count"]).toEqualTypeOf(); + expectTypeOf(writeEnd["pi.session.last_seq"]).toEqualTypeOf(); + + const telemetryContext: TelemetryContext = NOOP_TELEMETRY_CONTEXT; + const context = withTelemetryContext(telemetryContext, BACKGROUND_CONTEXT); + await startHarnessSpan( + "pi.harness.run", + { + "pi.session.id": "session", + "pi.lane.name": "main", + "pi.operation.id": "operation", + "pi.operation.kind": "run", + "pi.operation.recovery": false, + }, + (span) => { + span.setAttributes({ "pi.operation.outcome": "completed" }); + span.setAttributes({}); + // @ts-expect-error the harness schema declares no span events + span.addEvent("result"); + }, + context, + ); + + const compileTimeFailures = () => { + const extraRunAttributes = { + "pi.session.id": "session", + "pi.lane.name": "main", + "pi.operation.id": "operation", + "pi.operation.kind": "run", + "pi.operation.recovery": false, + "pi.unknown": true, + } as const; + // @ts-expect-error variables with unknown attributes are rejected + void startHarnessSpan("pi.harness.run", extraRunAttributes, () => {}, context); + void startHarnessSpan( + "pi.harness.checkpoint", + { + "pi.lane.name": "main", + "pi.operation.id": "operation", + "pi.checkpoint.kind": "normal", + }, + (span) => { + // @ts-expect-error empty end schemas reject every attribute + span.setAttributes({ "pi.unknown": true }); + }, + context, + ); + void startHarnessSpan( + "pi.harness.run", + { + "pi.session.id": "session", + "pi.lane.name": "main", + "pi.operation.id": "operation", + // @ts-expect-error run spans accept only the run operation kind + "pi.operation.kind": "navigation", + "pi.operation.recovery": false, + }, + () => {}, + context, + ); + // @ts-expect-error missing required run start attributes + void startHarnessSpan("pi.harness.run", {}, () => {}, context); + }; + expectTypeOf(compileTimeFailures).toBeFunction(); + }); +}); diff --git a/packages/agent/test/harness/text-line-reader.test.ts b/packages/agent/test/harness/text-line-reader.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0785f47cbabd12b4191e5ac27585f9252f5c32e --- /dev/null +++ b/packages/agent/test/harness/text-line-reader.test.ts @@ -0,0 +1,120 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { BACKGROUND_CONTEXT, withAbortSignal } from "../../src/harness/context.ts"; +import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts"; +import { getOrThrow, type TextLine, type TextLineReader } from "../../src/harness/types.ts"; + +let root: string; +let env: NodeExecutionEnv; +const readers: TextLineReader[] = []; + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "pi-text-line-reader-")); + env = new NodeExecutionEnv({ cwd: root }); +}); + +afterEach(async () => { + await Promise.all(readers.splice(0).map((reader) => reader.close(BACKGROUND_CONTEXT))); + await rm(root, { recursive: true, force: true }); +}); + +async function openReader(content: string | Uint8Array): Promise { + await writeFile(join(root, "text.txt"), content); + const reader = getOrThrow(await env.openTextLineReader("text.txt", BACKGROUND_CONTEXT)); + readers.push(reader); + return reader; +} + +async function readLines(reader: TextLineReader): Promise { + const lines: TextLine[] = []; + while (true) { + const line = getOrThrow(await reader.readLine(BACKGROUND_CONTEXT)); + if (line === undefined) return lines; + lines.push(line); + } +} + +describe("TextLineReader", () => { + it("decodes Unicode, blank lines, and a torn final line", async () => { + const reader = await openReader("hé🙂\n\n\n終\ntorn"); + expect(await readLines(reader)).toEqual([ + { text: "hé🙂", terminated: true }, + { text: "", terminated: true }, + { text: "", terminated: true }, + { text: "終", terminated: true }, + { text: "torn", terminated: false }, + ]); + expect(getOrThrow(await reader.readLine(BACKGROUND_CONTEXT))).toBeUndefined(); + }); + + it("reads an empty file", async () => { + const reader = await openReader(""); + expect(await readLines(reader)).toEqual([]); + }); + + it("decodes multibyte characters split across 64 KiB chunks", async () => { + const first = `${"a".repeat(64 * 1024 - 1)}🙂${"é".repeat(40_000)}\n`; + const reader = await openReader(`${first}終`); + expect(await readLines(reader)).toEqual([ + { text: first.slice(0, -1), terminated: true }, + { text: "終", terminated: false }, + ]); + }); + + it("replaces malformed and incomplete UTF-8", async () => { + const reader = await openReader(new Uint8Array([0xff, 0x0a, 0xe2, 0x82])); + expect(await readLines(reader)).toEqual([ + { text: "�", terminated: true }, + { text: "�", terminated: false }, + ]); + }); + + it("rejects an open with a pre-aborted context", async () => { + await writeFile(join(root, "text.txt"), "one\n"); + const controller = new AbortController(); + controller.abort(); + const context = withAbortSignal(controller.signal, BACKGROUND_CONTEXT); + expect(await env.openTextLineReader("text.txt", context)).toMatchObject({ + ok: false, + error: { code: "aborted" }, + }); + }); + + it("does not consume a buffered line when its context is pre-aborted", async () => { + const reader = await openReader("one\ntwo\n"); + getOrThrow(await reader.readLine(BACKGROUND_CONTEXT)); + const controller = new AbortController(); + controller.abort(); + const context = withAbortSignal(controller.signal, BACKGROUND_CONTEXT); + expect(await reader.readLine(context)).toMatchObject({ ok: false, error: { code: "aborted" } }); + expect(getOrThrow(await reader.readLine(BACKGROUND_CONTEXT))?.text).toBe("two"); + }); + + it("honors cancellation during a read and allows retry", async () => { + const reader = await openReader(`${"é".repeat(70_000)}\nlast`); + const controller = new AbortController(); + const pending = reader.readLine(withAbortSignal(controller.signal, BACKGROUND_CONTEXT)); + controller.abort(); + expect(await pending).toMatchObject({ ok: false, error: { code: "aborted" } }); + expect((await readLines(reader)).map((line) => line.text)).toEqual(["é".repeat(70_000), "last"]); + }); + + it("closes idempotently even with an aborted context and rejects later reads", async () => { + const reader = await openReader("one\ntwo\n"); + getOrThrow(await reader.readLine(BACKGROUND_CONTEXT)); + const controller = new AbortController(); + controller.abort(); + await expect(reader.close(withAbortSignal(controller.signal, BACKGROUND_CONTEXT))).resolves.toBeUndefined(); + await expect(reader.close(BACKGROUND_CONTEXT)).resolves.toBeUndefined(); + expect(await reader.readLine(BACKGROUND_CONTEXT)).toMatchObject({ ok: false, error: { code: "invalid" } }); + }); + + it("returns a FileError for a missing file", async () => { + expect(await env.openTextLineReader("missing.txt", BACKGROUND_CONTEXT)).toMatchObject({ + ok: false, + error: { code: "not_found", path: join(root, "missing.txt") }, + }); + }); +}); diff --git a/packages/agent/test/harness/tools.test.ts b/packages/agent/test/harness/tools.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9bae006a3811daf4dbb9768148080af9416dd579 --- /dev/null +++ b/packages/agent/test/harness/tools.test.ts @@ -0,0 +1,782 @@ +import { symlink } from "node:fs/promises"; +import { applyPatch } from "diff"; +import { describe, expect, it, vi } from "vitest"; +import { BACKGROUND_CONTEXT, type Context, withAbortSignal } from "../../src/harness/context.ts"; +import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts"; +import { type BashToolDetails, createBashTool } from "../../src/harness/tools/bash.ts"; +import { createEditTool } from "../../src/harness/tools/edit.ts"; +import { createReadTool } from "../../src/harness/tools/read.ts"; +import { createWriteTool } from "../../src/harness/tools/write.ts"; +import { + ExecutionError, + err, + type FileError, + getOrThrow, + ok, + type Result, + type ShellExecOptions, + type ShellExecResult, +} from "../../src/harness/types.ts"; +import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, truncateTail } from "../../src/harness/utils/truncate.ts"; +import { createTempDir } from "./session-test-utils.ts"; + +const noUpdate = () => {}; + +function textOutput(result: { content: Array<{ type: string; text?: string }> }): string { + return result.content.flatMap((part) => (part.type === "text" ? [part.text ?? ""] : [])).join("\n"); +} + +function createContext() { + const env = new NodeExecutionEnv({ cwd: createTempDir() }); + return { env }; +} + +function deferred(): { promise: Promise; resolve: () => void } { + let resolve = () => {}; + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise; + }); + return { promise, resolve }; +} + +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +class SlowReadExecutionEnv extends NodeExecutionEnv { + override async readTextFile(path: string, context: Context): Promise> { + await delay(20); + return super.readTextFile(path, context); + } +} + +class BlockingWriteExecutionEnv extends NodeExecutionEnv { + readonly firstWriteStarted = deferred(); + readonly finishFirstWrite = deferred(); + secondWriteStarted = false; + + override async writeFile( + path: string, + content: string | Uint8Array, + context: Context, + ): Promise> { + if (content === "first\n") { + this.firstWriteStarted.resolve(); + await this.finishFirstWrite.promise; + } else if (content === "second\n") { + this.secondWriteStarted = true; + } + return super.writeFile(path, content, context); + } +} + +class BlockingEditExecutionEnv extends NodeExecutionEnv { + readonly firstEditWriteStarted = deferred(); + readonly finishFirstEditWrite = deferred(); + firstEditWriteSettled = false; + secondEditWriteStarted = false; + + override async writeFile( + path: string, + content: string | Uint8Array, + context: Context, + ): Promise> { + if (content === "ALPHA\nbeta\n") { + this.firstEditWriteStarted.resolve(); + await this.finishFirstEditWrite.promise; + const result = await super.writeFile(path, content, BACKGROUND_CONTEXT); + this.firstEditWriteSettled = true; + return result; + } + if (content === "ALPHA\nBETA\n" || content === "alpha\nBETA\n") { + this.secondEditWriteStarted = true; + } + return super.writeFile(path, content, context); + } +} + +function fakeShellOutput(text: string, options: ShellExecOptions | undefined, spillPath?: string): ShellExecResult { + const limits = options?.capture?.limits ?? { + maxBytes: DEFAULT_MAX_BYTES, + maxLines: DEFAULT_MAX_LINES, + retain: "tail" as const, + }; + const truncated = truncateTail(text, limits); + const { content, ...truncation } = truncated; + options?.onUpdate?.( + { + kind: "replace", + output: { text: content, truncation, ...(spillPath === undefined ? {} : { spillPath }) }, + }, + BACKGROUND_CONTEXT, + ); + return { exitCode: 0, truncation, ...(spillPath === undefined ? {} : { spillPath }) }; +} + +class LateOutputExecutionEnv extends NodeExecutionEnv { + override async exec( + _command: string, + options: ShellExecOptions | undefined, + context: Context, + ): Promise> { + const result = fakeShellOutput("before\n", options); + setTimeout(() => { + const truncation = truncateTail("before\nlate\n", options?.capture?.limits); + options?.onUpdate?.({ kind: "replace", output: { text: truncation.content, truncation } }, context); + }, 0); + return ok(result); + } +} + +const TRUNCATED_OUTPUT_LINES = DEFAULT_MAX_LINES + 1; +const invocation = { + invocationId: "test-result", + operationId: "test-operation", + turnId: "test-turn", + getMemo: async () => undefined, + setMemo: async () => {}, +}; + +class CheckpointOutputExecutionEnv extends NodeExecutionEnv { + override async exec( + _command: string, + options: ShellExecOptions | undefined, + _context: Context, + ): Promise> { + fakeShellOutput("one\n", options); + await delay(2_100); + fakeShellOutput("one\ntwo\n", options); + await delay(100); + fakeShellOutput("one\ntwo\nthree\n", options); + await delay(2_000); + return ok(fakeShellOutput("one\ntwo\nthree\nfour\n", options)); + } +} + +class TimeoutOutputExecutionEnv extends NodeExecutionEnv { + override async exec( + _command: string, + options: ShellExecOptions | undefined, + context: Context, + ): Promise> { + const output = `${Array.from({ length: TRUNCATED_OUTPUT_LINES }, (_, index) => `line-${index + 1}`).join("\n")}\n`; + const spillPath = getOrThrow(await this.createTempFile({ prefix: "timeout-", suffix: ".log" }, context)); + getOrThrow(await this.writeFile(spillPath, output, context)); + fakeShellOutput(output, options, spillPath); + return err(new ExecutionError("timeout", `timeout:${options?.timeout}`)); + } +} + +function createTinyBmp(): Uint8Array { + const bytes = new Uint8Array(58); + const view = new DataView(bytes.buffer); + bytes[0] = 0x42; + bytes[1] = 0x4d; + view.setUint32(2, bytes.length, true); + view.setUint32(10, 54, true); + view.setUint32(14, 40, true); + view.setInt32(18, 1, true); + view.setInt32(22, 1, true); + view.setUint16(26, 1, true); + view.setUint16(28, 24, true); + view.setUint32(34, 4, true); + return bytes; +} + +describe("AgentHarness tools", () => { + describe("read", () => { + it("reads text with offsets, limits, and continuation notices", async () => { + const context = createContext(); + getOrThrow( + await context.env.writeFile( + "test.txt", + Array.from({ length: 100 }, (_, index) => `Line ${index + 1}`).join("\n"), + BACKGROUND_CONTEXT, + ), + ); + + const result = await createReadTool().execute( + "read-1", + { path: "test.txt", offset: 41, limit: 20 }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + const output = textOutput(result); + + expect(output).not.toContain("Line 40"); + expect(output).toContain("Line 41"); + expect(output).toContain("Line 60"); + expect(output).not.toContain("Line 61"); + expect(output).toContain("[40 more lines in file. Use offset=61 to continue.]"); + }); + + it("truncates large text by line count", async () => { + const context = createContext(); + getOrThrow( + await context.env.writeFile( + "large.txt", + Array.from({ length: 2500 }, (_, index) => `Line ${index + 1}`).join("\n"), + BACKGROUND_CONTEXT, + ), + ); + + const result = await createReadTool().execute( + "read-2", + { path: "large.txt" }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + + expect(textOutput(result)).toContain("[Showing lines 1-2000 of 2500. Use offset=2001 to continue.]"); + expect(result.details?.truncation).toMatchObject({ + truncated: true, + truncatedBy: "lines", + totalLines: 2500, + outputLines: 2000, + }); + }); + + it("does not count a trailing newline as an extra line at the truncation limit", async () => { + const context = createContext(); + getOrThrow( + await context.env.writeFile( + "exact.txt", + `${Array.from({ length: 2000 }, () => "x").join("\n")}\n`, + BACKGROUND_CONTEXT, + ), + ); + + const result = await createReadTool().execute( + "read-exact", + { path: "exact.txt" }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + + expect(result.details).toBeUndefined(); + expect(textOutput(result)).not.toContain("Use offset="); + }); + + it("rejects offsets beyond the file", async () => { + const context = createContext(); + getOrThrow(await context.env.writeFile("short.txt", "one\ntwo\nthree", BACKGROUND_CONTEXT)); + + await expect( + createReadTool().execute( + "read-3", + { path: "short.txt", offset: 100 }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ), + ).rejects.toThrow("Offset 100 is beyond end of file (3 lines total)"); + }); + + it("detects supported images by content", async () => { + const context = createContext(); + const png = Uint8Array.from( + Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGD4DwABBAEAX+XDSwAAAABJRU5ErkJggg==", + "base64", + ), + ); + getOrThrow(await context.env.writeFile("image.txt", png, BACKGROUND_CONTEXT)); + + const result = await createReadTool().execute( + "read-4", + { path: "image.txt" }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + + expect(textOutput(result)).toContain("Read image file [image/png]"); + expect(result.content).toContainEqual({ + type: "image", + data: Buffer.from(png).toString("base64"), + mimeType: "image/png", + }); + }); + + it("delegates image conversion and resizing to an injected processor", async () => { + const context = createContext(); + const bmp = createTinyBmp(); + getOrThrow(await context.env.writeFile("image.bmp", bmp, BACKGROUND_CONTEXT)); + let received: { bytes: Uint8Array; mimeType: string; autoResizeImages: boolean } | undefined; + const tool = createReadTool({ + autoResizeImages: false, + imageProcessor: async (bytes, mimeType, options) => { + received = { bytes, mimeType, autoResizeImages: options.autoResizeImages }; + return { + ok: true, + data: "converted", + mimeType: "image/png", + hints: ["[Image converted from image/bmp to image/png.]"], + }; + }, + }); + + const result = await tool.execute( + "read-bmp", + { path: "image.bmp" }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + + expect(received).toMatchObject({ mimeType: "image/bmp", autoResizeImages: false }); + expect(Array.from(received?.bytes ?? [])).toEqual(Array.from(bmp)); + expect(textOutput(result)).toContain("[Image converted from image/bmp to image/png.]"); + expect(result.content).toContainEqual({ type: "image", data: "converted", mimeType: "image/png" }); + }); + }); + + describe("write", () => { + it("writes files and creates parent directories", async () => { + const context = createContext(); + const result = await createWriteTool().execute( + "write-1", + { path: "nested/dir/file.txt", content: "hello" }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + + expect(textOutput(result)).toBe("Successfully wrote to nested/dir/file.txt"); + expect(getOrThrow(await context.env.readTextFile("nested/dir/file.txt", BACKGROUND_CONTEXT))).toBe("hello"); + }); + + it("keeps the mutation queue locked until an aborted write settles", async () => { + const env = new BlockingWriteExecutionEnv({ cwd: createTempDir() }); + const tool = createWriteTool(); + const controller = new AbortController(); + const firstWrite = tool.execute( + "write-first", + { path: "file.txt", content: "first\n" }, + noUpdate, + { + env, + }, + invocation, + withAbortSignal(controller.signal, BACKGROUND_CONTEXT), + ); + await env.firstWriteStarted.promise; + controller.abort(); + const secondWrite = tool.execute( + "write-second", + { path: "file.txt", content: "second\n" }, + noUpdate, + { env }, + invocation, + BACKGROUND_CONTEXT, + ); + + await delay(20); + expect(env.secondWriteStarted).toBe(false); + env.finishFirstWrite.resolve(); + await expect(firstWrite).rejects.toThrow(); + await secondWrite; + expect(getOrThrow(await env.readTextFile("file.txt", BACKGROUND_CONTEXT))).toBe("second\n"); + }); + }); + + describe("edit", () => { + it("applies disjoint edits and returns both diff formats", async () => { + const context = createContext(); + const original = "alpha\nbeta\ngamma\ndelta\n"; + getOrThrow(await context.env.writeFile("edit.txt", original, BACKGROUND_CONTEXT)); + + const result = await createEditTool().execute( + "edit-1", + { + path: "edit.txt", + edits: [ + { oldText: "alpha\n", newText: "ALPHA\n" }, + { oldText: "gamma\n", newText: "GAMMA\n" }, + ], + }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + + expect(textOutput(result)).toBe("Successfully replaced 2 block(s) in edit.txt."); + expect(result.details?.diff).toContain("ALPHA"); + expect(result.details?.diff).toContain("GAMMA"); + expect(applyPatch(original, result.details?.patch ?? "")).toBe("ALPHA\nbeta\nGAMMA\ndelta\n"); + expect(getOrThrow(await context.env.readTextFile("edit.txt", BACKGROUND_CONTEXT))).toBe( + "ALPHA\nbeta\nGAMMA\ndelta\n", + ); + }); + + it("matches all edits against the original and rejects overlaps", async () => { + const context = createContext(); + getOrThrow(await context.env.writeFile("edit.txt", "one\ntwo\nthree\n", BACKGROUND_CONTEXT)); + + await expect( + createEditTool().execute( + "edit-2", + { + path: "edit.txt", + edits: [ + { oldText: "one\ntwo\n", newText: "ONE\nTWO\n" }, + { oldText: "two\nthree\n", newText: "TWO\nTHREE\n" }, + ], + }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ), + ).rejects.toThrow(/overlap/); + expect(getOrThrow(await context.env.readTextFile("edit.txt", BACKGROUND_CONTEXT))).toBe("one\ntwo\nthree\n"); + }); + + it("rejects missing and duplicate target text", async () => { + const context = createContext(); + getOrThrow(await context.env.writeFile("edit.txt", "foo foo foo", BACKGROUND_CONTEXT)); + const tool = createEditTool(); + + await expect( + tool.execute( + "edit-3", + { path: "edit.txt", edits: [{ oldText: "bar", newText: "baz" }] }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ), + ).rejects.toThrow(/Could not find the exact text/); + await expect( + tool.execute( + "edit-4", + { path: "edit.txt", edits: [{ oldText: "foo", newText: "bar" }] }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ), + ).rejects.toThrow(/Found 3 occurrences/); + }); + + it("keeps the mutation queue locked until an aborted edit write settles", async () => { + const env = new BlockingEditExecutionEnv({ cwd: createTempDir() }); + getOrThrow(await env.writeFile("file.txt", "alpha\nbeta\n", BACKGROUND_CONTEXT)); + const tool = createEditTool(); + const controller = new AbortController(); + const firstEdit = tool.execute( + "edit-first", + { path: "file.txt", edits: [{ oldText: "alpha", newText: "ALPHA" }] }, + noUpdate, + { env }, + invocation, + withAbortSignal(controller.signal, BACKGROUND_CONTEXT), + ); + await env.firstEditWriteStarted.promise; + controller.abort(); + const secondEdit = tool.execute( + "edit-second", + { path: "file.txt", edits: [{ oldText: "beta", newText: "BETA" }] }, + noUpdate, + { env }, + invocation, + BACKGROUND_CONTEXT, + ); + + await delay(20); + expect(env.secondEditWriteStarted).toBe(false); + env.finishFirstEditWrite.resolve(); + await expect(firstEdit).rejects.toThrow("Operation aborted"); + await secondEdit; + expect(env.firstEditWriteSettled).toBe(true); + expect(getOrThrow(await env.readTextFile("file.txt", BACKGROUND_CONTEXT))).toBe("ALPHA\nBETA\n"); + }); + + it("serializes concurrent edits through canonical and symlink paths", async () => { + const env = new SlowReadExecutionEnv({ cwd: createTempDir() }); + getOrThrow(await env.writeFile("target.txt", "alpha\nbeta\ngamma\n", BACKGROUND_CONTEXT)); + await symlink("target.txt", `${env.cwd}/link.txt`); + const tool = createEditTool(); + + await Promise.all([ + tool.execute( + "edit-target", + { path: "target.txt", edits: [{ oldText: "alpha", newText: "ALPHA" }] }, + noUpdate, + { env }, + invocation, + BACKGROUND_CONTEXT, + ), + tool.execute( + "edit-link", + { path: "link.txt", edits: [{ oldText: "beta", newText: "BETA" }] }, + noUpdate, + { env }, + invocation, + BACKGROUND_CONTEXT, + ), + ]); + + expect(getOrThrow(await env.readTextFile("target.txt", BACKGROUND_CONTEXT))).toBe("ALPHA\nBETA\ngamma\n"); + }); + + it("edits regular files through symlinks", async () => { + const context = createContext(); + getOrThrow(await context.env.writeFile("target.txt", "before\n", BACKGROUND_CONTEXT)); + await symlink("target.txt", `${context.env.cwd}/link.txt`); + + await createEditTool().execute( + "edit-symlink", + { path: "link.txt", edits: [{ oldText: "before", newText: "after" }] }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + + expect(getOrThrow(await context.env.readTextFile("target.txt", BACKGROUND_CONTEXT))).toBe("after\n"); + }); + + it("preserves BOM and CRLF line endings", async () => { + const context = createContext(); + getOrThrow(await context.env.writeFile("edit.txt", "\uFEFFone\r\ntwo\r\n", BACKGROUND_CONTEXT)); + + await createEditTool().execute( + "edit-5", + { path: "edit.txt", edits: [{ oldText: "two", newText: "TWO" }] }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + + expect(getOrThrow(await context.env.readTextFile("edit.txt", BACKGROUND_CONTEXT))).toBe( + "\uFEFFone\r\nTWO\r\n", + ); + }); + }); + + describe("bash", () => { + it("executes commands and combines stdout and stderr", async () => { + const context = createContext(); + const result = await createBashTool().execute( + "bash-1", + { command: "printf out; printf err >&2" }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + + expect(textOutput(result)).toContain("out"); + expect(textOutput(result)).toContain("err"); + }); + + it("reports nonzero exits and timeouts", async () => { + const context = createContext(); + const tool = createBashTool(); + + await expect( + tool.execute( + "bash-2", + { command: "printf failed; exit 7" }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ), + ).rejects.toThrow(/failed[\s\S]*Command exited with code 7/); + await expect( + tool.execute( + "bash-3", + { command: "sleep 2", timeout: 0.01 }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ), + ).rejects.toThrow(/Command timed out after 0.01 seconds/); + }); + + it("preserves truncated output when a command times out", async () => { + const context = { env: new TimeoutOutputExecutionEnv({ cwd: createTempDir() }) }; + let error: unknown; + try { + await createBashTool().execute( + "bash-timeout-output", + { command: "emit-output-then-time-out", timeout: 0.05 }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + } catch (cause) { + error = cause; + } + + expect(error).toBeInstanceOf(Error); + const message = (error as Error).message; + expect(message).toContain("Command timed out after 0.05 seconds"); + const fullOutputPath = message.match(/Full output: ([^\]\n]+)/)?.[1]; + expect(fullOutputPath).toBeDefined(); + const fullOutput = getOrThrow(await context.env.readTextFile(fullOutputPath!, BACKGROUND_CONTEXT)); + expect(fullOutput).toContain("line-1\nline-2"); + expect(fullOutput).toContain(`line-${DEFAULT_MAX_LINES}\nline-${TRUNCATED_OUTPUT_LINES}`); + }); + + it("ignores output callbacks after execution settles", async () => { + const env = new LateOutputExecutionEnv({ cwd: createTempDir() }); + const updates: string[] = []; + const result = await createBashTool().execute( + "bash-late", + { command: "late" }, + (update) => updates.push(textOutput(update)), + { env }, + invocation, + BACKGROUND_CONTEXT, + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(textOutput(result)).toBe("before\n"); + expect(updates.some((update) => update.includes("late"))).toBe(false); + }); + + it("reports the total size of an oversized final line", async () => { + const context = createContext(); + const result = await createBashTool().execute( + "bash-long-line", + { command: "printf '%060000d' 0" }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + + expect(textOutput(result)).toMatch(/Showing last 50\.0KB of line 1 \(line is 58\.6KB\)\. Full output:/); + }); + + it("prepares command, cwd, and an explicit environment with the turn context", async () => { + const env = new NodeExecutionEnv({ + cwd: createTempDir(), + shellEnv: { PI_BASH_PREPARE_INHERITED: "inherited" }, + }); + getOrThrow(await env.createDir("workspace", undefined, BACKGROUND_CONTEXT)); + const context = { env, workspace: `${env.cwd}/workspace` }; + const controller = new AbortController(); + let receivedContext: typeof context | undefined; + let receivedSignal: AbortSignal | undefined; + const tool = createBashTool({ + commandPrefix: "prefix=ready", + prepare: async (execution, turnContext, callContext) => { + receivedContext = turnContext; + receivedSignal = callContext.abortSignal; + execution.cwd = turnContext.workspace; + execution.env = { PI_BASH_PREPARE_EXPLICIT: "explicit" }; + execution.inheritEnv = false; + execution.command += `\nprintf '%s:%s:%s:%s' "$prefix" "\${PI_BASH_PREPARE_INHERITED-}" "$PI_BASH_PREPARE_EXPLICIT" "$PWD"`; + }, + }); + + const result = await tool.execute( + "bash-prepare", + { command: ":" }, + noUpdate, + context, + invocation, + withAbortSignal(controller.signal, BACKGROUND_CONTEXT), + ); + + expect(receivedContext).toBe(context); + expect(receivedSignal).toBe(controller.signal); + expect(textOutput(result)).toBe( + `ready::explicit:${getOrThrow(await env.canonicalPath(context.workspace, BACKGROUND_CONTEXT))}`, + ); + }); + + it("supports command prefixes", async () => { + const context = createContext(); + const result = await createBashTool({ commandPrefix: "value=hello" }).execute( + "bash-4", + { command: "printf $value" }, + noUpdate, + context, + invocation, + BACKGROUND_CONTEXT, + ); + + expect(textOutput(result)).toBe("hello"); + }); + + it("requests distinct bounded checkpoints at most every two seconds", async () => { + vi.useFakeTimers({ now: 0 }); + try { + const env = new CheckpointOutputExecutionEnv({ cwd: createTempDir() }); + const checkpoints: string[] = []; + const execution = createBashTool().execute( + "bash-checkpoints", + { command: "controlled" }, + (update, options) => { + if (options?.checkpoint === true) checkpoints.push(textOutput(update)); + }, + { env }, + invocation, + BACKGROUND_CONTEXT, + ); + await vi.advanceTimersByTimeAsync(4_500); + await execution; + + expect(checkpoints).toEqual(["one\ntwo\n", "one\ntwo\nthree\nfour\n"]); + } finally { + vi.useRealTimers(); + } + }); + + it("coalesces updates and persists truncated full output", async () => { + const context = createContext(); + const updates: Array<{ + content: Array<{ type: "text"; text: string } | { type: "image"; data: string; mimeType: string }>; + details?: BashToolDetails; + }> = []; + const result = await createBashTool().execute( + "bash-5", + { command: "i=1; while [ $i -le 3000 ]; do echo line-$i; i=$((i + 1)); done" }, + (update) => updates.push(update), + context, + invocation, + BACKGROUND_CONTEXT, + ); + + expect(updates.length).toBeLessThan(25); + expect(result.details?.truncation).toMatchObject({ + truncated: true, + truncatedBy: "lines", + totalLines: 3000, + outputLines: 2000, + }); + expect(textOutput(result)).toContain("line-3000"); + expect(result.details?.fullOutputPath).toBeDefined(); + const finalUpdate = updates.at(-1); + expect(finalUpdate ? textOutput(finalUpdate) : "").toContain("line-3000"); + expect(finalUpdate?.details).toMatchObject({ + truncation: { totalLines: 3000, totalBytes: expect.any(Number) }, + fullOutputPath: result.details?.fullOutputPath, + }); + const fullOutput = getOrThrow( + await context.env.readTextFile(result.details!.fullOutputPath!, BACKGROUND_CONTEXT), + ); + expect(fullOutput).toContain("line-1\nline-2"); + expect(fullOutput).toContain("line-2999\nline-3000"); + }); + }); +}); diff --git a/packages/agent/test/harness/truncate.test.ts b/packages/agent/test/harness/truncate.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..42da9d1fffebe4d7d89fe8bfaa14c34598c0264a --- /dev/null +++ b/packages/agent/test/harness/truncate.test.ts @@ -0,0 +1,178 @@ +import { describe, expect, it } from "vitest"; +import { truncateHead, truncateTail } from "../../src/harness/utils/truncate.ts"; + +const encoder = new TextEncoder(); + +function byteLength(content: string): number { + return encoder.encode(content).length; +} + +function bufferTail(content: string, maxBytes: number): string { + const bytes = Buffer.from(content, "utf8"); + if (bytes.length <= maxBytes) return content; + let start = bytes.length - maxBytes; + while (start < bytes.length && (bytes[start] & 0xc0) === 0x80) start++; + return bytes.subarray(start).toString("utf8"); +} + +function assertMatchesBufferTail(input: string, maxByteValues?: readonly number[]): void { + const totalBytes = Buffer.byteLength(input, "utf8"); + const values = maxByteValues ?? Array.from({ length: totalBytes + 5 }, (_, maxBytes) => maxBytes); + for (const maxBytes of values) { + const result = truncateTail(input, { maxBytes, maxLines: 10 }); + const expected = bufferTail(input, maxBytes); + if (result.content !== expected) { + throw new Error( + `tail mismatch input=${JSON.stringify(input)} maxBytes=${maxBytes} expected=${JSON.stringify(expected)} actual=${JSON.stringify(result.content)}`, + ); + } + const outputBytes = Buffer.byteLength(result.content, "utf8"); + if (outputBytes > maxBytes) { + throw new Error( + `tail output exceeded byte limit input=${JSON.stringify(input)} maxBytes=${maxBytes} outputBytes=${outputBytes}`, + ); + } + } +} + +function sampledByteLimits(input: string): number[] { + const totalBytes = Buffer.byteLength(input, "utf8"); + const candidates = [ + 0, + 1, + 2, + 3, + 4, + 5, + 8, + Math.floor(totalBytes / 2) - 1, + Math.floor(totalBytes / 2), + Math.floor(totalBytes / 2) + 1, + totalBytes - 8, + totalBytes - 5, + totalBytes - 4, + totalBytes - 3, + totalBytes - 2, + totalBytes - 1, + totalBytes, + totalBytes + 1, + totalBytes + 4, + ]; + return [...new Set(candidates.filter((value) => value >= 0))].sort((a, b) => a - b); +} + +describe("truncate utilities", () => { + it("counts UTF-8 bytes without Node Buffer", () => { + const content = "aé🙂\nb"; + const result = truncateHead(content, { maxBytes: 100, maxLines: 10 }); + + expect(result.truncated).toBe(false); + expect(result.totalBytes).toBe(byteLength(content)); + expect(result.outputBytes).toBe(byteLength(content)); + expect(result.totalBytes).toBe(9); + }); + + it("does not count a trailing newline as an extra line", () => { + const content = `${Array.from({ length: 3 }, () => "line").join("\n")}\n`; + const head = truncateHead(content, { maxBytes: 100, maxLines: 3 }); + const tail = truncateTail(content, { maxBytes: 100, maxLines: 3 }); + + expect(head).toMatchObject({ truncated: false, totalLines: 3, outputLines: 3 }); + expect(tail).toMatchObject({ truncated: false, totalLines: 3, outputLines: 3 }); + }); + + it("truncates head on UTF-8 byte limits without partial lines", () => { + const content = "éé\nabc"; + const result = truncateHead(content, { maxBytes: 4, maxLines: 10 }); + + expect(result.content).toBe("éé"); + expect(result.truncated).toBe(true); + expect(result.truncatedBy).toBe("bytes"); + expect(result.outputBytes).toBe(4); + expect(result.firstLineExceedsLimit).toBe(false); + }); + + it("reports head truncation when the first line exceeds the byte limit", () => { + const result = truncateHead("éé\nabc", { maxBytes: 3, maxLines: 10 }); + + expect(result.content).toBe(""); + expect(result.truncated).toBe(true); + expect(result.truncatedBy).toBe("bytes"); + expect(result.firstLineExceedsLimit).toBe(true); + }); + + it("truncates tail on UTF-8 boundaries when only a partial last line fits", () => { + const result = truncateTail("aé🙂b", { maxBytes: 5, maxLines: 10 }); + + expect(result.content).toBe("🙂b"); + expect(result.truncated).toBe(true); + expect(result.truncatedBy).toBe("bytes"); + expect(result.lastLinePartial).toBe(true); + expect(result.outputBytes).toBe(5); + }); + + it("truncates an oversized single line with a trailing newline", () => { + const input = `${"X".repeat(300_000)}\n`; + const result = truncateTail(input, { maxBytes: 1024, maxLines: 100 }); + + expect(result.content).toBe("X".repeat(1024)); + expect(result.outputBytes).toBe(1024); + expect(result.outputLines).toBe(1); + expect(result.lastLinePartial).toBe(true); + expect(result.truncatedBy).toBe("bytes"); + }); + + it("drops an oversized trailing character when it cannot fit in tail byte limit", () => { + const result = truncateTail("abc🙂", { maxBytes: 3, maxLines: 10 }); + + expect(result.content).toBe(""); + expect(result.truncated).toBe(true); + expect(result.truncatedBy).toBe("bytes"); + expect(result.lastLinePartial).toBe(true); + expect(result.outputBytes).toBe(0); + }); + + it("matches Buffer tail truncation semantics for surrogate edge cases", () => { + const inputs = ["a\ud83d", "\ude42b", "a\ude42b", "\ud83d\ud83d\ude42", "\ud83d\ude42\ude42", "👩‍💻"]; + for (const input of inputs) assertMatchesBufferTail(input); + }); + + it("matches Buffer tail truncation semantics across deterministic fuzz cases", () => { + const alphabet = [ + "a", + "\u007f", + "\u0080", + "é", + "\u07ff", + "\u0800", + "中", + "\ud7ff", + "\ud800", + "\ud83d", + "\udc00", + "\ude42", + "🙂", + "\ue000", + "\uffff", + ]; + + function checkExhaustive(prefix: string, depth: number): void { + assertMatchesBufferTail(prefix, sampledByteLimits(prefix)); + if (depth === 0) return; + for (const character of alphabet) checkExhaustive(prefix + character, depth - 1); + } + checkExhaustive("", 3); + + let seed = 0x12345678; + function random(): number { + seed = (seed * 1664525 + 1013904223) >>> 0; + return seed / 0x100000000; + } + for (let i = 0; i < 1_000; i++) { + let input = ""; + const length = Math.floor(random() * 80); + for (let j = 0; j < length; j++) input += alphabet[Math.floor(random() * alphabet.length)]; + assertMatchesBufferTail(input, sampledByteLimits(input)); + } + }); +}); diff --git a/packages/agent/test/harness/types.test.ts b/packages/agent/test/harness/types.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2999085e4136f8a9da7062b74d8f71d6aa4c4842 --- /dev/null +++ b/packages/agent/test/harness/types.test.ts @@ -0,0 +1,523 @@ +import type { AssistantMessage, AssistantMessageFrame, DeferredHandle, Usage } from "@earendil-works/pi-ai"; +import { expectTypeOf, it } from "vitest"; +import * as storedValues from "../../src/harness/session/values.ts"; +import type { + AgentHarness, + AgentHarnessOptions, + AgentHarnessStreamOptions, + AgentHarnessTool, + AgentHarnessToolInvocation, + AgentLane, + AgentMessage, + AgentTool, + Branch, + BranchScan, + CancelQueuedResult, + CheckpointData, + Context, + Control, + CustomEntry, + DriveOptions, + DriveOutcome, + DriveResult, + Entry, + EntryProjector, + EntryWrite, + GenerationContext, + HarnessEvent, + HookHandler, + HookMap, + HookName, + IdGenerator, + InboxItem, + LaneConfiguration, + LaneExecutionInfo, + LaneSnapshot, + LaneSnapshotTool, + NewEntry, + OperationAdmissionResult, + OperationAt, + OperationMeta, + OperationRequest, + OperationResultRecord, + OperationScope, + OperationState, + RunResult, + SearchQuery, + Session, + SessionCreateOptions, + SessionMetadata, + SessionMutation, + SessionMutator, + SessionReader, + SessionRepo, + SessionSearchHit, + SessionSearchService, + SessionSnapshot, + SessionStats, + SettledAssistantMessage, + Storage, + StorageBranchScan, + SummaryContext, + SuspendedRun, + TerminalStatus, + ToolCall, + UsageRow, + UsageWrite, + ValueSetWrite, + Write, +} from "../../src/index.ts"; +import { insertEntry, insertUsage } from "../../src/index.ts"; + +const configuration = { + model: { provider: "provider", modelId: "model" }, + thinkingLevel: "off", + activeToolNames: ["read"], +} satisfies LaneConfiguration; + +const retryPolicy = { maxAttempts: 3, baseDelayMs: 100, maxAgentDelayMs: 30_000 } as const; +const generationContext = { + stepId: "step", + triggerEntryId: "trigger", + configuration, + streamOptions: { deferred: { window: "1h" } }, + retryPolicy, + overflowRecoveryUsed: false, +} satisfies GenerationContext; +const summaryContext = { + resultEntryId: "summary", + configuration, + streamOptions: {}, + retryPolicy, +} satisfies SummaryContext; +const checkpoint = { + continuation: { kind: "need_assistant", overflowRecoveryUsed: false }, + triggerEntryId: "trigger", +} satisfies CheckpointData; + +const runningControl = { status: "running" } satisfies Control; +const toolCalls = [ + { status: "planned", sourceIndex: 0, resultEntryId: "result-0" }, + { status: "effect_pending", sourceIndex: 1, resultEntryId: "result-1", replay: "safe" }, + { status: "outcome_ready", sourceIndex: 2, resultEntryId: "result-2", terminate: true }, + { status: "completed", sourceIndex: 3, resultEntryId: "result-3", terminate: false }, +] satisfies ToolCall[]; + +const runScope = { + control: runningControl, + settings: { + compaction: { enabled: true, reserveTokens: 1000, keepRecentTokens: 2000 }, + steeringMode: "all", + followUpMode: "one-at-a-time", + toolExecution: "parallel", + }, + latestAssistantEntryId: null, +} satisfies OperationScope; + +const runState = { ...runScope, at: "starting" } satisfies OperationState; +// One value fixture per flat leaf; `satisfies OperationState[]` keeps every discriminant checked. +const operationStates = [ + runState, + { ...runScope, at: "checkpoint", ...checkpoint }, + { ...runScope, at: "assistant.ready", generationContext, nextAttempt: 1 }, + { + ...runScope, + at: "assistant.effect_pending", + generationContext, + attempt: 1, + responseEntryId: "response", + usageId: "usage", + intendedOutputLimit: 4096, + contextWindow: 128000, + }, + { + ...runScope, + at: "assistant.retry_wait", + generationContext, + nextAttempt: 2, + notBefore: 10, + errorMessage: "retry", + }, + { + ...runScope, + at: "tools", + batch: { assistantEntryId: "assistant", configuration, turnId: "turn", calls: toolCalls }, + }, + { + ...runScope, + at: "deferred.suspended", + stepId: "step", + sourceEntryId: "source", + poll: 0, + configuration, + streamOptions: {}, + }, + { + ...runScope, + at: "deferred.effect_pending", + stepId: "step", + sourceEntryId: "source", + poll: 1, + responseEntryId: "response", + usageId: "usage", + configuration, + streamOptions: {}, + }, + { + ...runScope, + at: "summary.deciding", + task: { taskId: "task", reason: "threshold", boundary: { kind: "resume_checkpoint", resumeAfter: checkpoint } }, + }, + { + ...runScope, + at: "summary.ready", + task: { taskId: "task", reason: "manual", customInstructions: "compact", boundary: { kind: "finish" } }, + summaryContext, + nextAttempt: 1, + }, + { + ...runScope, + at: "summary.effect_pending", + task: { + taskId: "task", + boundary: { kind: "commit_navigation", targetId: "target", label: "target" }, + }, + summaryContext, + attempt: 1, + request: { index: 0, usageId: "usage" }, + usageIds: [], + }, + { + ...runScope, + at: "summary.retry_wait", + task: { taskId: "task", reason: "overflow", boundary: { kind: "resume_checkpoint", resumeAfter: checkpoint } }, + summaryContext, + nextAttempt: 2, + notBefore: 10, + errorMessage: "retry", + }, + { ...runScope, at: "navigation.ready_to_commit", targetId: null }, +] satisfies OperationState[]; +const operations = [ + { + operationId: "run", + lane: "main", + sourceTipId: null, + startedAt: 1, + intent: { kind: "run", promptEntryIds: ["prompt"] }, + }, + { + operationId: "compaction", + lane: "main", + sourceTipId: "source", + startedAt: 2, + intent: { kind: "compaction", customInstructions: "compact" }, + }, + { + operationId: "navigation", + lane: "main", + sourceTipId: "source", + startedAt: 3, + intent: { kind: "navigation", targetId: "target", summarize: true, label: "target" }, + }, +] satisfies OperationMeta[]; + +const operationResult = { + operationId: "run", + kind: "run", + status: "completed", + fromTipId: null, + tipId: "leaf", + startedAt: 1, + endedAt: 2, +} satisfies OperationResultRecord; +const valueWrites: ValueSetWrite[] = [ + storedValues.setValue(storedValues.branchTip("main"), "leaf"), + storedValues.setValue(storedValues.laneConfig("main"), configuration), + storedValues.setValue(storedValues.laneState("main"), { + currentOperationId: "run", + lastOperationId: null, + inbox: [], + }), + storedValues.setValue(storedValues.operationResult("run"), operationResult), + storedValues.setValue(storedValues.operationMeta("run"), operations[0]), + storedValues.setValue(storedValues.operationState("run"), runState), + storedValues.setValue(storedValues.operationToolArgs("run", "step", 0), { path: "file" }), + storedValues.setValue(storedValues.operationPreparation("run", "task"), { + kind: "compaction", + messagesToSummarize: [], + turnPrefixMessages: [], + retainedTail: [], + isSplitTurn: false, + tokensBefore: 100, + fileOps: { read: [], written: [], edited: [] }, + settings: { enabled: true, reserveTokens: 1000, keepRecentTokens: 2000 }, + }), + storedValues.setValue(storedValues.pendingEntry("pending"), { + type: "custom", + customType: "note", + payload: { text: "pending" }, + }), + storedValues.setValue(storedValues.sessionName, "session"), + storedValues.setValue(storedValues.entryLabel("entry"), "label"), + storedValues.setValue(storedValues.value("test.value", "state"), null), +]; + +const usage = { + input: 1, + output: 2, + cacheRead: 3, + cacheWrite: 4, + totalTokens: 10, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, +} satisfies Usage; +const usageRow = { + id: "usage", + seq: 2, + usage, + entryId: "entry", + adjustment: false, + details: { attempt: 1 }, +} satisfies UsageRow; +const entryWrite = insertEntry({ + id: "entry", + parentId: null, + type: "message", + message: { role: "user", content: "hello", timestamp: 1 }, +}); +const usageWrite = insertUsage({ + id: usageRow.id, + usage, + adjustment: false, + entryId: "entry", +}); +const writes = [ + entryWrite, + usageWrite, + valueWrites[0]!, + storedValues.deleteValue(storedValues.entryLabel("entry")), +] satisfies Write[]; +const transaction = writes satisfies Write[]; + +it("covers the complete durable storage and Part 3 discriminants", () => { + expectTypeOf(entryWrite).toEqualTypeOf(); + expectTypeOf(usageWrite).toEqualTypeOf(); + expectTypeOf(storedValues.laneConfig("main")).toEqualTypeOf>(); + expectTypeOf(storedValues.pendingAssistantFrames("operation", "response")).toEqualTypeOf< + storedValues.ValueList + >(); + expectTypeOf().toEqualTypeOf<"run" | "compaction" | "navigation">(); + expectTypeOf().toEqualTypeOf<"running" | "cancel_requested">(); + expectTypeOf().toEqualTypeOf<"planned" | "effect_pending" | "outcome_ready" | "completed">(); + expectTypeOf().toEqualTypeOf< + | "starting" + | "checkpoint" + | "assistant.ready" + | "assistant.effect_pending" + | "assistant.retry_wait" + | "tools" + | "deferred.suspended" + | "deferred.effect_pending" + | "summary.deciding" + | "summary.ready" + | "summary.effect_pending" + | "summary.retry_wait" + | "summary.deciding" + | "summary.ready" + | "summary.effect_pending" + | "summary.retry_wait" + | "navigation.ready_to_commit" + | "summary.deciding" + | "summary.ready" + | "summary.effect_pending" + | "summary.retry_wait" + >(); + expectTypeOf().toEqualTypeOf<"steer" | "followUp" | "nextRun" | "write">(); + expectTypeOf().toEqualTypeOf<"completed" | "declined" | "aborted" | "failed">(); + expectTypeOf().toEqualTypeOf<"message" | "compaction" | "branch_summary" | "custom">(); + void transaction; + void operationStates; + + const compileTimeFailures = () => { + // @ts-expect-error lane.config requires a complete LaneConfiguration + const invalidValue: ValueSetWrite = storedValues.setValue(storedValues.laneConfig("main"), "model"); + // @ts-expect-error response entries require settled assistant content at runtime, not a pending settlement type + const invalidSettled: SettledAssistantMessage = { stopReason: "pending" } as AssistantMessage; + void invalidValue; + void invalidSettled; + }; + expectTypeOf(compileTimeFailures).toBeFunction(); +}); + +it("covers storage, session, repository, search, and identity signatures", () => { + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf<(timestampMs?: number) => string>(); + expectTypeOf[0]["start"]>().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf< + ( + transactionToCommit: Write[], + context: Context, + ) => Promise<{ firstSeq: number; seqs: number[]; timestamp: number; stats: SessionStats }> + >(); + expectTypeOf().toEqualTypeOf<(context: Context) => Promise>(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf<(context: Context) => Promise>(); + expectTypeOf().toEqualTypeOf< + (mutation: (mutator: SessionMutator, context: Context) => T | Promise, context: Context) => Promise + >(); + expectTypeOf().toEqualTypeOf< + ( + transactionToCommit: Write[], + context: Context, + ) => Promise<{ firstSeq: number; seqs: number[]; timestamp: number; stats: SessionStats }> + >(); + expectTypeOf().toEqualTypeOf< + (query: StorageBranchScan, context: Context) => Promise + >(); + expectTypeOf().toEqualTypeOf< + (name: string, at: string | null, context: Context) => Promise + >(); + expectTypeOf().toEqualTypeOf< + (options: SessionCreateOptions, context: Context) => Promise + >(); + expectTypeOf().toEqualTypeOf< + (query: SearchQuery) => Promise + >(); + expectTypeOf().toEqualTypeOf<(sessionId: string) => void>(); +}); + +it("covers Part 5 results, events, hooks, snapshots, tools, and stream options", () => { + type RunErrorTag = Extract["error"]["_tag"]; + type CancelKind = Extract["value"]["kind"]; + expectTypeOf().toEqualTypeOf< + "LaneBusy" | "InvalidMessage" | "UnknownSkill" | "UnknownTemplate" | "Closed" + >(); + expectTypeOf().toEqualTypeOf<"cancelled" | "already_consumed" | "not_found">(); + expectTypeOf().toEqualTypeOf< + | "run_start" + | "run_resume" + | "run_suspend" + | "operation_abort" + | "run_end" + | "fault" + | "handler_error" + | "turn_start" + | "turn_end" + | "retry_scheduled" + | "retry_start" + | "retry_end" + | "message_start" + | "message_update" + | "message_end" + | "tool_start" + | "tool_update" + | "tool_end" + | "entry_added" + | "queue_update" + | "value_update" + | "config_update" + | "compaction_start" + | "compaction_end" + | "navigation_start" + | "navigation_end" + | "lane_created" + | "usage" + >(); + expectTypeOf().toEqualTypeOf< + | "before_run" + | "before_drive" + | "before_run_end" + | "transform_context" + | "before_request" + | "before_payload" + | "after_response" + | "before_tool" + | "after_tool" + | "before_compaction" + | "before_navigation" + >(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf>().returns.toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf<{ + messages: AgentMessage[]; + systemPrompt: string; + }>(); + expectTypeOf().not.toEqualTypeOf(); + expectTypeOf().toEqualTypeOf<"running" | "settled">(); + expectTypeOf().returns.toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf<{ + operationId: string; + status: "suspended"; + deferred: DeferredHandle; + }>(); + expectTypeOf().returns.toEqualTypeOf>(); + expectTypeOf().returns.toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf<"operationId" | "waitForRetry" | "pollDeferred">(); + expectTypeOf().toEqualTypeOf<"settled" | "waiting">(); + expectTypeOf().returns.toEqualTypeOf>(); + expectTypeOf().returns.toEqualTypeOf>(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf< + Extract< + keyof AgentLane, + | "session" + | "models" + | "hooks" + | "activeDrive" + | "command" + | "settleOperation" + | "continueOperation" + | "readConfig" + | "mismatch" + > + >().toEqualTypeOf(); + expectTypeOf< + Extract< + keyof AgentHarness, + | "session" + | "models" + | "activeDrive" + | "command" + | "settleOperation" + | "continueOperation" + | "readConfig" + | "mismatch" + > + >().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf< + "prompt" | "skill" | "prompt_template" | "compaction" | "navigation" + >(); + expectTypeOf["execute"]>[4]>().toEqualTypeOf(); + expectTypeOf["execute"]>[5]>().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf<"never" | "safe" | undefined>(); + expectTypeOf().toEqualTypeOf< + boolean | { window?: "15m" | "1h" | "24h" } | undefined + >(); + expectTypeOf().toEqualTypeOf< + (entry: CustomEntry, context: Context) => AgentMessage[] | undefined | Promise + >(); + expectTypeOf>().toEqualTypeOf>(); + + const compileTimeFailures = () => { + // @ts-expect-error callers cannot supply the harness-owned abort signal + const invalidOptions: AgentHarnessStreamOptions = { signal: new AbortController().signal }; + const invalidDriveOptions: DriveOptions = { + operationId: "run", + // @ts-expect-error drive has no wall-clock deadline + deadline: Date.now(), + }; + const invalidValueEvent: Extract = { + type: "value_update", + value: "session_name", + name: "session", + // @ts-expect-error value events are harness-global and cannot carry a lane + lane: "main", + }; + void invalidOptions; + void invalidDriveOptions; + void invalidValueEvent; + }; + expectTypeOf(compileTimeFailures).toBeFunction(); +}); diff --git a/packages/agent/test/harness/values.test.ts b/packages/agent/test/harness/values.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6f438194213d6322a55dd8a7b7e87a20d3ef1840 --- /dev/null +++ b/packages/agent/test/harness/values.test.ts @@ -0,0 +1,183 @@ +import type { AssistantMessageFrame } from "@earendil-works/pi-ai"; +import { describe, expect, expectTypeOf, it } from "vitest"; +import { BACKGROUND_CONTEXT } from "../../src/harness/context.ts"; +import { MemoryStorage } from "../../src/harness/session/memory.ts"; +import type { + DurableStructuralPreparation, + JsonValue, + LaneConfiguration, + LaneState, + OperationMeta, + OperationResultRecord, + OperationState, + PendingEntry, + SessionReader, +} from "../../src/harness/session/types.ts"; +import { + appendList, + branchTip, + branchTipInventoryPrefix, + deleteList, + deleteValue, + entryLabel, + type ListElement, + laneConfig, + laneState, + list, + operationMeta, + operationPreparation, + operationPreparationPrefix, + operationResult, + operationState, + operationToolArgs, + operationToolArgsPrefix, + operationToolMemo, + operationToolMemoPrefix, + pendingAssistantFrames, + pendingEntry, + pendingToolOutput, + pendingToolOutputPrefix, + type StoredValue, + sessionName, + setValue, + type Value, + type ValueList, + value, +} from "../../src/harness/session/values.ts"; + +describe("bound value addresses", () => { + it("binds immutable scalar and list addresses with validated components", () => { + expect(value("app.state")).toEqual({ kind: "value", namespace: "app.state", key: "" }); + expect(list("app.events", "workspace")).toEqual({ + kind: "list", + namespace: "app.events", + key: "workspace", + }); + expect(Object.isFrozen(value("app.state"))).toBe(true); + expect(() => value("")).toThrow("must not be empty"); + expect(() => value("app\0state")).toThrow("must not contain"); + expect(() => list("app.events", "bad\0key")).toThrow("must not contain"); + expect(value("pi.application")).toEqual({ kind: "value", namespace: "pi.application", key: "" }); + }); + + it("preserves invariant address and helper types", () => { + const scalar = value<{ count: number }>("app.state"); + const events = list<{ name: string }>("app.events"); + expectTypeOf(scalar).toEqualTypeOf>(); + expectTypeOf(events).toEqualTypeOf>(); + expectTypeOf(setValue(scalar, { count: 1 }).value).toEqualTypeOf(); + expectTypeOf(appendList(events, { name: "created" }).value).toEqualTypeOf(); + + const compileTimeFailures = () => { + // @ts-expect-error Value is invariant in its stored type + const widenedScalar: Value = scalar; + // @ts-expect-error ValueList is invariant in its element type + const widenedList: ValueList = events; + // @ts-expect-error the bound scalar address controls the write type + setValue(scalar, { count: "wrong" }); + // @ts-expect-error the bound list address controls the element type + appendList(events, { name: 1 }); + // @ts-expect-error scalar helpers reject list addresses + deleteValue(events); + // @ts-expect-error list helpers reject scalar addresses + deleteList(scalar); + void widenedScalar; + void widenedList; + }; + expectTypeOf(compileTimeFailures).toBeFunction(); + }); + + it("infers list element types through Storage and SessionReader", async () => { + const storage = new MemoryStorage({ now: () => 1 }); + const events = list<{ name: string }>("app.events"); + const reader: SessionReader = storage; + const storageElements = await storage.readList(events, undefined, BACKGROUND_CONTEXT); + const readerElements = await reader.readList(events, undefined, BACKGROUND_CONTEXT); + expectTypeOf(storageElements).toEqualTypeOf[]>(); + expectTypeOf(readerElements).toEqualTypeOf[]>(); + await storage.close(BACKGROUND_CONTEXT); + }); + + it("uses separately constructed equal addresses for one durable location", async () => { + const storage = new MemoryStorage({ now: () => 1 }); + const first = value<{ ready: boolean }>("app.state", "workspace"); + const second = value<{ ready: boolean }>("app.state", "workspace"); + await storage.commit([setValue(first, { ready: true })], BACKGROUND_CONTEXT); + const stored = await storage.getValue(second, BACKGROUND_CONTEXT); + expect(stored).toEqual({ address: first, value: { ready: true }, seq: 1 }); + expectTypeOf(stored).toEqualTypeOf | undefined>(); + await storage.close(BACKGROUND_CONTEXT); + }); +}); + +describe("built-in durable addresses", () => { + it("uses the exact reserved namespaces, keys, kinds, and value types", () => { + const config = laneConfig("review"); + const meta = operationMeta("operation"); + const state = operationState("operation"); + const frames = pendingAssistantFrames("operation", "response"); + expectTypeOf(config).toEqualTypeOf>(); + expectTypeOf(branchTip("review")).toEqualTypeOf>(); + expectTypeOf(laneState("review")).toEqualTypeOf>(); + expectTypeOf(operationResult("operation")).toEqualTypeOf>(); + expectTypeOf(meta).toEqualTypeOf>(); + expectTypeOf(state).toEqualTypeOf>(); + expectTypeOf(operationToolArgs("operation", "step", 2)).toEqualTypeOf>>(); + expectTypeOf(operationToolMemo("operation", "invocation", "name")).toEqualTypeOf>(); + expectTypeOf(operationPreparation("operation", "task")).toEqualTypeOf>(); + expectTypeOf(pendingEntry("entry")).toEqualTypeOf>(); + expectTypeOf(frames).toEqualTypeOf>(); + + expect([ + branchTip("review"), + laneConfig("review"), + laneState("review"), + operationResult("operation"), + meta, + state, + operationToolArgs("operation", "step", 2), + operationToolMemo("operation", "invocation", "name"), + operationPreparation("operation", "task"), + pendingEntry("entry"), + pendingToolOutput("operation", "invocation"), + frames, + sessionName, + entryLabel("entry"), + ]).toEqual([ + { kind: "value", namespace: "pi.branch.tip", key: "review" }, + { kind: "value", namespace: "pi.lane.config", key: "review" }, + { kind: "value", namespace: "pi.lane.state", key: "review" }, + { kind: "value", namespace: "pi.result", key: "operation" }, + { kind: "value", namespace: "pi.op.meta", key: "operation" }, + { kind: "value", namespace: "pi.op.state", key: "operation" }, + { kind: "value", namespace: "pi.op.tool_args", key: "operation:step:2" }, + { kind: "value", namespace: "pi.op.tool_memo", key: "operation:invocation:name" }, + { kind: "value", namespace: "pi.op.preparation", key: "operation:task" }, + { kind: "value", namespace: "pi.pending.entry", key: "entry" }, + { kind: "value", namespace: "pi.pending.tool_output", key: "operation:invocation" }, + { kind: "list", namespace: "pi.pending.assistant_frame", key: "operation:response" }, + { kind: "value", namespace: "pi.session.name", key: "" }, + { kind: "value", namespace: "pi.entry.label", key: "entry" }, + ]); + }); + + it("exports exactly the five documented scan-prefix constructors", () => { + const prefixes = [ + branchTipInventoryPrefix(), + operationToolArgsPrefix("operation"), + operationToolMemoPrefix("operation", "invocation"), + operationPreparationPrefix("operation"), + pendingToolOutputPrefix("operation"), + ]; + expect(prefixes).toHaveLength(5); + expect(prefixes).toEqual([ + { kind: "value", namespace: "pi.branch.tip", key: "" }, + { kind: "value", namespace: "pi.op.tool_args", key: "operation:" }, + { kind: "value", namespace: "pi.op.tool_memo", key: "operation:invocation:" }, + { kind: "value", namespace: "pi.op.preparation", key: "operation:" }, + { kind: "value", namespace: "pi.pending.tool_output", key: "operation:" }, + ]); + expect(operationToolArgsPrefix("operation", "step").key).toBe("operation:step:"); + expect(operationToolMemoPrefix("operation").key).toBe("operation:"); + }); +}); diff --git a/packages/agent/test/utils/calculate.ts b/packages/agent/test/utils/calculate.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a4fefc58c3c027f78f9069b7979d853dd45b427 --- /dev/null +++ b/packages/agent/test/utils/calculate.ts @@ -0,0 +1,40 @@ +import type { Usage } from "@earendil-works/pi-ai"; +import { type Static, Type } from "typebox"; +import type { AgentTool, AgentToolResult } from "../../src/types.ts"; + +export interface CalculateResult extends AgentToolResult { + content: Array<{ type: "text"; text: string }>; + details: undefined; +} + +export function calculate(expression: string): CalculateResult { + try { + const result = new Function(`return ${expression}`)(); + return { content: [{ type: "text", text: `${expression} = ${result}` }], details: undefined }; + } catch (e: any) { + throw new Error(e.message || String(e)); + } +} + +const calculateSchema = Type.Object({ + expression: Type.String({ description: "The mathematical expression to evaluate" }), +}); + +type CalculateParams = Static; + +export const calculateTool: AgentTool = { + label: "Calculator", + name: "calculate", + description: "Evaluate mathematical expressions", + parameters: calculateSchema, + execute: async (_toolCallId: string, args: CalculateParams) => { + return calculate(args.expression); + }, +}; + +export function createCalculateToolWithUsage(usage: Usage): AgentTool { + return { + ...calculateTool, + execute: async (_toolCallId: string, args: CalculateParams) => ({ ...calculate(args.expression), usage }), + }; +} diff --git a/packages/agent/test/utils/get-current-time.ts b/packages/agent/test/utils/get-current-time.ts new file mode 100644 index 0000000000000000000000000000000000000000..a83a82af3183e83df38db0c221b39e7143ef891e --- /dev/null +++ b/packages/agent/test/utils/get-current-time.ts @@ -0,0 +1,46 @@ +import { type Static, Type } from "typebox"; +import type { AgentTool, AgentToolResult } from "../../src/types.ts"; + +export interface GetCurrentTimeResult extends AgentToolResult<{ utcTimestamp: number }> {} + +export async function getCurrentTime(timezone?: string): Promise { + const date = new Date(); + if (timezone) { + try { + const timeStr = date.toLocaleString("en-US", { + timeZone: timezone, + dateStyle: "full", + timeStyle: "long", + }); + return { + content: [{ type: "text", text: timeStr }], + details: { utcTimestamp: date.getTime() }, + }; + } catch (_e) { + throw new Error(`Invalid timezone: ${timezone}. Current UTC time: ${date.toISOString()}`); + } + } + const timeStr = date.toLocaleString("en-US", { dateStyle: "full", timeStyle: "long" }); + return { + content: [{ type: "text", text: timeStr }], + details: { utcTimestamp: date.getTime() }, + }; +} + +const getCurrentTimeSchema = Type.Object({ + timezone: Type.Optional( + Type.String({ description: "Optional timezone (e.g., 'America/New_York', 'Europe/London')" }), + ), +}); + +type GetCurrentTimeParams = Static; + +export const getCurrentTimeTool: AgentTool = { + label: "Current Time", + name: "get_current_time", + description: "Get the current date and time", + parameters: getCurrentTimeSchema, + execute: async (_toolCallId: string, args: GetCurrentTimeParams) => { + return getCurrentTime(args.timezone); + }, +}; diff --git a/packages/agent/test/utils/wait-for-tick.ts b/packages/agent/test/utils/wait-for-tick.ts new file mode 100644 index 0000000000000000000000000000000000000000..72ad2876ab3a369f37bf19a04624577a46c631d7 --- /dev/null +++ b/packages/agent/test/utils/wait-for-tick.ts @@ -0,0 +1,3 @@ +export function waitForTick(): Promise { + return new Promise((resolve) => setTimeout(resolve, 0)); +} diff --git a/packages/ai/src/api/openai-responses.ts b/packages/ai/src/api/openai-responses.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4d16d2f5de5b00f25d4748b32b96f92ce870a95 --- /dev/null +++ b/packages/ai/src/api/openai-responses.ts @@ -0,0 +1,389 @@ +import OpenAI from "openai"; +import type { ResponseCreateParamsStreaming } from "openai/resources/responses/responses.js"; +import { clampThinkingLevel } from "../models.ts"; +import type { + Api, + AssistantMessage, + CacheRetention, + Context, + Model, + OpenAIResponsesCompat, + ProviderEnv, + ProviderHeaders, + SimpleStreamOptions, + StreamFunction, + StreamOptions, + Usage, +} from "../types.ts"; +import { splitDeferredTools } from "../utils/deferred-tools.ts"; +import { formatProviderError, normalizeProviderError } from "../utils/error-body.ts"; +import { AssistantMessageEventStream } from "../utils/event-stream.ts"; +import { headersToRecord } from "../utils/headers.ts"; +import { getPiUserAgent } from "../utils/pi-user-agent.ts"; +import { getProviderEnvValue } from "../utils/provider-env.ts"; +import { retryProviderRequest } from "../utils/provider-retry.ts"; +import { createGrammarToolInputProperties } from "./constrained-sampling.ts"; +import { buildCopilotDynamicHeaders, hasCopilotVisionInput } from "./github-copilot-headers.ts"; +import { clampOpenAIPromptCacheKey } from "./openai-prompt-cache.ts"; +import { convertResponsesMessages, convertResponsesTools, processResponsesStream } from "./openai-responses-shared.ts"; +import { buildBaseOptions } from "./simple-options.ts"; + +const OPENAI_TOOL_CALL_PROVIDERS = new Set(["openai", "openai-codex", "opencode"]); +// OpenAI Responses rejects max_output_tokens below 16: https://github.com/earendil-works/pi/issues/6265 +const OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16; + +function hasHeader(headers: ProviderHeaders | undefined, name: string): boolean { + if (!headers) return false; + const expected = name.toLowerCase(); + for (const [key, value] of Object.entries(headers)) { + if (key.toLowerCase() === expected && value !== null && value.trim().length > 0) return true; + } + return false; +} + +function getClientApiKey(provider: string, apiKey: string | undefined, headers: ProviderHeaders | undefined): string { + if (apiKey) return apiKey; + if (hasHeader(headers, "authorization") || hasHeader(headers, "cf-aig-authorization")) return "unused"; + throw new Error(`No API key for provider: ${provider}`); +} + +function detectSessionAffinityFormat(model: Pick, "provider" | "baseUrl">) { + return model.provider === "openrouter" || model.baseUrl.includes("openrouter.ai") ? "openrouter" : "openai"; +} + +/** + * Resolve cache retention preference. + * Defaults to "short" and uses PI_CACHE_RETENTION for backward compatibility. + */ +function resolveCacheRetention(cacheRetention?: CacheRetention, env?: ProviderEnv): CacheRetention { + if (cacheRetention) { + return cacheRetention; + } + if (getProviderEnvValue("PI_CACHE_RETENTION", env) === "long") { + return "long"; + } + return "short"; +} + +function getCompat(model: Model<"openai-responses">): Required { + return { + supportsDeveloperRole: model.compat?.supportsDeveloperRole ?? true, + sessionAffinityFormat: model.compat?.sessionAffinityFormat ?? detectSessionAffinityFormat(model), + supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true, + supportsStrictMode: model.compat?.supportsStrictMode ?? false, + supportsOpenAIGrammarTools: model.compat?.supportsOpenAIGrammarTools ?? false, + supportsAdditionalTools: model.compat?.supportsAdditionalTools ?? false, + supportsToolSearch: model.compat?.supportsToolSearch ?? false, + supportsExplicitPromptCacheMode: model.compat?.supportsExplicitPromptCacheMode ?? false, + supportsMaxOutputTokens: model.compat?.supportsMaxOutputTokens ?? true, + }; +} + +function getPromptCacheRetention( + compat: Required, + cacheRetention: CacheRetention, +): "24h" | undefined { + return cacheRetention === "long" && compat.supportsLongCacheRetention && !compat.supportsExplicitPromptCacheMode + ? "24h" + : undefined; +} + +function getPromptCacheOptions( + compat: Required, + cacheRetention: CacheRetention, +): { mode?: "explicit"; ttl?: "30m" } | undefined { + if (!compat.supportsExplicitPromptCacheMode) return undefined; + if (cacheRetention === "none") return { mode: "explicit" }; + if (cacheRetention === "long" && compat.supportsLongCacheRetention) return { ttl: "30m" }; + return undefined; +} + +// OpenAI Responses-specific options +export interface OpenAIResponsesOptions extends StreamOptions { + reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh" | "max"; + reasoningSummary?: "auto" | "detailed" | "concise" | null; + serviceTier?: ResponseCreateParamsStreaming["service_tier"]; + toolChoice?: ResponseCreateParamsStreaming["tool_choice"]; +} + +/** + * Generate function for OpenAI Responses API + */ +export const stream: StreamFunction<"openai-responses", OpenAIResponsesOptions> = ( + model: Model<"openai-responses">, + context: Context, + options?: OpenAIResponsesOptions, +): AssistantMessageEventStream => { + const stream = new AssistantMessageEventStream(); + + // Start async processing + (async () => { + const output: AssistantMessage = { + role: "assistant", + content: [], + api: model.api as 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: "pending", + timestamp: Date.now(), + }; + + try { + // Create OpenAI client + const apiKey = getClientApiKey(model.provider, options?.apiKey, options?.headers); + const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env); + const cacheSessionId = cacheRetention === "none" ? undefined : options?.sessionId; + const compat = getCompat(model); + const grammarToolInputProperties = createGrammarToolInputProperties( + context.tools, + compat.supportsOpenAIGrammarTools, + ); + const client = createClient(model, context, apiKey, options?.headers, options?.fetch, cacheSessionId); + let params = buildParams(model, context, options, compat, grammarToolInputProperties); + const nextParams = await options?.onPayload?.(params, model); + if (nextParams !== undefined) { + params = nextParams as ResponseCreateParamsStreaming; + } + const requestOptions = { + ...(options?.signal ? { signal: options.signal } : {}), + ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}), + maxRetries: 0, + }; + const { data: openaiStream, response } = await retryProviderRequest( + () => client.responses.create(params, requestOptions).withResponse(), + { + maxRetries: options?.maxRetries, + maxRetryDelayMs: options?.maxRetryDelayMs, + signal: options?.signal, + }, + ); + await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model); + stream.push({ type: "start", partial: output }); + + await processResponsesStream(openaiStream, output, stream, model, { + serviceTier: options?.serviceTier, + grammarToolInputProperties, + applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model), + }); + + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + + if (output.stopReason === "pending") { + throw new Error("OpenAI Responses stream ended without a stop reason"); + } + if (output.stopReason === "aborted" || output.stopReason === "error") { + throw new Error(output.errorMessage || "An unknown error occurred"); + } + + stream.push({ type: "done", reason: output.stopReason, message: output }); + stream.end(); + } catch (error) { + for (const block of output.content) { + delete (block as { index?: number }).index; + // Streaming scratch buffers are only used during parsing; never persist them. + delete (block as { partialJson?: string }).partialJson; + delete (block as { customInput?: unknown }).customInput; + } + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = formatProviderError( + normalizeProviderError(error), + `${model.provider === "openai" ? "OpenAI" : model.provider} API error`, + ); + stream.push({ type: "error", reason: output.stopReason, error: output }); + stream.end(); + } + })(); + + return stream; +}; + +export const streamSimple: StreamFunction<"openai-responses", SimpleStreamOptions> = ( + model: Model<"openai-responses">, + context: Context, + options?: SimpleStreamOptions, +): AssistantMessageEventStream => { + getClientApiKey(model.provider, options?.apiKey, options?.headers); + + const base = { + ...buildBaseOptions(model, context, options, options?.apiKey), + toolChoice: options?.toolChoice, + } satisfies OpenAIResponsesOptions; + const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined; + const reasoningEffort = clampedReasoning === "off" ? undefined : clampedReasoning; + + return stream(model, context, { + ...base, + reasoningEffort, + } satisfies OpenAIResponsesOptions); +}; + +function createClient( + model: Model<"openai-responses">, + context: Context, + apiKey: string, + optionsHeaders?: ProviderHeaders, + fetch?: typeof globalThis.fetch, + sessionId?: string, +) { + const compat = getCompat(model); + const headers: ProviderHeaders = { "User-Agent": getPiUserAgent(), ...model.headers }; + if (model.provider === "github-copilot") { + const hasImages = hasCopilotVisionInput(context.messages); + const copilotHeaders = buildCopilotDynamicHeaders({ + messages: context.messages, + hasImages, + }); + Object.assign(headers, copilotHeaders); + } + + if (sessionId) { + if (compat.sessionAffinityFormat === "openrouter") { + headers["x-session-id"] = sessionId; + } else { + if (compat.sessionAffinityFormat === "openai") { + headers.session_id = sessionId; + } + headers["x-client-request-id"] = sessionId; + } + } + + // Merge options headers last so they can override defaults + if (optionsHeaders) { + Object.assign(headers, optionsHeaders); + } + + return new OpenAI({ + apiKey, + baseURL: model.baseUrl, + dangerouslyAllowBrowser: true, + fetch, + defaultHeaders: headers, + }); +} + +function buildParams( + model: Model<"openai-responses">, + context: Context, + options: OpenAIResponsesOptions | undefined, + compat: Required = getCompat(model), + grammarToolInputProperties: ReadonlyMap = createGrammarToolInputProperties( + context.tools, + compat.supportsOpenAIGrammarTools, + ), +) { + const deferredToolsMode = compat.supportsAdditionalTools + ? "additional-tools" + : compat.supportsToolSearch + ? "tool-search" + : undefined; + const toolPlacement = splitDeferredTools(context, deferredToolsMode !== undefined); + const messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS, { + grammarToolInputProperties, + deferredTools: toolPlacement.deferred, + deferredToolsMode, + toolOptions: { + supportsStrictMode: compat.supportsStrictMode, + supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools, + }, + }); + + const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env); + const params: ResponseCreateParamsStreaming & { + prompt_cache_options?: { mode?: "explicit"; ttl?: "30m" }; + } = { + model: model.id, + input: messages, + stream: true, + prompt_cache_key: cacheRetention === "none" ? undefined : clampOpenAIPromptCacheKey(options?.sessionId), + prompt_cache_retention: getPromptCacheRetention(compat, cacheRetention), + prompt_cache_options: getPromptCacheOptions(compat, cacheRetention), + store: false, + }; + + if (options?.maxTokens && compat.supportsMaxOutputTokens) { + params.max_output_tokens = Math.max(options.maxTokens, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS); + } + + if (options?.temperature !== undefined) { + params.temperature = options?.temperature; + } + + if (options?.serviceTier !== undefined) { + params.service_tier = options.serviceTier; + } + + if (toolPlacement.immediate.length > 0) { + params.tools = convertResponsesTools(toolPlacement.immediate, { + supportsStrictMode: compat.supportsStrictMode, + supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools, + }); + } + + if (options?.toolChoice !== undefined) { + params.tool_choice = options.toolChoice; + } + + if (model.reasoning) { + if (options?.reasoningEffort || options?.reasoningSummary) { + const effort = options?.reasoningEffort + ? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort) + : "medium"; + params.reasoning = { + effort: effort as NonNullable["effort"], + summary: options?.reasoningSummary || "auto", + }; + params.include = ["reasoning.encrypted_content"]; + } else if (model.provider !== "github-copilot" && model.thinkingLevelMap?.off !== null) { + params.reasoning = { + effort: (model.thinkingLevelMap?.off ?? "none") as NonNullable["effort"], + }; + } + if (model.provider === "xai") params.include = ["reasoning.encrypted_content"]; + } + + // Last so custom keys override the named request fields. + if (options?.samplingParams) { + Object.assign(params, options.samplingParams); + } + + return params; +} + +function getServiceTierCostMultiplier( + model: Pick, "id">, + serviceTier: ResponseCreateParamsStreaming["service_tier"] | undefined, +): number { + switch (serviceTier) { + case "flex": + return 0.5; + case "priority": + return model.id === "gpt-5.5" ? 2.5 : 2; + default: + return 1; + } +} + +function applyServiceTierPricing( + usage: Usage, + serviceTier: ResponseCreateParamsStreaming["service_tier"] | undefined, + model: Pick, "id">, +) { + const multiplier = getServiceTierCostMultiplier(model, serviceTier); + if (multiplier === 1) return; + + usage.cost.input *= multiplier; + usage.cost.output *= multiplier; + usage.cost.cacheRead *= multiplier; + usage.cost.cacheWrite *= multiplier; + usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite; +} diff --git a/packages/ai/src/api/simple-options.ts b/packages/ai/src/api/simple-options.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a30265ad259f0018b699d1a4051989c09e0447e --- /dev/null +++ b/packages/ai/src/api/simple-options.ts @@ -0,0 +1,95 @@ +import type { + Api, + Context, + Model, + SimpleStreamOptions, + StreamOptions, + ThinkingBudgets, + ThinkingLevel, +} from "../types.ts"; +import { estimateContextTokens } from "../utils/estimate.ts"; + +const CONTEXT_SAFETY_TOKENS = 4096; +const MIN_MAX_TOKENS = 1; + +export function clampMaxTokensToContext(model: Model, context: Context, maxTokens: number): number { + if (model.contextWindow <= 0) return Math.max(MIN_MAX_TOKENS, maxTokens); + const available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS; + return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available)); +} + +export function buildBaseOptions( + model: Model, + context: Context, + options?: SimpleStreamOptions, + apiKey?: string, +): StreamOptions { + const samplingParams = + model.samplingParams || options?.samplingParams + ? { ...model.samplingParams, ...options?.samplingParams } + : undefined; + return { + temperature: options?.temperature, + samplingParams, + maxTokens: clampMaxTokensToContext(model, context, options?.maxTokens ?? model.maxTokens), + signal: options?.signal, + telemetryContext: options?.telemetryContext, + apiKey: apiKey || options?.apiKey, + fetch: options?.fetch, + transport: options?.transport, + cacheRetention: options?.cacheRetention, + sessionId: options?.sessionId, + headers: options?.headers, + onPayload: options?.onPayload, + onResponse: options?.onResponse, + timeoutMs: options?.timeoutMs, + websocketConnectTimeoutMs: options?.websocketConnectTimeoutMs, + maxRetries: options?.maxRetries, + maxRetryDelayMs: options?.maxRetryDelayMs, + metadata: options?.metadata, + env: options?.env, + }; +} + +/** Tokens always left for the answer when a thinking budget shares the response ceiling. */ +export const MIN_ANSWER_TOKENS = 1024; + +export const DEFAULT_THINKING_BUDGETS: ThinkingBudgets = { + minimal: 1024, + low: 2048, + medium: 8192, + high: 16384, +}; + +export function clampReasoning(effort: ThinkingLevel | undefined): Exclude | undefined { + return effort === "xhigh" || effort === "max" ? "high" : effort; +} + +export function thinkingBudgetForLevel(reasoningLevel: ThinkingLevel, customBudgets?: ThinkingBudgets): number { + const budgets = { ...DEFAULT_THINKING_BUDGETS, ...customBudgets }; + const level = clampReasoning(reasoningLevel)!; + return budgets[level]!; +} + +/** Cap a thinking budget so at least MIN_ANSWER_TOKENS remain under a shared response ceiling. */ +export function clampThinkingBudgetToAnswerRoom(thinkingBudget: number, ceiling: number): number { + return Math.min(thinkingBudget, Math.max(0, ceiling - MIN_ANSWER_TOKENS)); +} + +export function adjustMaxTokensForThinking( + // Undefined means no explicit caller cap. Use the model cap and fit thinking inside it. + baseMaxTokens: number | undefined, + modelMaxTokens: number, + reasoningLevel: ThinkingLevel, + customBudgets?: ThinkingBudgets, +): { maxTokens: number; thinkingBudget: number } { + let thinkingBudget = thinkingBudgetForLevel(reasoningLevel, customBudgets); + const maxTokens = + baseMaxTokens === undefined ? modelMaxTokens : Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens); + + if (maxTokens <= thinkingBudget) { + thinkingBudget = clampThinkingBudgetToAnswerRoom(thinkingBudget, maxTokens); + } + + return { maxTokens, thinkingBudget }; +} diff --git a/packages/ai/src/providers/all.ts b/packages/ai/src/providers/all.ts new file mode 100644 index 0000000000000000000000000000000000000000..8785e94aed69942629bd4c4da69b55fa8db053d2 --- /dev/null +++ b/packages/ai/src/providers/all.ts @@ -0,0 +1,155 @@ +import { createImagesModels, type ImagesProvider, type MutableImagesModels } from "../images-models.ts"; +import { MODELS } from "../models.generated.ts"; +import { type CreateModelsOptions, createModels, type MutableModels, type Provider } from "../models.ts"; +import type { Api, Model } from "../types.ts"; +import { amazonBedrockProvider } from "./amazon-bedrock.ts"; +import { antLingProvider } from "./ant-ling.ts"; +import { anthropicProvider } from "./anthropic.ts"; +import { azureOpenAIResponsesProvider } from "./azure-openai-responses.ts"; +import { basetenProvider } from "./baseten.ts"; +import { cerebrasProvider } from "./cerebras.ts"; +import { cloudflareAIGatewayProvider } from "./cloudflare-ai-gateway.ts"; +import { cloudflareWorkersAIProvider } from "./cloudflare-workers-ai.ts"; +import modelDataManifest from "./data/.manifest.json" with { type: "json" }; +import { deepseekProvider } from "./deepseek.ts"; +import { fireworksProvider } from "./fireworks.ts"; +import { githubCopilotProvider } from "./github-copilot.ts"; +import { googleProvider } from "./google.ts"; +import { googleVertexProvider } from "./google-vertex.ts"; +import { groqProvider } from "./groq.ts"; +import { huggingfaceProvider } from "./huggingface.ts"; +import { kimiCodingProvider } from "./kimi-coding.ts"; +import { minimaxProvider } from "./minimax.ts"; +import { minimaxCnProvider } from "./minimax-cn.ts"; +import { mistralProvider } from "./mistral.ts"; +import { moonshotaiProvider } from "./moonshotai.ts"; +import { moonshotaiCnProvider } from "./moonshotai-cn.ts"; +import { nvidiaProvider } from "./nvidia.ts"; +import { openaiProvider } from "./openai.ts"; +import { openaiCodexProvider } from "./openai-codex.ts"; +import { opencodeProvider } from "./opencode.ts"; +import { opencodeGoProvider } from "./opencode-go.ts"; +import { openrouterProvider } from "./openrouter.ts"; +import { openrouterImagesProvider } from "./openrouter-images.ts"; +import { qwenTokenPlanProvider } from "./qwen-token-plan.ts"; +import { qwenTokenPlanCnProvider } from "./qwen-token-plan-cn.ts"; +import { qwenTokenPlanIndividualProvider } from "./qwen-token-plan-individual.ts"; +import { radiusProvider } from "./radius.ts"; +import { togetherProvider } from "./together.ts"; +import { vercelAIGatewayProvider } from "./vercel-ai-gateway.ts"; +import { xaiProvider } from "./xai.ts"; +import { xiaomiProvider } from "./xiaomi.ts"; +import { xiaomiTokenPlanAmsProvider } from "./xiaomi-token-plan-ams.ts"; +import { xiaomiTokenPlanCnProvider } from "./xiaomi-token-plan-cn.ts"; +import { xiaomiTokenPlanSgpProvider } from "./xiaomi-token-plan-sgp.ts"; +import { zaiProvider } from "./zai.ts"; +import { zaiCodingCnProvider } from "./zai-coding-cn.ts"; + +export { radiusProvider }; + +/** Providers present in the generated catalog. `KnownProvider` additionally + * includes purely dynamic providers (e.g. "radius") that have no static + * catalog entry. */ +export type BuiltinProvider = keyof typeof MODELS; + +type BuiltinModelApi< + TProvider extends BuiltinProvider, + TModelId extends keyof (typeof MODELS)[TProvider], +> = (typeof MODELS)[TProvider][TModelId] extends { api: infer TApi } ? (TApi extends Api ? TApi : never) : never; + +/** Typed read of the generated built-in catalog. */ +export function getBuiltinModel( + provider: TProvider, + modelId: TModelId, +): Model> { + const models = MODELS[provider] as Record> | undefined; + return models?.[modelId as string] as Model>; +} + +export function getBuiltinProviders(): BuiltinProvider[] { + return Object.keys(MODELS) as BuiltinProvider[]; +} + +/** Generation timestamp shared by all built-in provider catalogs. */ +export function getBuiltinModelDataGeneratedAt(): number | undefined { + const generatedAt = Date.parse(modelDataManifest.generatedAt); + return Number.isNaN(generatedAt) ? undefined : generatedAt; +} + +export function getBuiltinModels( + provider: TProvider, +): Model>[] { + const models = MODELS[provider] as Record> | undefined; + return models + ? (Object.values(models) as Model>[]) + : []; +} + +/** All built-in providers, freshly constructed. */ +export function builtinProviders(): Provider[] { + return [ + amazonBedrockProvider(), + antLingProvider(), + anthropicProvider(), + azureOpenAIResponsesProvider(), + basetenProvider(), + cerebrasProvider(), + cloudflareAIGatewayProvider(), + cloudflareWorkersAIProvider(), + deepseekProvider(), + fireworksProvider(), + githubCopilotProvider(), + googleProvider(), + googleVertexProvider(), + groqProvider(), + huggingfaceProvider(), + kimiCodingProvider(), + minimaxProvider(), + minimaxCnProvider(), + mistralProvider(), + moonshotaiProvider(), + moonshotaiCnProvider(), + nvidiaProvider(), + openaiProvider(), + openaiCodexProvider(), + opencodeProvider(), + opencodeGoProvider(), + openrouterProvider(), + qwenTokenPlanProvider(), + qwenTokenPlanCnProvider(), + qwenTokenPlanIndividualProvider(), + radiusProvider(), + togetherProvider(), + vercelAIGatewayProvider(), + xaiProvider(), + xiaomiProvider(), + xiaomiTokenPlanAmsProvider(), + xiaomiTokenPlanCnProvider(), + xiaomiTokenPlanSgpProvider(), + zaiProvider(), + zaiCodingCnProvider(), + ]; +} + +/** A `Models` collection with every built-in provider registered. */ +export function builtinModels(options?: CreateModelsOptions): MutableModels { + const models = createModels(options); + for (const provider of builtinProviders()) { + models.setProvider(provider); + } + return models; +} + +/** All built-in image-generation providers, freshly constructed. */ +export function builtinImagesProviders(): ImagesProvider[] { + return [openrouterImagesProvider()]; +} + +/** An `ImagesModels` collection with every built-in image-generation provider registered. */ +export function builtinImagesModels(options?: CreateModelsOptions): MutableImagesModels { + const models = createImagesModels(options); + for (const provider of builtinImagesProviders()) { + models.setProvider(provider); + } + return models; +} diff --git a/packages/ai/src/providers/amazon-bedrock.ts b/packages/ai/src/providers/amazon-bedrock.ts new file mode 100644 index 0000000000000000000000000000000000000000..d629f1e1c3090718c782600e51f1d5228f6c3481 --- /dev/null +++ b/packages/ai/src/providers/amazon-bedrock.ts @@ -0,0 +1,90 @@ +import { bedrockConverseStreamApi } from "../api/bedrock-converse-stream.lazy.ts"; +import type { ApiKeyAuth } from "../auth/types.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { AMAZON_BEDROCK_MODELS } from "./amazon-bedrock.models.ts"; + +/** + * Bedrock accepts a bearer token or the AWS SDK's default credential chain. + * The login flow can store a token/profile choice; resolve also detects ambient + * AWS credentials without copying them into pi's credential store. + */ +const bedrockAuth: ApiKeyAuth = { + name: "AWS credentials or bearer token", + login: async (interaction) => { + interaction.signal.throwIfAborted(); + const method = await interaction.prompt({ + type: "select", + message: "Select Amazon Bedrock authentication method:", + options: [ + { id: "bearer-token", label: "Bearer token" }, + { id: "aws-profile", label: "AWS profile" }, + { id: "credential-chain", label: "Existing AWS credential chain" }, + ], + }); + interaction.signal.throwIfAborted(); + if (method === "bearer-token") { + return { + type: "api_key", + key: await interaction.prompt({ type: "secret", message: "Enter Amazon Bedrock bearer token" }), + }; + } + interaction.notify({ + type: "info", + message: "Amazon Bedrock supports AWS profiles, IAM credentials, and role-based credentials.", + links: [ + { + label: "AWS credential provider chain", + url: "https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html", + }, + ], + }); + if (method === "aws-profile") { + return { + type: "api_key", + env: { AWS_PROFILE: await interaction.prompt({ type: "text", message: "Enter AWS profile name" }) }, + }; + } + if (method !== "credential-chain") throw new Error(`Unknown Amazon Bedrock auth method: ${method}`); + await interaction.prompt({ + type: "text", + message: "Configure AWS credentials, then press Enter to continue", + }); + return { type: "api_key" }; + }, + resolve: async ({ ctx, credential, signal }) => { + const env = async (name: string) => { + signal.throwIfAborted(); + const value = await ctx.env(name); + signal.throwIfAborted(); + return value; + }; + if (credential?.key) { + return { auth: { apiKey: credential.key }, env: credential.env, source: "stored credential" }; + } + if (await env("AWS_BEARER_TOKEN_BEDROCK")) return { auth: {}, source: "AWS_BEARER_TOKEN_BEDROCK" }; + if (credential?.env?.AWS_PROFILE ?? (await env("AWS_PROFILE"))) { + return { + auth: {}, + env: credential?.env, + source: credential?.env?.AWS_PROFILE ? "stored credential" : "AWS_PROFILE", + }; + } + if ((await env("AWS_ACCESS_KEY_ID")) && (await env("AWS_SECRET_ACCESS_KEY"))) { + return { auth: {}, source: "AWS access keys" }; + } + if (await env("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")) return { auth: {}, source: "ECS task role" }; + if (await env("AWS_CONTAINER_CREDENTIALS_FULL_URI")) return { auth: {}, source: "ECS task role" }; + if (await env("AWS_WEB_IDENTITY_TOKEN_FILE")) return { auth: {}, source: "web identity token" }; + return undefined; + }, +}; + +export function amazonBedrockProvider(): Provider<"bedrock-converse-stream"> { + return createProvider({ + id: "amazon-bedrock", + name: "Amazon Bedrock", + auth: { apiKey: bedrockAuth }, + models: Object.values(AMAZON_BEDROCK_MODELS), + api: bedrockConverseStreamApi(), + }); +} diff --git a/packages/ai/src/providers/ant-ling.models.ts b/packages/ai/src/providers/ant-ling.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff190daab3aa80ba22a62c3a3a34d9de8bed5935 --- /dev/null +++ b/packages/ai/src/providers/ant-ling.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/ant-ling.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const ANT_LING_MODELS: ModelCatalog = + flattenModelCatalog("ant-ling", values); diff --git a/packages/ai/src/providers/ant-ling.ts b/packages/ai/src/providers/ant-ling.ts new file mode 100644 index 0000000000000000000000000000000000000000..03bb314d9940f30130c7a99c0e7ad478ebc85452 --- /dev/null +++ b/packages/ai/src/providers/ant-ling.ts @@ -0,0 +1,15 @@ +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { ANT_LING_MODELS } from "./ant-ling.models.ts"; + +export function antLingProvider(): Provider<"openai-completions"> { + return createProvider({ + id: "ant-ling", + name: "Ant Ling", + baseUrl: "https://api.ant-ling.com/v1", + auth: { apiKey: envApiKeyAuth("Ant Ling API key", ["ANT_LING_API_KEY"]) }, + models: Object.values(ANT_LING_MODELS), + api: openAICompletionsApi(), + }); +} diff --git a/packages/ai/src/providers/anthropic.models.ts b/packages/ai/src/providers/anthropic.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..43d5ed70f16e9bf72f57bc07b28a66a23a275d7d --- /dev/null +++ b/packages/ai/src/providers/anthropic.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/anthropic.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const ANTHROPIC_MODELS: ModelCatalog = + flattenModelCatalog("anthropic", values); diff --git a/packages/ai/src/providers/azure-openai-responses.models.ts b/packages/ai/src/providers/azure-openai-responses.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..d5f8c48ecdde97934cc9c5d21686d89249d5dab0 --- /dev/null +++ b/packages/ai/src/providers/azure-openai-responses.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/azure-openai-responses.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const AZURE_OPENAI_RESPONSES_MODELS: ModelCatalog = + flattenModelCatalog("azure-openai-responses", values); diff --git a/packages/ai/src/providers/azure-openai-responses.ts b/packages/ai/src/providers/azure-openai-responses.ts new file mode 100644 index 0000000000000000000000000000000000000000..78351deae417a06d0f05755105aba82fa2e0a76f --- /dev/null +++ b/packages/ai/src/providers/azure-openai-responses.ts @@ -0,0 +1,14 @@ +import { azureOpenAIResponsesApi } from "../api/azure-openai-responses.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { AZURE_OPENAI_RESPONSES_MODELS } from "./azure-openai-responses.models.ts"; + +export function azureOpenAIResponsesProvider(): Provider<"azure-openai-responses"> { + return createProvider({ + id: "azure-openai-responses", + name: "Azure OpenAI", + auth: { apiKey: envApiKeyAuth("Azure OpenAI API key", ["AZURE_OPENAI_API_KEY"]) }, + models: Object.values(AZURE_OPENAI_RESPONSES_MODELS), + api: azureOpenAIResponsesApi(), + }); +} diff --git a/packages/ai/src/providers/baseten.models.ts b/packages/ai/src/providers/baseten.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..22a55ac42c5cd5941bbe679fbf8bf62d90b7fe81 --- /dev/null +++ b/packages/ai/src/providers/baseten.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/baseten.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const BASETEN_MODELS: ModelCatalog = + flattenModelCatalog("baseten", values); diff --git a/packages/ai/src/providers/cerebras.ts b/packages/ai/src/providers/cerebras.ts new file mode 100644 index 0000000000000000000000000000000000000000..9ffc737554bc51ea9a155854bcc9d9014c49046b --- /dev/null +++ b/packages/ai/src/providers/cerebras.ts @@ -0,0 +1,15 @@ +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { CEREBRAS_MODELS } from "./cerebras.models.ts"; + +export function cerebrasProvider(): Provider<"openai-completions"> { + return createProvider({ + id: "cerebras", + name: "Cerebras", + baseUrl: "https://api.cerebras.ai/v1", + auth: { apiKey: envApiKeyAuth("Cerebras API key", ["CEREBRAS_API_KEY"]) }, + models: Object.values(CEREBRAS_MODELS), + api: openAICompletionsApi(), + }); +} diff --git a/packages/ai/src/providers/cloudflare-ai-gateway.ts b/packages/ai/src/providers/cloudflare-ai-gateway.ts new file mode 100644 index 0000000000000000000000000000000000000000..99d976225ad790cc86dd6954d0a6ad0b9a607e19 --- /dev/null +++ b/packages/ai/src/providers/cloudflare-ai-gateway.ts @@ -0,0 +1,27 @@ +import { anthropicMessagesApi } from "../api/anthropic-messages.lazy.ts"; +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { openAIResponsesApi } from "../api/openai-responses.lazy.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { CLOUDFLARE_AI_GATEWAY_MODELS } from "./cloudflare-ai-gateway.models.ts"; +import { cloudflareAIGatewayAuth } from "./cloudflare-auth.ts"; +import { cloudflareStreams } from "./cloudflare-stream.ts"; + +type CloudflareAIGatewayApi = "anthropic-messages" | "openai-completions" | "openai-responses"; + +export function cloudflareAIGatewayProvider(): Provider { + // The api map is pinned to all three APIs: models.dev's gateway catalog drops and + // restores `workers-ai/*` (openai-completions) entries over time, and inference from + // `models` alone would otherwise reject the openai-completions entry whenever the + // generated catalog happens to contain none. + return createProvider({ + id: "cloudflare-ai-gateway", + name: "Cloudflare AI Gateway", + auth: { apiKey: cloudflareAIGatewayAuth() }, + models: Object.values(CLOUDFLARE_AI_GATEWAY_MODELS), + api: { + "anthropic-messages": cloudflareStreams(anthropicMessagesApi()), + "openai-completions": cloudflareStreams(openAICompletionsApi()), + "openai-responses": cloudflareStreams(openAIResponsesApi()), + }, + }); +} diff --git a/packages/ai/src/providers/cloudflare-auth.ts b/packages/ai/src/providers/cloudflare-auth.ts new file mode 100644 index 0000000000000000000000000000000000000000..72fd23d07df18546c3575f7f4d724def1b74c824 --- /dev/null +++ b/packages/ai/src/providers/cloudflare-auth.ts @@ -0,0 +1,103 @@ +import type { ApiKeyAuth, ApiKeyCredential, AuthContext } from "../auth/types.ts"; +import type { ProviderEnv } from "../types.ts"; + +const CLOUDFLARE_API_KEY = "CLOUDFLARE_API_KEY"; +const CLOUDFLARE_ACCOUNT_ID = "CLOUDFLARE_ACCOUNT_ID"; +const CLOUDFLARE_GATEWAY_ID = "CLOUDFLARE_GATEWAY_ID"; + +type CloudflareAuthKind = "workers-ai" | "ai-gateway"; + +async function resolveValue( + name: string, + ctx: AuthContext, + credential: ApiKeyCredential | undefined, + signal: AbortSignal, +): Promise { + // Per-field merge: prefer the credential value, fall back to ambient env. + // A credential carrying only the API key must still pick up the account / + // gateway id from the environment. + const fromCredential = credential + ? name === CLOUDFLARE_API_KEY + ? credential.key + : credential.env?.[name] + : undefined; + if (fromCredential !== undefined) return fromCredential; + signal.throwIfAborted(); + const value = await ctx.env(name); + signal.throwIfAborted(); + return value; +} + +async function resolveCloudflareEnv( + kind: CloudflareAuthKind, + ctx: AuthContext, + credential: ApiKeyCredential | undefined, + signal: AbortSignal, +): Promise<{ apiKey: string; env: ProviderEnv; source: string } | undefined> { + const apiKey = await resolveValue(CLOUDFLARE_API_KEY, ctx, credential, signal); + const accountId = await resolveValue(CLOUDFLARE_ACCOUNT_ID, ctx, credential, signal); + const gatewayId = + kind === "ai-gateway" ? await resolveValue(CLOUDFLARE_GATEWAY_ID, ctx, credential, signal) : undefined; + + if (!apiKey || !accountId || (kind === "ai-gateway" && !gatewayId)) return undefined; + + return { + apiKey, + env: { + CLOUDFLARE_ACCOUNT_ID: accountId, + ...(gatewayId ? { CLOUDFLARE_GATEWAY_ID: gatewayId } : {}), + }, + source: credential ? "stored credential" : CLOUDFLARE_API_KEY, + }; +} + +export function cloudflareWorkersAIAuth(): ApiKeyAuth { + return { + name: "Cloudflare API key", + login: async (interaction) => { + const key = await interaction.prompt({ type: "secret", message: "Enter Cloudflare API key" }); + const accountId = await interaction.prompt({ type: "text", message: "Enter Cloudflare account ID" }); + return { type: "api_key", key, env: { CLOUDFLARE_ACCOUNT_ID: accountId } }; + }, + resolve: async ({ ctx, credential, signal }) => { + const resolved = await resolveCloudflareEnv("workers-ai", ctx, credential, signal); + if (!resolved) return undefined; + return { + auth: { apiKey: resolved.apiKey }, + env: resolved.env, + source: resolved.source, + }; + }, + }; +} + +export function cloudflareAIGatewayAuth(): ApiKeyAuth { + return { + name: "Cloudflare API key", + login: async (interaction) => { + const key = await interaction.prompt({ type: "secret", message: "Enter Cloudflare API key" }); + const accountId = await interaction.prompt({ type: "text", message: "Enter Cloudflare account ID" }); + const gatewayId = await interaction.prompt({ type: "text", message: "Enter Cloudflare AI Gateway ID" }); + return { + type: "api_key", + key, + env: { CLOUDFLARE_ACCOUNT_ID: accountId, CLOUDFLARE_GATEWAY_ID: gatewayId }, + }; + }, + resolve: async ({ ctx, credential, signal }) => { + const resolved = await resolveCloudflareEnv("ai-gateway", ctx, credential, signal); + if (!resolved) return undefined; + return { + auth: { + headers: { + "cf-aig-authorization": `Bearer ${resolved.apiKey}`, + Authorization: null, + "x-api-key": null, + }, + }, + env: resolved.env, + source: resolved.source, + }; + }, + }; +} diff --git a/packages/ai/src/providers/cloudflare-stream.ts b/packages/ai/src/providers/cloudflare-stream.ts new file mode 100644 index 0000000000000000000000000000000000000000..7284f65626aed1305019a13577da485a542b9b50 --- /dev/null +++ b/packages/ai/src/providers/cloudflare-stream.ts @@ -0,0 +1,28 @@ +import type { Api, Model, ProviderEnv, ProviderStreams } from "../types.ts"; + +const CLOUDFLARE_ACCOUNT_ID = "CLOUDFLARE_ACCOUNT_ID"; +const CLOUDFLARE_GATEWAY_ID = "CLOUDFLARE_GATEWAY_ID"; + +export function resolveCloudflareModel( + model: Model, + env: ProviderEnv | undefined, +): Model { + if (!env) return model; + const baseUrl = model.baseUrl + .replaceAll(`{${CLOUDFLARE_ACCOUNT_ID}}`, env[CLOUDFLARE_ACCOUNT_ID] ?? `{${CLOUDFLARE_ACCOUNT_ID}}`) + .replaceAll(`{${CLOUDFLARE_GATEWAY_ID}}`, env[CLOUDFLARE_GATEWAY_ID] ?? `{${CLOUDFLARE_GATEWAY_ID}}`); + return baseUrl === model.baseUrl ? model : { ...model, baseUrl }; +} + +/** + * Wrap an API implementation so Cloudflare account/gateway endpoint + * placeholders materialize from the resolved provider env before dispatch. + */ +export function cloudflareStreams(streams: ProviderStreams): ProviderStreams { + return { + stream: (model, context, options) => + streams.stream(resolveCloudflareModel(model, options?.env), context, options), + streamSimple: (model, context, options) => + streams.streamSimple(resolveCloudflareModel(model, options?.env), context, options), + }; +} diff --git a/packages/ai/src/providers/cloudflare-workers-ai.models.ts b/packages/ai/src/providers/cloudflare-workers-ai.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..35a7578ffc593e5e1e26582352eceda759b2eba6 --- /dev/null +++ b/packages/ai/src/providers/cloudflare-workers-ai.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/cloudflare-workers-ai.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const CLOUDFLARE_WORKERS_AI_MODELS: ModelCatalog = + flattenModelCatalog("cloudflare-workers-ai", values); diff --git a/packages/ai/src/providers/deepseek.models.ts b/packages/ai/src/providers/deepseek.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..f99b3a5b301a33dc8a96b132fc2190edde4c8c7e --- /dev/null +++ b/packages/ai/src/providers/deepseek.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/deepseek.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const DEEPSEEK_MODELS: ModelCatalog = + flattenModelCatalog("deepseek", values); diff --git a/packages/ai/src/providers/fireworks.models.ts b/packages/ai/src/providers/fireworks.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..ffb0b09c0a58b9e04dedb78946242e38175c94f1 --- /dev/null +++ b/packages/ai/src/providers/fireworks.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/fireworks.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const FIREWORKS_MODELS: ModelCatalog = + flattenModelCatalog("fireworks", values); diff --git a/packages/ai/src/providers/github-copilot.ts b/packages/ai/src/providers/github-copilot.ts new file mode 100644 index 0000000000000000000000000000000000000000..eab784d88840f4a29829066ee4b402d10d94e754 --- /dev/null +++ b/packages/ai/src/providers/github-copilot.ts @@ -0,0 +1,34 @@ +import { anthropicMessagesApi } from "../api/anthropic-messages.lazy.ts"; +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { openAIResponsesApi } from "../api/openai-responses.lazy.ts"; +import { envApiKeyAuth, lazyOAuth } from "../auth/helpers.ts"; +import { loadGitHubCopilotOAuth } from "../auth/oauth/load.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { GITHUB_COPILOT_MODELS } from "./github-copilot.models.ts"; + +export function githubCopilotProvider(): Provider<"anthropic-messages" | "openai-completions" | "openai-responses"> { + return createProvider({ + id: "github-copilot", + name: "GitHub Copilot", + baseUrl: "https://api.individual.githubcopilot.com", + auth: { + apiKey: envApiKeyAuth("GitHub Copilot token", ["COPILOT_GITHUB_TOKEN"]), + oauth: lazyOAuth({ name: "GitHub Copilot", isSubscription: true, load: loadGitHubCopilotOAuth }), + }, + models: Object.values(GITHUB_COPILOT_MODELS), + filterModels: (models, credential) => { + if (credential?.type !== "oauth") return models; + const availableModelIds = credential.availableModelIds; + if (!Array.isArray(availableModelIds) || !availableModelIds.every((id) => typeof id === "string")) { + return models; + } + const available = new Set(availableModelIds); + return models.filter((model) => available.has(model.id)); + }, + api: { + "anthropic-messages": anthropicMessagesApi(), + "openai-completions": openAICompletionsApi(), + "openai-responses": openAIResponsesApi(), + }, + }); +} diff --git a/packages/ai/src/providers/google-vertex.models.ts b/packages/ai/src/providers/google-vertex.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e8b6b5594650cd2278fb939a5612d33b71dd93a --- /dev/null +++ b/packages/ai/src/providers/google-vertex.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/google-vertex.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const GOOGLE_VERTEX_MODELS: ModelCatalog = + flattenModelCatalog("google-vertex", values); diff --git a/packages/ai/src/providers/google.models.ts b/packages/ai/src/providers/google.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d0989d6a7d73a4b0545dbcdd25dc08cf3d4a627 --- /dev/null +++ b/packages/ai/src/providers/google.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/google.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const GOOGLE_MODELS: ModelCatalog = + flattenModelCatalog("google", values); diff --git a/packages/ai/src/providers/google.ts b/packages/ai/src/providers/google.ts new file mode 100644 index 0000000000000000000000000000000000000000..0bd452373227e781b961a3eb37d6a0fc3aead8a6 --- /dev/null +++ b/packages/ai/src/providers/google.ts @@ -0,0 +1,15 @@ +import { googleGenerativeAIApi } from "../api/google-generative-ai.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { GOOGLE_MODELS } from "./google.models.ts"; + +export function googleProvider(): Provider<"google-generative-ai"> { + return createProvider({ + id: "google", + name: "Google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + auth: { apiKey: envApiKeyAuth("Gemini API key", ["GEMINI_API_KEY"]) }, + models: Object.values(GOOGLE_MODELS), + api: googleGenerativeAIApi(), + }); +} diff --git a/packages/ai/src/providers/groq.models.ts b/packages/ai/src/providers/groq.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..770bf0ca568951ae46a8efce8f682bd422d0f064 --- /dev/null +++ b/packages/ai/src/providers/groq.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/groq.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const GROQ_MODELS: ModelCatalog = + flattenModelCatalog("groq", values); diff --git a/packages/ai/src/providers/groq.ts b/packages/ai/src/providers/groq.ts new file mode 100644 index 0000000000000000000000000000000000000000..5892e0488264e2ef53e09ed581179f107e4528db --- /dev/null +++ b/packages/ai/src/providers/groq.ts @@ -0,0 +1,15 @@ +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { GROQ_MODELS } from "./groq.models.ts"; + +export function groqProvider(): Provider<"openai-completions"> { + return createProvider({ + id: "groq", + name: "Groq", + baseUrl: "https://api.groq.com/openai/v1", + auth: { apiKey: envApiKeyAuth("Groq API key", ["GROQ_API_KEY"]) }, + models: Object.values(GROQ_MODELS), + api: openAICompletionsApi(), + }); +} diff --git a/packages/ai/src/providers/huggingface.models.ts b/packages/ai/src/providers/huggingface.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..490d2793a3224c827d22d2b023b0cb04d4365feb --- /dev/null +++ b/packages/ai/src/providers/huggingface.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/huggingface.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const HUGGINGFACE_MODELS: ModelCatalog = + flattenModelCatalog("huggingface", values); diff --git a/packages/ai/src/providers/kimi-coding.models.ts b/packages/ai/src/providers/kimi-coding.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..4decb71f46bc0cc3bbb22510fbcd4be25b1267e6 --- /dev/null +++ b/packages/ai/src/providers/kimi-coding.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/kimi-coding.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const KIMI_CODING_MODELS: ModelCatalog = + flattenModelCatalog("kimi-coding", values); diff --git a/packages/ai/src/providers/kimi-coding.ts b/packages/ai/src/providers/kimi-coding.ts new file mode 100644 index 0000000000000000000000000000000000000000..81ae4af2e92e08eb31eafab4d760c5692bc2b1c2 --- /dev/null +++ b/packages/ai/src/providers/kimi-coding.ts @@ -0,0 +1,24 @@ +import { anthropicMessagesApi } from "../api/anthropic-messages.lazy.ts"; +import { envApiKeyAuth, lazyOAuth } from "../auth/helpers.ts"; +import { loadKimiCodingOAuth } from "../auth/oauth/load.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { KIMI_CODING_MODELS } from "./kimi-coding.models.ts"; + +export function kimiCodingProvider(): Provider<"anthropic-messages"> { + return createProvider({ + id: "kimi-coding", + name: "Kimi For Coding", + baseUrl: "https://api.kimi.com/coding", + auth: { + apiKey: envApiKeyAuth("Kimi API key", ["KIMI_API_KEY"]), + oauth: lazyOAuth({ + name: "Kimi Code (subscription)", + isSubscription: true, + loginLabel: "Sign in with Kimi Code", + load: loadKimiCodingOAuth, + }), + }, + models: Object.values(KIMI_CODING_MODELS), + api: anthropicMessagesApi(), + }); +} diff --git a/packages/ai/src/providers/minimax-cn.models.ts b/packages/ai/src/providers/minimax-cn.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ee19be2a8c3b347e14cc73191e11fec55919926 --- /dev/null +++ b/packages/ai/src/providers/minimax-cn.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/minimax-cn.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const MINIMAX_CN_MODELS: ModelCatalog = + flattenModelCatalog("minimax-cn", values); diff --git a/packages/ai/src/providers/minimax-cn.ts b/packages/ai/src/providers/minimax-cn.ts new file mode 100644 index 0000000000000000000000000000000000000000..5cbe5acc55926d52fac7ffa3008c2c903ed0d86b --- /dev/null +++ b/packages/ai/src/providers/minimax-cn.ts @@ -0,0 +1,15 @@ +import { anthropicMessagesApi } from "../api/anthropic-messages.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { MINIMAX_CN_MODELS } from "./minimax-cn.models.ts"; + +export function minimaxCnProvider(): Provider<"anthropic-messages"> { + return createProvider({ + id: "minimax-cn", + name: "MiniMax CN", + baseUrl: "https://api.minimaxi.com/anthropic", + auth: { apiKey: envApiKeyAuth("MiniMax CN API key", ["MINIMAX_CN_API_KEY"]) }, + models: Object.values(MINIMAX_CN_MODELS), + api: anthropicMessagesApi(), + }); +} diff --git a/packages/ai/src/providers/minimax.ts b/packages/ai/src/providers/minimax.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a956bd6bbdc29084c66ad2100a2ec72485de2f5 --- /dev/null +++ b/packages/ai/src/providers/minimax.ts @@ -0,0 +1,15 @@ +import { anthropicMessagesApi } from "../api/anthropic-messages.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { MINIMAX_MODELS } from "./minimax.models.ts"; + +export function minimaxProvider(): Provider<"anthropic-messages"> { + return createProvider({ + id: "minimax", + name: "MiniMax", + baseUrl: "https://api.minimax.io/anthropic", + auth: { apiKey: envApiKeyAuth("MiniMax API key", ["MINIMAX_API_KEY"]) }, + models: Object.values(MINIMAX_MODELS), + api: anthropicMessagesApi(), + }); +} diff --git a/packages/ai/src/providers/mistral.ts b/packages/ai/src/providers/mistral.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b84a71fb66f8a2cbfb81728d542281c16014548 --- /dev/null +++ b/packages/ai/src/providers/mistral.ts @@ -0,0 +1,15 @@ +import { mistralConversationsApi } from "../api/mistral-conversations.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { MISTRAL_MODELS } from "./mistral.models.ts"; + +export function mistralProvider(): Provider<"mistral-conversations"> { + return createProvider({ + id: "mistral", + name: "Mistral", + baseUrl: "https://api.mistral.ai", + auth: { apiKey: envApiKeyAuth("Mistral API key", ["MISTRAL_API_KEY"]) }, + models: Object.values(MISTRAL_MODELS), + api: mistralConversationsApi(), + }); +} diff --git a/packages/ai/src/providers/moonshotai-cn.ts b/packages/ai/src/providers/moonshotai-cn.ts new file mode 100644 index 0000000000000000000000000000000000000000..b813734bcfe6761c4ae000bfce9571c02942f7a9 --- /dev/null +++ b/packages/ai/src/providers/moonshotai-cn.ts @@ -0,0 +1,15 @@ +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { MOONSHOTAI_CN_MODELS } from "./moonshotai-cn.models.ts"; + +export function moonshotaiCnProvider(): Provider<"openai-completions"> { + return createProvider({ + id: "moonshotai-cn", + name: "Moonshot AI CN", + baseUrl: "https://api.moonshot.cn/v1", + auth: { apiKey: envApiKeyAuth("Moonshot AI API key", ["MOONSHOT_API_KEY"]) }, + models: Object.values(MOONSHOTAI_CN_MODELS), + api: openAICompletionsApi(), + }); +} diff --git a/packages/ai/src/providers/moonshotai.ts b/packages/ai/src/providers/moonshotai.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc15c5706ad333e58d09daec9daf4b3840e778dd --- /dev/null +++ b/packages/ai/src/providers/moonshotai.ts @@ -0,0 +1,15 @@ +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { MOONSHOTAI_MODELS } from "./moonshotai.models.ts"; + +export function moonshotaiProvider(): Provider<"openai-completions"> { + return createProvider({ + id: "moonshotai", + name: "Moonshot AI", + baseUrl: "https://api.moonshot.ai/v1", + auth: { apiKey: envApiKeyAuth("Moonshot AI API key", ["MOONSHOT_API_KEY"]) }, + models: Object.values(MOONSHOTAI_MODELS), + api: openAICompletionsApi(), + }); +} diff --git a/packages/ai/src/providers/nvidia.models.ts b/packages/ai/src/providers/nvidia.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d31b205d3abed31291c1ecbb19430f8519ef099 --- /dev/null +++ b/packages/ai/src/providers/nvidia.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/nvidia.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const NVIDIA_MODELS: ModelCatalog = + flattenModelCatalog("nvidia", values); diff --git a/packages/ai/src/providers/nvidia.ts b/packages/ai/src/providers/nvidia.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc539f60b685c63842b0f68ce93d03cfdd05e7fd --- /dev/null +++ b/packages/ai/src/providers/nvidia.ts @@ -0,0 +1,15 @@ +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { NVIDIA_MODELS } from "./nvidia.models.ts"; + +export function nvidiaProvider(): Provider<"openai-completions"> { + return createProvider({ + id: "nvidia", + name: "NVIDIA", + baseUrl: "https://integrate.api.nvidia.com/v1", + auth: { apiKey: envApiKeyAuth("NVIDIA API key", ["NVIDIA_API_KEY"]) }, + models: Object.values(NVIDIA_MODELS), + api: openAICompletionsApi(), + }); +} diff --git a/packages/ai/src/providers/openai-codex.models.ts b/packages/ai/src/providers/openai-codex.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..43b500f79a2bbc4cf6550e1639f466d8b6d4d7ac --- /dev/null +++ b/packages/ai/src/providers/openai-codex.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/openai-codex.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const OPENAI_CODEX_MODELS: ModelCatalog = + flattenModelCatalog("openai-codex", values); diff --git a/packages/ai/src/providers/openai.models.ts b/packages/ai/src/providers/openai.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4ba19c9cc3a0f53339bea4c0d0105a1dfc0eff9 --- /dev/null +++ b/packages/ai/src/providers/openai.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/openai.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const OPENAI_MODELS: ModelCatalog = + flattenModelCatalog("openai", values); diff --git a/packages/ai/src/providers/opencode-go.ts b/packages/ai/src/providers/opencode-go.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c0b58f4b7f7352307c4b8f09cbcd93750f4a5ad --- /dev/null +++ b/packages/ai/src/providers/opencode-go.ts @@ -0,0 +1,21 @@ +import { anthropicMessagesApi } from "../api/anthropic-messages.lazy.ts"; +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { openAIResponsesApi } from "../api/openai-responses.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { OPENCODE_GO_MODELS } from "./opencode-go.models.ts"; +import { withOpenCodeSessionHeader } from "./opencode-headers.ts"; + +export function opencodeGoProvider(): Provider<"anthropic-messages" | "openai-completions" | "openai-responses"> { + return createProvider<"anthropic-messages" | "openai-completions" | "openai-responses">({ + id: "opencode-go", + name: "OpenCode Go", + auth: { apiKey: envApiKeyAuth("OpenCode API key", ["OPENCODE_API_KEY"]) }, + models: Object.values(OPENCODE_GO_MODELS), + api: { + "anthropic-messages": withOpenCodeSessionHeader(anthropicMessagesApi()), + "openai-completions": withOpenCodeSessionHeader(openAICompletionsApi()), + "openai-responses": withOpenCodeSessionHeader(openAIResponsesApi()), + }, + }); +} diff --git a/packages/ai/src/providers/opencode.models.ts b/packages/ai/src/providers/opencode.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2d6b396126d64a0e41602a7f2a3eb4c07d007e7 --- /dev/null +++ b/packages/ai/src/providers/opencode.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/opencode.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const OPENCODE_MODELS: ModelCatalog = + flattenModelCatalog("opencode", values); diff --git a/packages/ai/src/providers/opencode.ts b/packages/ai/src/providers/opencode.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6126f68da92cac0d36856961a9b21d08c38c5eb --- /dev/null +++ b/packages/ai/src/providers/opencode.ts @@ -0,0 +1,25 @@ +import { anthropicMessagesApi } from "../api/anthropic-messages.lazy.ts"; +import { googleGenerativeAIApi } from "../api/google-generative-ai.lazy.ts"; +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { openAIResponsesApi } from "../api/openai-responses.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { OPENCODE_MODELS } from "./opencode.models.ts"; +import { withOpenCodeSessionHeader } from "./opencode-headers.ts"; + +export function opencodeProvider(): Provider< + "anthropic-messages" | "google-generative-ai" | "openai-completions" | "openai-responses" +> { + return createProvider({ + id: "opencode", + name: "OpenCode Zen", + auth: { apiKey: envApiKeyAuth("OpenCode API key", ["OPENCODE_API_KEY"]) }, + models: Object.values(OPENCODE_MODELS), + api: { + "anthropic-messages": withOpenCodeSessionHeader(anthropicMessagesApi()), + "google-generative-ai": withOpenCodeSessionHeader(googleGenerativeAIApi()), + "openai-completions": withOpenCodeSessionHeader(openAICompletionsApi()), + "openai-responses": withOpenCodeSessionHeader(openAIResponsesApi()), + }, + }); +} diff --git a/packages/ai/src/providers/openrouter.ts b/packages/ai/src/providers/openrouter.ts new file mode 100644 index 0000000000000000000000000000000000000000..382a5f1a4ce07ad9cdadeefd192e8be416cc5866 --- /dev/null +++ b/packages/ai/src/providers/openrouter.ts @@ -0,0 +1,27 @@ +import { anthropicMessagesApi } from "../api/anthropic-messages.lazy.ts"; +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth, lazyOAuth } from "../auth/helpers.ts"; +import { loadOpenRouterOAuth } from "../auth/oauth/load.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { OPENROUTER_MODELS } from "./openrouter.models.ts"; + +export function openrouterProvider(): Provider<"anthropic-messages" | "openai-completions"> { + return createProvider({ + id: "openrouter", + name: "OpenRouter", + baseUrl: "https://openrouter.ai/api/v1", + auth: { + apiKey: envApiKeyAuth("OpenRouter API key", ["OPENROUTER_API_KEY"]), + oauth: lazyOAuth({ + name: "OpenRouter OAuth", + loginLabel: "Sign in with OpenRouter", + load: loadOpenRouterOAuth, + }), + }, + models: Object.values(OPENROUTER_MODELS), + api: { + "anthropic-messages": anthropicMessagesApi(), + "openai-completions": openAICompletionsApi(), + }, + }); +} diff --git a/packages/ai/src/providers/qwen-token-plan-cn.models.ts b/packages/ai/src/providers/qwen-token-plan-cn.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..5fe4244cd9c87277459b9c87167e00c39df8aa55 --- /dev/null +++ b/packages/ai/src/providers/qwen-token-plan-cn.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/qwen-token-plan-cn.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const QWEN_TOKEN_PLAN_CN_MODELS: ModelCatalog = + flattenModelCatalog("qwen-token-plan-cn", values); diff --git a/packages/ai/src/providers/qwen-token-plan-cn.ts b/packages/ai/src/providers/qwen-token-plan-cn.ts new file mode 100644 index 0000000000000000000000000000000000000000..259b5a7f028f302e421f91fec6490d5c2e862632 --- /dev/null +++ b/packages/ai/src/providers/qwen-token-plan-cn.ts @@ -0,0 +1,15 @@ +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { QWEN_TOKEN_PLAN_CN_MODELS } from "./qwen-token-plan-cn.models.ts"; + +export function qwenTokenPlanCnProvider(): Provider<"openai-completions"> { + return createProvider({ + id: "qwen-token-plan-cn", + name: "Qwen Token Plan CN", + baseUrl: "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1", + auth: { apiKey: envApiKeyAuth("Qwen Token Plan CN API key", ["QWEN_TOKEN_PLAN_CN_API_KEY"]) }, + models: Object.values(QWEN_TOKEN_PLAN_CN_MODELS), + api: openAICompletionsApi(), + }); +} diff --git a/packages/ai/src/providers/qwen-token-plan-individual.ts b/packages/ai/src/providers/qwen-token-plan-individual.ts new file mode 100644 index 0000000000000000000000000000000000000000..a231d1b313d1646c5e9053e09d1b9767c2acb2a2 --- /dev/null +++ b/packages/ai/src/providers/qwen-token-plan-individual.ts @@ -0,0 +1,15 @@ +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { QWEN_TOKEN_PLAN_INDIVIDUAL_MODELS } from "./qwen-token-plan-individual.models.ts"; + +export function qwenTokenPlanIndividualProvider(): Provider<"openai-completions"> { + return createProvider({ + id: "qwen-token-plan-individual", + name: "Qwen Token Plan Individual", + baseUrl: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", + auth: { apiKey: envApiKeyAuth("Qwen Token Plan Individual API key", ["QWEN_TOKEN_PLAN_API_KEY"]) }, + models: Object.values(QWEN_TOKEN_PLAN_INDIVIDUAL_MODELS), + api: openAICompletionsApi(), + }); +} diff --git a/packages/ai/src/providers/qwen-token-plan.ts b/packages/ai/src/providers/qwen-token-plan.ts new file mode 100644 index 0000000000000000000000000000000000000000..295560ba2afbcc74d2509d4acbb0c89ba6624f81 --- /dev/null +++ b/packages/ai/src/providers/qwen-token-plan.ts @@ -0,0 +1,15 @@ +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { QWEN_TOKEN_PLAN_MODELS } from "./qwen-token-plan.models.ts"; + +export function qwenTokenPlanProvider(): Provider<"openai-completions"> { + return createProvider({ + id: "qwen-token-plan", + name: "Qwen Token Plan", + baseUrl: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", + auth: { apiKey: envApiKeyAuth("Qwen Token Plan API key", ["QWEN_TOKEN_PLAN_API_KEY"]) }, + models: Object.values(QWEN_TOKEN_PLAN_MODELS), + api: openAICompletionsApi(), + }); +} diff --git a/packages/ai/src/providers/radius-config.ts b/packages/ai/src/providers/radius-config.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2715aaec31ec99afe9b302d1d289546319a97f4 --- /dev/null +++ b/packages/ai/src/providers/radius-config.ts @@ -0,0 +1,96 @@ +import type { OAuthCredential } from "../auth/types.ts"; +import type { Model, ThinkingLevelMap } from "../types.ts"; + +export const DEFAULT_RADIUS_GATEWAY = "https://radius.pi.dev"; + +export type RadiusGatewayModel = { + id: string; + name: string; + reasoning: boolean; + thinkingLevelMap?: ThinkingLevelMap; + input: ("text" | "image")[]; + cost: Model<"pi-messages">["cost"]; + contextWindow: number; + maxTokens: number; +}; + +export type RadiusGatewayConfig = { + baseUrl: string; + models: RadiusGatewayModel[]; +}; + +export type RadiusOAuthCredential = OAuthCredential & { + gatewayConfig?: RadiusGatewayConfig; +}; + +function isRadiusGatewayModel(value: unknown): value is RadiusGatewayModel { + if (typeof value !== "object" || value === null || Array.isArray(value)) return false; + const model = value as Partial; + return ( + typeof model.id === "string" && + typeof model.name === "string" && + typeof model.reasoning === "boolean" && + Array.isArray(model.input) && + typeof model.cost === "object" && + model.cost !== null && + !Array.isArray(model.cost) && + typeof model.contextWindow === "number" && + typeof model.maxTokens === "number" + ); +} + +function sanitizeRadiusGatewayConfig(config: unknown): RadiusGatewayConfig | undefined { + if (typeof config !== "object" || config === null || Array.isArray(config)) return undefined; + const { baseUrl, models } = config as Partial; + if (typeof baseUrl !== "string" || !Array.isArray(models)) return undefined; + return { + baseUrl, + models: models.filter(isRadiusGatewayModel).map((model) => ({ ...model })), + }; +} + +export function normalizeRadiusGatewayUrl(value: string): string { + const withScheme = /^https?:\/\//iu.test(value) ? value : `https://${value}`; + return withScheme.replace(/\/+$/u, ""); +} + +export function getRadiusCredentialConfig(credential: OAuthCredential | undefined): RadiusGatewayConfig | undefined { + return sanitizeRadiusGatewayConfig((credential as RadiusOAuthCredential | undefined)?.gatewayConfig); +} + +export function getRadiusModelsFromConfig(providerId: string, config: RadiusGatewayConfig): Model<"pi-messages">[] { + return config.models.map((model) => ({ + ...model, + api: "pi-messages", + provider: providerId, + baseUrl: config.baseUrl, + })); +} + +export function getRadiusModels(providerId: string, credential: OAuthCredential | undefined): Model<"pi-messages">[] { + const config = getRadiusCredentialConfig(credential); + return config ? getRadiusModelsFromConfig(providerId, config) : []; +} + +function truncateHttpBody(body: string): string { + const trimmed = body.trim(); + return trimmed.length > 512 ? `${trimmed.slice(0, 512)}…` : trimmed; +} + +export async function loadRadiusGatewayConfig( + gateway: string, + apiKey?: string, + signal?: AbortSignal, +): Promise { + const headers: Record = { accept: "application/json" }; + if (apiKey) headers.authorization = `Bearer ${apiKey}`; + const response = await fetch(new URL("/v1/config", gateway), { headers, signal }); + if (!response.ok) { + throw new Error( + `Could not load Radius config from ${gateway}: ${response.status}: ${truncateHttpBody(await response.text())}`, + ); + } + const config = sanitizeRadiusGatewayConfig(await response.json()); + if (!config) throw new Error(`Invalid Radius config from ${gateway}`); + return config; +} diff --git a/packages/ai/src/providers/together.models.ts b/packages/ai/src/providers/together.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..d5223b9eb0c2f6c956bfd055d944cb699df04cb8 --- /dev/null +++ b/packages/ai/src/providers/together.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/together.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const TOGETHER_MODELS: ModelCatalog = + flattenModelCatalog("together", values); diff --git a/packages/ai/src/providers/vercel-ai-gateway.models.ts b/packages/ai/src/providers/vercel-ai-gateway.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..24cfce859de25839e90e4c53f1f37290e17e690f --- /dev/null +++ b/packages/ai/src/providers/vercel-ai-gateway.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/vercel-ai-gateway.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const VERCEL_AI_GATEWAY_MODELS: ModelCatalog = + flattenModelCatalog("vercel-ai-gateway", values); diff --git a/packages/ai/src/providers/vercel-ai-gateway.ts b/packages/ai/src/providers/vercel-ai-gateway.ts new file mode 100644 index 0000000000000000000000000000000000000000..3aca03283fc55fb158bfced6eb6c0ae7b66f9d64 --- /dev/null +++ b/packages/ai/src/providers/vercel-ai-gateway.ts @@ -0,0 +1,15 @@ +import { anthropicMessagesApi } from "../api/anthropic-messages.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { VERCEL_AI_GATEWAY_MODELS } from "./vercel-ai-gateway.models.ts"; + +export function vercelAIGatewayProvider(): Provider<"anthropic-messages"> { + return createProvider({ + id: "vercel-ai-gateway", + name: "Vercel AI Gateway", + baseUrl: "https://ai-gateway.vercel.sh", + auth: { apiKey: envApiKeyAuth("Vercel AI Gateway API key", ["AI_GATEWAY_API_KEY"]) }, + models: Object.values(VERCEL_AI_GATEWAY_MODELS), + api: anthropicMessagesApi(), + }); +} diff --git a/packages/ai/src/providers/xai.models.ts b/packages/ai/src/providers/xai.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..333a41aeba09d68d5475829d63338a50260edce2 --- /dev/null +++ b/packages/ai/src/providers/xai.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/xai.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const XAI_MODELS: ModelCatalog = + flattenModelCatalog("xai", values); diff --git a/packages/ai/src/providers/xiaomi-token-plan-ams.models.ts b/packages/ai/src/providers/xiaomi-token-plan-ams.models.ts new file mode 100644 index 0000000000000000000000000000000000000000..fdfddae77eb66b0d331596eb7b0ff9a2321b5754 --- /dev/null +++ b/packages/ai/src/providers/xiaomi-token-plan-ams.models.ts @@ -0,0 +1,8 @@ +// This file is auto-generated by scripts/generate-models.ts +// Do not edit manually - run 'npm run generate-models' to update + +import values from "./data/xiaomi-token-plan-ams.json" with { type: "json" }; +import { flattenModelCatalog, type ModelCatalog } from "../model-catalog.ts"; + +export const XIAOMI_TOKEN_PLAN_AMS_MODELS: ModelCatalog = + flattenModelCatalog("xiaomi-token-plan-ams", values); diff --git a/packages/ai/src/providers/xiaomi-token-plan-ams.ts b/packages/ai/src/providers/xiaomi-token-plan-ams.ts new file mode 100644 index 0000000000000000000000000000000000000000..017aa67192c8a1fd4685feb2bf67c08edf0a100c --- /dev/null +++ b/packages/ai/src/providers/xiaomi-token-plan-ams.ts @@ -0,0 +1,15 @@ +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { XIAOMI_TOKEN_PLAN_AMS_MODELS } from "./xiaomi-token-plan-ams.models.ts"; + +export function xiaomiTokenPlanAmsProvider(): Provider<"openai-completions"> { + return createProvider({ + id: "xiaomi-token-plan-ams", + name: "Xiaomi Token Plan AMS", + baseUrl: "https://token-plan-ams.xiaomimimo.com/v1", + auth: { apiKey: envApiKeyAuth("Xiaomi Token Plan AMS API key", ["XIAOMI_TOKEN_PLAN_AMS_API_KEY"]) }, + models: Object.values(XIAOMI_TOKEN_PLAN_AMS_MODELS), + api: openAICompletionsApi(), + }); +} diff --git a/packages/ai/src/providers/xiaomi-token-plan-sgp.ts b/packages/ai/src/providers/xiaomi-token-plan-sgp.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3762057f42f415fe45c8d5104cf9f453d985812 --- /dev/null +++ b/packages/ai/src/providers/xiaomi-token-plan-sgp.ts @@ -0,0 +1,15 @@ +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { XIAOMI_TOKEN_PLAN_SGP_MODELS } from "./xiaomi-token-plan-sgp.models.ts"; + +export function xiaomiTokenPlanSgpProvider(): Provider<"openai-completions"> { + return createProvider({ + id: "xiaomi-token-plan-sgp", + name: "Xiaomi Token Plan SGP", + baseUrl: "https://token-plan-sgp.xiaomimimo.com/v1", + auth: { apiKey: envApiKeyAuth("Xiaomi Token Plan SGP API key", ["XIAOMI_TOKEN_PLAN_SGP_API_KEY"]) }, + models: Object.values(XIAOMI_TOKEN_PLAN_SGP_MODELS), + api: openAICompletionsApi(), + }); +} diff --git a/packages/ai/src/providers/zai.ts b/packages/ai/src/providers/zai.ts new file mode 100644 index 0000000000000000000000000000000000000000..854010661655298b2774c99542c7292abf51b4bd --- /dev/null +++ b/packages/ai/src/providers/zai.ts @@ -0,0 +1,15 @@ +import { openAICompletionsApi } from "../api/openai-completions.lazy.ts"; +import { envApiKeyAuth } from "../auth/helpers.ts"; +import { createProvider, type Provider } from "../models.ts"; +import { ZAI_MODELS } from "./zai.models.ts"; + +export function zaiProvider(): Provider<"openai-completions"> { + return createProvider({ + id: "zai", + name: "Z.AI", + baseUrl: "https://api.z.ai/api/coding/paas/v4", + auth: { apiKey: envApiKeyAuth("Z.AI API key", ["ZAI_API_KEY"]) }, + models: Object.values(ZAI_MODELS), + api: openAICompletionsApi(), + }); +} diff --git a/packages/ai/src/utils/abort-signals.ts b/packages/ai/src/utils/abort-signals.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e1a9ade91c021e8d9b761a2fb8f0ac1316c9daf --- /dev/null +++ b/packages/ai/src/utils/abort-signals.ts @@ -0,0 +1,41 @@ +export interface CombinedAbortSignal { + signal?: AbortSignal; + cleanup: () => void; +} + +export function combineAbortSignals(signals: readonly (AbortSignal | undefined)[]): CombinedAbortSignal { + const activeSignals = signals.filter((signal): signal is AbortSignal => signal !== undefined); + if (activeSignals.length === 0) { + return { cleanup: () => {} }; + } + if (activeSignals.length === 1) { + return { signal: activeSignals[0], cleanup: () => {} }; + } + + const controller = new AbortController(); + const listeners: Array<{ signal: AbortSignal; listener: () => void }> = []; + const abort = (signal: AbortSignal) => { + if (!controller.signal.aborted) { + controller.abort(signal.reason); + } + }; + + for (const signal of activeSignals) { + if (signal.aborted) { + abort(signal); + break; + } + const listener = () => abort(signal); + signal.addEventListener("abort", listener, { once: true }); + listeners.push({ signal, listener }); + } + + return { + signal: controller.signal, + cleanup: () => { + for (const { signal, listener } of listeners) { + signal.removeEventListener("abort", listener); + } + }, + }; +} diff --git a/packages/ai/src/utils/abort.ts b/packages/ai/src/utils/abort.ts new file mode 100644 index 0000000000000000000000000000000000000000..5d76d19f412f82b26f9b856e332aa5637513f690 --- /dev/null +++ b/packages/ai/src/utils/abort.ts @@ -0,0 +1,50 @@ +function abortReason(signal: AbortSignal): unknown { + if (signal.reason !== undefined) return signal.reason; + const error = new Error("The operation was aborted"); + error.name = "AbortError"; + return error; +} + +/** Create an operation-local signal for public APIs whose signal is optional. */ +export function operationSignal(signal?: AbortSignal): AbortSignal { + return signal ?? new AbortController().signal; +} + +/** + * Stop waiting for an operation when its signal aborts while continuing to + * observe the abandoned promise so a later rejection is always handled. + */ +export function raceWithAbortSignal(operation: Promise, signal: AbortSignal): Promise { + if (signal.aborted) { + void operation.catch(() => {}); + return Promise.reject(abortReason(signal)); + } + + return new Promise((resolve, reject) => { + let settled = false; + const cleanup = () => signal.removeEventListener("abort", onAbort); + const onAbort = () => { + if (settled) return; + settled = true; + cleanup(); + reject(abortReason(signal)); + }; + + signal.addEventListener("abort", onAbort, { once: true }); + void operation.then( + (value) => { + if (settled) return; + settled = true; + cleanup(); + resolve(value); + }, + (error: unknown) => { + if (settled) return; + settled = true; + cleanup(); + reject(error); + }, + ); + if (signal.aborted) onAbort(); + }); +} diff --git a/packages/ai/src/utils/assistant-message-frame.ts b/packages/ai/src/utils/assistant-message-frame.ts new file mode 100644 index 0000000000000000000000000000000000000000..65e23ede5994dfc5efd15cc172177c8d402b096d --- /dev/null +++ b/packages/ai/src/utils/assistant-message-frame.ts @@ -0,0 +1,490 @@ +import type { AssistantMessage, AssistantMessageEvent, TextContent, ThinkingContent, ToolCall } from "../types.ts"; +import { parseStreamingJson } from "./json-parse.ts"; + +/** + * Compact, replayable assistant-message progress. Terminal settlement is + * intentionally excluded and must be persisted separately. + */ +export type AssistantMessageFrame = + | { type: "start"; partial: AssistantMessage } + | { type: "text_start"; contentIndex: number; content: TextContent } + | { type: "text_delta"; contentIndex: number; delta: string } + | { type: "text_end"; contentIndex: number; content: string; textSignature?: string } + | { type: "thinking_start"; contentIndex: number; content: ThinkingContent } + | { type: "thinking_delta"; contentIndex: number; delta: string } + | { + type: "thinking_end"; + contentIndex: number; + content: string; + thinkingSignature?: string; + redacted?: boolean; + } + | { type: "toolcall_start"; contentIndex: number; toolCall: ToolCall } + | { type: "toolcall_checkpoint"; contentIndex: number; json: string } + | { type: "toolcall_delta"; contentIndex: number; delta: string } + | { + type: "toolcall_end"; + contentIndex: number; + id: string; + name: string; + arguments: ToolCall["arguments"]; + thoughtSignature?: string; + namespace?: string; + }; + +type EncoderBlockState = + | { kind: "text" | "thinking"; coveredChars: number; deltaChars: number } + | { + kind: "toolCall"; + caughtUp: boolean; + catchupJson: string; + snapshotArguments: string; + }; + +type ReducerBlockState = + | { kind: "text"; ended: boolean } + | { kind: "thinking"; ended: boolean } + | { kind: "toolCall"; ended: boolean; json: string }; + +function cloneTextContent(content: TextContent): TextContent { + return { + type: "text", + text: content.text, + ...(content.textSignature === undefined ? {} : { textSignature: content.textSignature }), + }; +} + +function cloneThinkingContent(content: ThinkingContent): ThinkingContent { + return { + type: "thinking", + thinking: content.thinking, + ...(content.thinkingSignature === undefined ? {} : { thinkingSignature: content.thinkingSignature }), + ...(content.redacted === undefined ? {} : { redacted: content.redacted }), + }; +} + +function cloneToolCall(toolCall: ToolCall): ToolCall { + return { + type: "toolCall", + id: toolCall.id, + name: toolCall.name, + arguments: structuredClone(toolCall.arguments), + ...(toolCall.thoughtSignature === undefined ? {} : { thoughtSignature: toolCall.thoughtSignature }), + ...(toolCall.namespace === undefined ? {} : { namespace: toolCall.namespace }), + }; +} + +function cloneStartMessage(message: AssistantMessage): AssistantMessage { + return { + role: "assistant", + content: [], + api: message.api, + provider: message.provider, + model: message.model, + ...(message.responseModel === undefined ? {} : { responseModel: message.responseModel }), + ...(message.responseId === undefined ? {} : { responseId: message.responseId }), + ...(message.providerThinkingLevel === undefined ? {} : { providerThinkingLevel: message.providerThinkingLevel }), + ...(message.diagnostics === undefined ? {} : { diagnostics: structuredClone(message.diagnostics) }), + usage: structuredClone(message.usage), + stopReason: "pending", + timestamp: message.timestamp, + }; +} + +function assertContentIndex(contentIndex: number): void { + if (!Number.isSafeInteger(contentIndex) || contentIndex < 0) { + throw new Error(`Invalid assistant message frame contentIndex: ${contentIndex}`); + } +} + +function eventBlock(event: Exclude) { + assertContentIndex(event.contentIndex); + const block = event.partial.content[event.contentIndex]; + if (!block) { + throw new Error(`${event.type} event has no content block at index ${event.contentIndex}`); + } + return block; +} + +function serializedArguments(argumentsValue: ToolCall["arguments"]): string { + const serialized = JSON.stringify(argumentsValue); + if (serialized === undefined) throw new Error("Tool-call arguments are not JSON-serializable"); + return serialized; +} + +const EMPTY_PARSED_TOOL_ARGUMENTS = serializedArguments(parseStreamingJson("")); + +function isJsonPrefix(snapshot: unknown, current: unknown): boolean { + if (typeof snapshot === "string") return typeof current === "string" && current.startsWith(snapshot); + if (Array.isArray(snapshot)) { + return ( + Array.isArray(current) && + snapshot.length <= current.length && + snapshot.every((value, index) => isJsonPrefix(value, current[index])) + ); + } + if (typeof snapshot !== "object" || snapshot === null) return Object.is(snapshot, current); + if (typeof current !== "object" || current === null || Array.isArray(current)) return false; + const currentRecord = current as Record; + return Object.entries(snapshot).every( + ([key, value]) => Object.hasOwn(currentRecord, key) && isJsonPrefix(value, currentRecord[key]), + ); +} + +/** + * Encodes one assistant stream. `partial` remains a shared live accumulator; + * the encoder uses per-block offsets to avoid replaying deltas already visible + * when an older queued event is consumed. + */ +export class AssistantMessageFrameEncoder { + private started = false; + private terminal = false; + private readonly blocks = new Map(); + + encode(event: AssistantMessageEvent): AssistantMessageFrame | undefined { + if (this.terminal) throw new Error(`Assistant message event ${event.type} follows a terminal event`); + + switch (event.type) { + case "start": + if (this.started) throw new Error("Assistant message stream contains more than one start event"); + this.started = true; + return { type: "start", partial: cloneStartMessage(event.partial) }; + case "done": + if (!this.started) throw new Error("Assistant message done event appears before start"); + this.terminal = true; + return undefined; + case "error": + this.terminal = true; + return undefined; + } + + if (!this.started) throw new Error(`Assistant message ${event.type} event appears before start`); + + switch (event.type) { + case "text_start": { + const content = eventBlock(event); + if (content.type !== "text") { + throw new Error(`text_start event points to ${content.type} block at index ${event.contentIndex}`); + } + this.startBlock(event.contentIndex, { + kind: "text", + coveredChars: content.text.length, + deltaChars: 0, + }); + return { type: "text_start", contentIndex: event.contentIndex, content: cloneTextContent(content) }; + } + case "text_delta": + return this.encodeTextDelta(event.contentIndex, event.delta, "text"); + case "text_end": { + const content = eventBlock(event); + if (content.type !== "text") { + throw new Error(`text_end event points to ${content.type} block at index ${event.contentIndex}`); + } + this.endBlock(event.contentIndex, "text"); + return { + type: "text_end", + contentIndex: event.contentIndex, + content: event.content, + ...(content.textSignature === undefined ? {} : { textSignature: content.textSignature }), + }; + } + case "thinking_start": { + const content = eventBlock(event); + if (content.type !== "thinking") { + throw new Error(`thinking_start event points to ${content.type} block at index ${event.contentIndex}`); + } + this.startBlock(event.contentIndex, { + kind: "thinking", + coveredChars: content.thinking.length, + deltaChars: 0, + }); + return { + type: "thinking_start", + contentIndex: event.contentIndex, + content: cloneThinkingContent(content), + }; + } + case "thinking_delta": + return this.encodeTextDelta(event.contentIndex, event.delta, "thinking"); + case "thinking_end": { + const content = eventBlock(event); + if (content.type !== "thinking") { + throw new Error(`thinking_end event points to ${content.type} block at index ${event.contentIndex}`); + } + this.endBlock(event.contentIndex, "thinking"); + return { + type: "thinking_end", + contentIndex: event.contentIndex, + content: event.content, + ...(content.thinkingSignature === undefined ? {} : { thinkingSignature: content.thinkingSignature }), + ...(content.redacted === undefined ? {} : { redacted: content.redacted }), + }; + } + case "toolcall_start": { + const content = eventBlock(event); + if (content.type !== "toolCall") { + throw new Error(`toolcall_start event points to ${content.type} block at index ${event.contentIndex}`); + } + const snapshotArguments = serializedArguments(content.arguments); + const caughtUp = snapshotArguments === EMPTY_PARSED_TOOL_ARGUMENTS; + this.startBlock(event.contentIndex, { + kind: "toolCall", + caughtUp, + catchupJson: "", + snapshotArguments: caughtUp ? "" : snapshotArguments, + }); + return { type: "toolcall_start", contentIndex: event.contentIndex, toolCall: cloneToolCall(content) }; + } + case "toolcall_delta": { + const state = this.block(event.contentIndex, "toolCall"); + if (state.kind !== "toolCall") throw new Error("Unreachable tool-call encoder state"); + if (state.caughtUp) { + return event.delta.length === 0 + ? undefined + : { type: "toolcall_delta", contentIndex: event.contentIndex, delta: event.delta }; + } + state.catchupJson += event.delta; + const argumentsValue = parseStreamingJson(state.catchupJson); + if (serializedArguments(argumentsValue) !== state.snapshotArguments) { + // Legacy grammar calls include the initial input in toolcall_start, but their + // JSON delta stream still begins at an empty input. Its parsed arguments can + // therefore extend, rather than exactly reproduce, the start snapshot. + const snapshotArguments = parseStreamingJson(state.snapshotArguments); + if (!isJsonPrefix(snapshotArguments, argumentsValue)) return undefined; + } + state.caughtUp = true; + state.snapshotArguments = ""; + const json = state.catchupJson; + state.catchupJson = ""; + return json.length === 0 + ? undefined + : { type: "toolcall_checkpoint", contentIndex: event.contentIndex, json }; + } + case "toolcall_end": { + const content = eventBlock(event); + if (content.type !== "toolCall") { + throw new Error(`toolcall_end event points to ${content.type} block at index ${event.contentIndex}`); + } + if (event.toolCall.type !== "toolCall") { + throw new Error(`toolcall_end event has invalid tool call at index ${event.contentIndex}`); + } + this.endBlock(event.contentIndex, "toolCall"); + return { + type: "toolcall_end", + contentIndex: event.contentIndex, + id: event.toolCall.id, + name: event.toolCall.name, + arguments: structuredClone(event.toolCall.arguments), + ...(event.toolCall.thoughtSignature === undefined + ? {} + : { thoughtSignature: event.toolCall.thoughtSignature }), + ...(event.toolCall.namespace === undefined ? {} : { namespace: event.toolCall.namespace }), + }; + } + } + } + + private startBlock(contentIndex: number, state: EncoderBlockState): void { + assertContentIndex(contentIndex); + if (this.blocks.has(contentIndex)) { + throw new Error(`Assistant message block ${contentIndex} starts more than once`); + } + this.blocks.set(contentIndex, state); + } + + private block(contentIndex: number, kind: EncoderBlockState["kind"]): EncoderBlockState { + assertContentIndex(contentIndex); + const state = this.blocks.get(contentIndex); + if (state === undefined) throw new Error(`Assistant message ${kind} block ${contentIndex} has not started`); + if (state.kind !== kind) { + throw new Error(`Assistant message block ${contentIndex} is ${state.kind}, not ${kind}`); + } + return state; + } + + private endBlock(contentIndex: number, kind: EncoderBlockState["kind"]): void { + this.block(contentIndex, kind); + this.blocks.delete(contentIndex); + } + + private encodeTextDelta( + contentIndex: number, + delta: string, + kind: "text" | "thinking", + ): AssistantMessageFrame | undefined { + const state = this.block(contentIndex, kind); + if (state.kind === "toolCall") throw new Error("Unreachable text encoder state"); + const deltaStart = state.deltaChars; + state.deltaChars += delta.length; + const covered = Math.max(0, state.coveredChars - deltaStart); + if (covered >= delta.length) return undefined; + const uncovered = covered === 0 ? delta : delta.slice(covered); + return kind === "text" + ? { type: "text_delta", contentIndex, delta: uncovered } + : { type: "thinking_delta", contentIndex, delta: uncovered }; + } +} + +function appendBlock( + message: AssistantMessage, + states: Map, + contentIndex: number, + block: TextContent | ThinkingContent | ToolCall, + state: ReducerBlockState, +): void { + assertContentIndex(contentIndex); + if (contentIndex !== message.content.length) { + const reason = contentIndex < message.content.length ? "already exists" : "would leave a gap"; + throw new Error(`Cannot start assistant message block at index ${contentIndex}: ${reason}`); + } + message.content.push(structuredClone(block)); + states.set(contentIndex, state); +} + +function activeBlock( + message: AssistantMessage, + states: Map, + contentIndex: number, + expectedKind: ReducerBlockState["kind"], + frameType: AssistantMessageFrame["type"], +): { block: TextContent | ThinkingContent | ToolCall; state: ReducerBlockState } { + assertContentIndex(contentIndex); + const state = states.get(contentIndex); + const block = message.content[contentIndex]; + if (!state || !block) { + throw new Error(`${frameType} frame has no started block at index ${contentIndex}`); + } + if (state.kind !== expectedKind || block.type !== expectedKind) { + throw new Error( + `${frameType} frame expected ${expectedKind} block at index ${contentIndex}, found ${block.type}`, + ); + } + if (state.ended) { + throw new Error(`${frameType} frame follows the end of block at index ${contentIndex}`); + } + return { block, state }; +} + +/** + * Replay compact frames without mutating them. Returns `undefined` when the + * iterable contains no start frame. + */ +export function reduceAssistantMessageFrames(frames: Iterable): AssistantMessage | undefined { + let message: AssistantMessage | undefined; + let frameBeforeStart: AssistantMessageFrame["type"] | undefined; + const states = new Map(); + + for (const frame of frames) { + if (frame.type === "start") { + if (message) throw new Error("Assistant message frame sequence contains more than one start frame"); + if (frameBeforeStart !== undefined) + throw new Error(`${frameBeforeStart} frame appears before the start frame`); + message = structuredClone(frame.partial); + continue; + } + if (!message) { + frameBeforeStart ??= frame.type; + continue; + } + + switch (frame.type) { + case "text_start": + if (frame.content.type !== "text") { + throw new Error(`text_start frame contains ${frame.content.type} content`); + } + appendBlock(message, states, frame.contentIndex, frame.content, { kind: "text", ended: false }); + break; + case "text_delta": { + const { block } = activeBlock(message, states, frame.contentIndex, "text", frame.type); + if (block.type !== "text") throw new Error("Unreachable text frame state"); + block.text += frame.delta; + break; + } + case "text_end": { + const { block, state } = activeBlock(message, states, frame.contentIndex, "text", frame.type); + if (block.type !== "text") throw new Error("Unreachable text frame state"); + block.text = frame.content; + delete block.textSignature; + if (frame.textSignature !== undefined) block.textSignature = frame.textSignature; + state.ended = true; + break; + } + case "thinking_start": + if (frame.content.type !== "thinking") { + throw new Error(`thinking_start frame contains ${frame.content.type} content`); + } + appendBlock(message, states, frame.contentIndex, frame.content, { + kind: "thinking", + ended: false, + }); + break; + case "thinking_delta": { + const { block } = activeBlock(message, states, frame.contentIndex, "thinking", frame.type); + if (block.type !== "thinking") throw new Error("Unreachable thinking frame state"); + block.thinking += frame.delta; + break; + } + case "thinking_end": { + const { block, state } = activeBlock(message, states, frame.contentIndex, "thinking", frame.type); + if (block.type !== "thinking") throw new Error("Unreachable thinking frame state"); + block.thinking = frame.content; + delete block.thinkingSignature; + delete block.redacted; + if (frame.thinkingSignature !== undefined) block.thinkingSignature = frame.thinkingSignature; + if (frame.redacted !== undefined) block.redacted = frame.redacted; + state.ended = true; + break; + } + case "toolcall_start": + if (frame.toolCall.type !== "toolCall") { + throw new Error(`toolcall_start frame contains ${frame.toolCall.type} content`); + } + appendBlock(message, states, frame.contentIndex, frame.toolCall, { + kind: "toolCall", + ended: false, + json: "", + }); + break; + case "toolcall_checkpoint": { + const { block, state } = activeBlock(message, states, frame.contentIndex, "toolCall", frame.type); + if (block.type !== "toolCall" || state.kind !== "toolCall") { + throw new Error("Unreachable tool-call checkpoint state"); + } + state.json = frame.json; + block.arguments = parseStreamingJson(frame.json); + break; + } + case "toolcall_delta": { + const { block, state } = activeBlock(message, states, frame.contentIndex, "toolCall", frame.type); + if (block.type !== "toolCall" || state.kind !== "toolCall") { + throw new Error("Unreachable tool-call frame state"); + } + state.json += frame.delta; + break; + } + case "toolcall_end": { + const { block, state } = activeBlock(message, states, frame.contentIndex, "toolCall", frame.type); + if (block.type !== "toolCall") throw new Error("Unreachable tool-call frame state"); + block.id = frame.id; + block.name = frame.name; + block.arguments = structuredClone(frame.arguments); + delete block.thoughtSignature; + delete block.namespace; + if (frame.thoughtSignature !== undefined) block.thoughtSignature = frame.thoughtSignature; + if (frame.namespace !== undefined) block.namespace = frame.namespace; + state.ended = true; + break; + } + } + } + + if (!message) return undefined; + for (const [contentIndex, state] of states) { + if (state.kind !== "toolCall" || state.ended || state.json.length === 0) continue; + const block = message.content[contentIndex]; + if (block?.type !== "toolCall") throw new Error("Unreachable tool-call frame state"); + block.arguments = parseStreamingJson(state.json); + } + + return message; +} diff --git a/packages/ai/src/utils/deferred-tools.ts b/packages/ai/src/utils/deferred-tools.ts new file mode 100644 index 0000000000000000000000000000000000000000..edcf520467f2511c898e4e192dcae656762daf27 --- /dev/null +++ b/packages/ai/src/utils/deferred-tools.ts @@ -0,0 +1,39 @@ +import type { Context, Tool } from "../types.ts"; + +type ToolNameNormalizer = (name: string) => string; + +const identityToolName: ToolNameNormalizer = (name) => name; + +/** Split current tools into prefix and transcript-loaded definitions. */ +export function splitDeferredTools( + context: Context, + enabled: boolean, + normalizeName: ToolNameNormalizer = identityToolName, +): { immediate: Tool[]; deferred: Map } { + const uniqueTools = new Map(); + for (const tool of context.tools ?? []) uniqueTools.set(normalizeName(tool.name), tool); + if (!enabled) return { immediate: [...uniqueTools.values()], deferred: new Map() }; + + const deferredNames = new Set(); + const usedNames = new Set(); + for (const message of context.messages) { + if (message.role === "assistant") { + for (const block of message.content) { + if (block.type === "toolCall") usedNames.add(normalizeName(block.name)); + } + } else if (message.role === "toolResult") { + for (const name of message.addedToolNames ?? []) { + const normalizedName = normalizeName(name); + if (!usedNames.has(normalizedName)) deferredNames.add(normalizedName); + } + } + } + + const immediate: Tool[] = []; + const deferred = new Map(); + for (const [name, tool] of uniqueTools) { + if (deferredNames.has(name)) deferred.set(name, tool); + else immediate.push(tool); + } + return { immediate, deferred }; +} diff --git a/packages/ai/src/utils/diagnostics.ts b/packages/ai/src/utils/diagnostics.ts new file mode 100644 index 0000000000000000000000000000000000000000..89d135619cf66203cff337546874ad33d355ecb1 --- /dev/null +++ b/packages/ai/src/utils/diagnostics.ts @@ -0,0 +1,45 @@ +export interface DiagnosticErrorInfo { + name?: string; + message: string; + stack?: string; + code?: string | number; +} + +export interface AssistantMessageDiagnostic { + type: string; + timestamp: number; + error?: DiagnosticErrorInfo; + details?: Record; +} + +export function formatThrownValue(value: unknown): string { + if (value instanceof Error) return value.message || value.name; + if (typeof value === "string") return value; + return String(value); +} + +export function extractDiagnosticError(error: unknown): DiagnosticErrorInfo { + if (!(error instanceof Error)) return { name: "ThrownValue", message: formatThrownValue(error) }; + const code = (error as Error & { code?: unknown }).code; + return { + name: error.name || undefined, + message: error.message || error.name, + stack: error.stack, + code: typeof code === "string" || typeof code === "number" ? code : undefined, + }; +} + +export function createAssistantMessageDiagnostic( + type: string, + error: unknown, + details?: Record, +): AssistantMessageDiagnostic { + return { type, timestamp: Date.now(), error: extractDiagnosticError(error), details }; +} + +export function appendAssistantMessageDiagnostic( + message: T, + diagnostic: AssistantMessageDiagnostic, +): void { + message.diagnostics = [...(message.diagnostics ?? []), diagnostic]; +} diff --git a/packages/ai/src/utils/error-body.ts b/packages/ai/src/utils/error-body.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb8c1859a7dc33474e56e371ec05a1bf89fabf73 --- /dev/null +++ b/packages/ai/src/utils/error-body.ts @@ -0,0 +1,149 @@ +// Shared normalization for provider HTTP error objects. +// +// Endpoints behind a proxy / gateway may return a non-2xx response whose body +// the provider SDK cannot fold into `error.message`. The SDK error object still +// carries the HTTP status and the raw/parsed body, but under SDK-specific field +// names. Provider catch blocks that read only `error.message` therefore drop +// the body and surface opaque messages like `"403 status code (no body)"` or +// collapse to `"Unknown: UnknownError"`. +// +// `normalizeProviderError` probes the known SDK field shapes (Mistral, +// `openai`, `@google/genai`, AWS Bedrock) and returns a struct each provider +// composes into its display string. The `messageCarriesBody` flag captures the +// Anthropic / `@google/genai` happy path where the SDK already folded the body +// into the message, so providers can preserve it without double-printing. + +export const MAX_PROVIDER_ERROR_BODY_CHARS = 4000; + +export interface NormalizedProviderError { + /** HTTP status code, when one could be extracted from the SDK error object. */ + status?: number; + /** Raw HTTP body reason, already trimmed and truncated to the cap. */ + body?: string; + /** `error.message`, or `safeJsonStringify(error)` for a non-`Error` throw. */ + message: string; + /** True when `message` already contains the body (no separate body to add). */ + messageCarriesBody: boolean; +} + +type SdkErrorShape = Error & { + statusCode?: unknown; + status?: unknown; + body?: unknown; + error?: unknown; + $metadata?: { httpStatusCode?: unknown }; + $response?: { statusCode?: unknown; body?: unknown }; +}; + +export function normalizeProviderError(error: unknown): NormalizedProviderError { + if (!(error instanceof Error)) { + return { message: safeJsonStringify(error), messageCarriesBody: false }; + } + + const sdkError = error as SdkErrorShape; + const status = extractStatus(sdkError); + const body = extractBody(sdkError); + const messageCarriesBody = body === undefined || error.message.includes(body); + + return { + status, + body, + message: error.message, + messageCarriesBody, + } satisfies NormalizedProviderError; +} + +/** + * Probe the HTTP status, first numeric hit wins, in SDK-field order: + * `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) → + * `$metadata.httpStatusCode` (Bedrock) → `$response.statusCode` (Bedrock). + */ +function extractStatus(error: SdkErrorShape): number | undefined { + if (typeof error.statusCode === "number") return error.statusCode; + if (typeof error.status === "number") return error.status; + if (typeof error.$metadata?.httpStatusCode === "number") return error.$metadata.httpStatusCode; + if (typeof error.$response?.statusCode === "number") return error.$response.statusCode; + return undefined; +} + +/** + * Probe the raw body reason, first usable hit wins, in SDK-field order: + * `body` string (Mistral) → `error` parsed JSON body object (`openai` SDK's + * `this.error`) → `$response.body` (Bedrock). Empty objects and unread response + * streams are treated as no body so they do not surface as `"{}"` or serialized + * stream internals. The chosen body is truncated to the cap. + */ +function extractBody(error: SdkErrorShape): string | undefined { + const bodyText = pickBodyText(error); + if (bodyText === undefined) return undefined; + const trimmed = bodyText.trim(); + if (trimmed.length === 0) return undefined; + return truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS); +} + +function pickBodyText(error: SdkErrorShape): string | undefined { + if (typeof error.body === "string") return error.body; + if (isPlainNonEmptyObject(error.error)) return safeJsonStringify(error.error); + const responseBody = error.$response?.body; + if (typeof responseBody === "string") return responseBody; + if (isReadableStreamLike(responseBody)) return undefined; + if (isPlainNonEmptyObject(responseBody)) return safeJsonStringify(responseBody); + return undefined; +} + +function isReadableStreamLike(value: unknown): boolean { + return typeof value === "object" && value !== null && "pipe" in value && typeof value.pipe === "function"; +} + +/** + * Only a PLAIN object counts as an HTTP body. SDK error fields can hold class + * instances instead of parsed bodies — AWS SDK v3's `$response.body` is an + * HTTP stream/response wrapper object, and stringifying one produced garbage + * like `{"_events":...}` as the "body", which then REPLACED `error.message` + * in the composed display string. `error.message` is where the SDK puts the + * real deserialized exception text ("Input is too long...", schema validation + * details, ...), so the one useful string was discarded for noise. A class + * instance yields no body, `messageCarriesBody` stays true, and the real + * message survives. Complements the `pipe` sniffing above: web + * ReadableStreams (pipeTo/pipeThrough, no `pipe`) and non-stream SDK wrapper + * classes fail the prototype check, while parsed JSON bodies (plain objects + * by construction) still pass. + */ +function isPlainNonEmptyObject(value: unknown): boolean { + if (typeof value !== "object" || value === null) return false; + const proto = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) return false; + return Object.keys(value).length > 0; +} + +/** + * Compose a display string from a normalized error. When the message already + * carries the body (Anthropic / `@google/genai` happy path) or no body/status + * was extracted, the message is returned unchanged. Otherwise the status and + * body are surfaced, with an optional provider prefix. + * + * - no prefix: `": "` + * - prefix: `" (): "` + */ +export function formatProviderError(norm: NormalizedProviderError, prefix?: string): string { + if (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) { + return prefix !== undefined && norm.status !== undefined + ? `${prefix} (${norm.status}): ${norm.message}` + : norm.message; + } + return prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`; +} + +export function truncateErrorText(text: string, maxChars: number): string { + if (text.length <= maxChars) return text; + return `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`; +} + +export function safeJsonStringify(value: unknown): string { + try { + const serialized = JSON.stringify(value); + return serialized === undefined ? String(value) : serialized; + } catch { + return String(value); + } +} diff --git a/packages/ai/src/utils/estimate.ts b/packages/ai/src/utils/estimate.ts new file mode 100644 index 0000000000000000000000000000000000000000..b434969ecc1e9cb767b558cd09d9b485d6400d2f --- /dev/null +++ b/packages/ai/src/utils/estimate.ts @@ -0,0 +1,143 @@ +import type { AssistantMessage, Context, ImageContent, Message, TextContent, Tool, Usage } from "../types.ts"; + +export interface ContextUsageEstimate { + /** Estimated total context tokens. */ + tokens: number; + /** Tokens reported by the most recent applicable assistant usage block. */ + usageTokens: number; + /** Estimated tokens after the most recent applicable assistant usage block. */ + trailingTokens: number; + /** Index of the applicable message that provided usage, or null when none exists. */ + lastUsageIndex: number | null; +} + +const CHARS_PER_TOKEN = 4; +const ESTIMATED_IMAGE_CHARS = 4800; + +export function calculateContextTokens(usage: Usage): number { + return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite; +} + +function safeJsonStringify(value: unknown): string { + try { + return JSON.stringify(value) ?? "undefined"; + } catch { + return "[unserializable]"; + } +} + +function estimateTextAndImageContentChars(content: string | Array): number { + if (typeof content === "string") return content.length; + + let chars = 0; + for (const block of content) chars += block.type === "text" ? block.text.length : ESTIMATED_IMAGE_CHARS; + return chars; +} + +export function estimateTextTokens(text: string): number { + return Math.ceil(text.length / CHARS_PER_TOKEN); +} + +export function estimateTextAndImageContentTokens(content: string | Array): number { + return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN); +} + +export function estimateMessageTokens(message: Message): number { + let chars = 0; + + if (message.role === "user") return estimateTextAndImageContentTokens(message.content); + if (message.role === "toolResult") return estimateTextAndImageContentTokens(message.content); + + for (const block of message.content) { + if (block.type === "text") { + chars += block.text.length; + } else if (block.type === "thinking") { + chars += block.thinking.length; + } else { + chars += block.name.length + safeJsonStringify(block.arguments).length; + } + } + return Math.ceil(chars / CHARS_PER_TOKEN); +} + +function getLastAssistantUsageInfo(messages: readonly Message[]): { usage: Usage; index: number } | undefined { + let latestPrefixTimestamp = Number.NEGATIVE_INFINITY; + let usageInfo: { usage: Usage; index: number } | undefined; + + for (let i = 0; i < messages.length; i++) { + const message = messages[i]; + if (message.role === "assistant") { + const assistant = message as AssistantMessage; + // A newer prefix message was inserted after this response (for example, a + // compaction summary), so its usage cannot describe the current prefix. + const usageAppliesToPrefix = assistant.timestamp >= latestPrefixTimestamp; + if ( + usageAppliesToPrefix && + assistant.stopReason !== "aborted" && + assistant.stopReason !== "error" && + calculateContextTokens(assistant.usage) > 0 + ) { + usageInfo = { usage: assistant.usage, index: i }; + } + } + latestPrefixTimestamp = Math.max(latestPrefixTimestamp, message.timestamp); + } + + return usageInfo; +} + +function estimateMessages(messages: readonly Message[]): ContextUsageEstimate { + const usageInfo = getLastAssistantUsageInfo(messages); + if (usageInfo) { + const usageTokens = calculateContextTokens(usageInfo.usage); + let trailingTokens = 0; + for (let i = usageInfo.index + 1; i < messages.length; i++) { + trailingTokens += estimateMessageTokens(messages[i]); + } + return { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usageInfo.index }; + } + + let tokens = 0; + for (const message of messages) tokens += estimateMessageTokens(message); + return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null }; +} + +function estimateToolsTokens(tools: readonly Tool[] | undefined): number { + if (!tools || tools.length === 0) return 0; + return estimateTextTokens(safeJsonStringify(tools)); +} + +function isMessageArray(value: Context | readonly Message[]): value is readonly Message[] { + return Array.isArray(value); +} + +export function estimateContextTokens(context: Context | readonly Message[]): ContextUsageEstimate { + if (isMessageArray(context)) return estimateMessages(context); + + const estimate = estimateMessages(context.messages); + if (estimate.lastUsageIndex !== null) { + const addedNames = new Set( + context.messages + .slice(estimate.lastUsageIndex + 1) + .filter((message) => message.role === "toolResult") + .flatMap((message) => message.addedToolNames ?? []), + ); + const addedToolTokens = estimateToolsTokens(context.tools?.filter((tool) => addedNames.has(tool.name))); + return { + tokens: estimate.tokens + addedToolTokens, + usageTokens: estimate.usageTokens, + trailingTokens: estimate.trailingTokens + addedToolTokens, + lastUsageIndex: estimate.lastUsageIndex, + }; + } + + const prefixTokens = + (context.systemPrompt ? estimateTextTokens(context.systemPrompt) : 0) + estimateToolsTokens(context.tools); + + return { + tokens: estimate.tokens + prefixTokens, + usageTokens: estimate.usageTokens, + trailingTokens: estimate.trailingTokens + prefixTokens, + lastUsageIndex: estimate.lastUsageIndex, + }; +} diff --git a/packages/ai/src/utils/event-stream.ts b/packages/ai/src/utils/event-stream.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4f731d59bf192d6889d9b25ba3f3dd2b1b5a9e6 --- /dev/null +++ b/packages/ai/src/utils/event-stream.ts @@ -0,0 +1,110 @@ +import type { AssistantMessage, AssistantMessageEvent } from "../types.ts"; + +class FifoQueue { + private incoming: T[] = []; + private outgoing: T[] = []; + + get length(): number { + return this.incoming.length + this.outgoing.length; + } + + enqueue(value: T): void { + this.incoming.push(value); + } + + dequeue(): T | undefined { + if (this.outgoing.length === 0) { + while (this.incoming.length > 0) { + this.outgoing.push(this.incoming.pop()!); + } + } + return this.outgoing.pop(); + } +} + +// Generic event stream class for async iteration +export class EventStream implements AsyncIterable { + private queue = new FifoQueue(); + private waiting = new FifoQueue<(value: IteratorResult) => void>(); + private done = false; + private finalResultPromise: Promise; + private resolveFinalResult!: (result: R) => void; + private isComplete: (event: T) => boolean; + private extractResult: (event: T) => R; + + constructor(isComplete: (event: T) => boolean, extractResult: (event: T) => R) { + this.isComplete = isComplete; + this.extractResult = extractResult; + this.finalResultPromise = new Promise((resolve) => { + this.resolveFinalResult = resolve; + }); + } + + push(event: T): void { + if (this.done) return; + + if (this.isComplete(event)) { + this.done = true; + this.resolveFinalResult(this.extractResult(event)); + } + + // Deliver to waiting consumer or queue it + const waiter = this.waiting.dequeue(); + if (waiter) { + waiter({ value: event, done: false }); + } else { + this.queue.enqueue(event); + } + } + + end(result?: R): void { + this.done = true; + if (result !== undefined) { + this.resolveFinalResult(result); + } + // Notify all waiting consumers that we're done + while (this.waiting.length > 0) { + const waiter = this.waiting.dequeue()!; + waiter({ value: undefined as any, done: true }); + } + } + + async *[Symbol.asyncIterator](): AsyncIterator { + while (true) { + if (this.queue.length > 0) { + yield this.queue.dequeue()!; + } else if (this.done) { + return; + } else { + const result = await new Promise>((resolve) => this.waiting.enqueue(resolve)); + if (result.done) return; + yield result.value; + } + } + } + + result(): Promise { + return this.finalResultPromise; + } +} + +export class AssistantMessageEventStream extends EventStream { + constructor() { + super( + (event) => event.type === "done" || event.type === "error", + (event) => { + if (event.type === "done") { + return event.message; + } else if (event.type === "error") { + return event.error; + } + throw new Error("Unexpected event type for final result"); + }, + ); + } +} + +/** Factory function for AssistantMessageEventStream (for use in extensions) */ +export function createAssistantMessageEventStream(): AssistantMessageEventStream { + return new AssistantMessageEventStream(); +} diff --git a/packages/ai/src/utils/hash.ts b/packages/ai/src/utils/hash.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ff55e8b41647ead2e6a580bedf36b03fd72a8d3 --- /dev/null +++ b/packages/ai/src/utils/hash.ts @@ -0,0 +1,13 @@ +/** Fast deterministic hash to shorten long strings */ +export function shortHash(str: string): string { + let h1 = 0xdeadbeef; + let h2 = 0x41c6ce57; + for (let i = 0; i < str.length; i++) { + const ch = str.charCodeAt(i); + h1 = Math.imul(h1 ^ ch, 2654435761); + h2 = Math.imul(h2 ^ ch, 1597334677); + } + h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909); + h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909); + return (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36); +} diff --git a/packages/ai/src/utils/headers.ts b/packages/ai/src/utils/headers.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d923d287014873ac7c50982d5c1d5edad30b083 --- /dev/null +++ b/packages/ai/src/utils/headers.ts @@ -0,0 +1,18 @@ +import type { ProviderHeaders } from "../types.ts"; + +export function headersToRecord(headers: Headers): Record { + const result: Record = {}; + for (const [key, value] of headers.entries()) { + result[key] = value; + } + return result; +} + +export function providerHeadersToRecord(headers: ProviderHeaders | undefined): Record | undefined { + if (!headers) return undefined; + const result: Record = {}; + for (const [key, value] of Object.entries(headers)) { + if (value !== null) result[key] = value; + } + return Object.keys(result).length > 0 ? result : undefined; +} diff --git a/packages/ai/src/utils/json-parse.ts b/packages/ai/src/utils/json-parse.ts new file mode 100644 index 0000000000000000000000000000000000000000..f39f9f09d6d6a5f6e42c09dcc474ed180bbc0634 --- /dev/null +++ b/packages/ai/src/utils/json-parse.ts @@ -0,0 +1,124 @@ +import { parse as partialParse } from "partial-json"; + +const VALID_JSON_ESCAPES = new Set(['"', "\\", "/", "b", "f", "n", "r", "t", "u"]); + +function isControlCharacter(char: string): boolean { + const codePoint = char.codePointAt(0); + return codePoint !== undefined && codePoint >= 0x00 && codePoint <= 0x1f; +} + +function escapeControlCharacter(char: string): string { + switch (char) { + case "\b": + return "\\b"; + case "\f": + return "\\f"; + case "\n": + return "\\n"; + case "\r": + return "\\r"; + case "\t": + return "\\t"; + default: + return `\\u${char.codePointAt(0)?.toString(16).padStart(4, "0") ?? "0000"}`; + } +} + +/** + * Repairs malformed JSON string literals by: + * - escaping raw control characters inside strings + * - doubling backslashes before invalid escape characters + */ +export function repairJson(json: string): string { + let repaired = ""; + let inString = false; + + for (let index = 0; index < json.length; index++) { + const char = json[index]; + + if (!inString) { + repaired += char; + if (char === '"') { + inString = true; + } + continue; + } + + if (char === '"') { + repaired += char; + inString = false; + continue; + } + + if (char === "\\") { + const nextChar = json[index + 1]; + if (nextChar === undefined) { + repaired += "\\\\"; + continue; + } + + if (nextChar === "u") { + const unicodeDigits = json.slice(index + 2, index + 6); + if (/^[0-9a-fA-F]{4}$/.test(unicodeDigits)) { + repaired += `\\u${unicodeDigits}`; + index += 5; + continue; + } + } + + if (VALID_JSON_ESCAPES.has(nextChar)) { + repaired += `\\${nextChar}`; + index += 1; + continue; + } + + repaired += "\\\\"; + continue; + } + + repaired += isControlCharacter(char) ? escapeControlCharacter(char) : char; + } + + return repaired; +} + +export function parseJsonWithRepair(json: string): T { + try { + return JSON.parse(json) as T; + } catch (error) { + const repairedJson = repairJson(json); + if (repairedJson !== json) { + return JSON.parse(repairedJson) as T; + } + throw error; + } +} + +/** + * Attempts to parse potentially incomplete JSON during streaming. + * Always returns a valid object, even if the JSON is incomplete. + * + * @param partialJson The partial JSON string from streaming + * @returns Parsed object or empty object if parsing fails + */ +export function parseStreamingJson>(partialJson: string | undefined): T { + if (!partialJson || partialJson.trim() === "") { + return {} as T; + } + + try { + return parseJsonWithRepair(partialJson); + } catch { + try { + const result = partialParse(partialJson); + return (result ?? {}) as T; + } catch { + try { + const result = partialParse(repairJson(partialJson)); + return (result ?? {}) as T; + } catch { + return {} as T; + } + } + } +} diff --git a/packages/ai/src/utils/node-http-proxy.ts b/packages/ai/src/utils/node-http-proxy.ts new file mode 100644 index 0000000000000000000000000000000000000000..0550f2659435b58c933593f732f1817531e32f41 --- /dev/null +++ b/packages/ai/src/utils/node-http-proxy.ts @@ -0,0 +1,161 @@ +import type { ProviderEnv } from "../types.ts"; +import { getProviderEnvValue } from "./provider-env.ts"; + +const DEFAULT_PROXY_PORTS: Record = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443, +}; + +function getProxyEnv(key: string, env?: ProviderEnv): string { + const lowercaseKey = key.toLowerCase(); + const uppercaseKey = key.toUpperCase(); + return ( + env?.[lowercaseKey] || + env?.[uppercaseKey] || + getProviderEnvValue(lowercaseKey) || + getProviderEnvValue(uppercaseKey) || + "" + ); +} + +function parseProxyTargetUrl(targetUrl: string | URL): URL | undefined { + if (targetUrl instanceof URL) { + return targetUrl; + } + + try { + return new URL(targetUrl); + } catch { + return undefined; + } +} + +function stripBrackets(host: string): string { + return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host; +} + +function parseNoProxyEntry(entry: string): { host: string; port: number } | undefined { + const trimmed = entry.trim().toLowerCase(); + if (!trimmed) return undefined; + + if (trimmed.startsWith("[")) { + const closingBracket = trimmed.indexOf("]"); + if (closingBracket !== -1) { + const host = trimmed.slice(1, closingBracket); + const rest = trimmed.slice(closingBracket + 1); + if (rest.startsWith(":")) { + const port = Number.parseInt(rest.slice(1), 10); + return { host, port: Number.isNaN(port) ? 0 : port }; + } + return { host, port: 0 }; + } + } + + if (trimmed.includes(":") && trimmed.split(":").length > 2) { + return { host: trimmed, port: 0 }; + } + + const colonIndex = trimmed.lastIndexOf(":"); + if (colonIndex !== -1 && colonIndex === trimmed.indexOf(":")) { + const host = trimmed.slice(0, colonIndex); + const port = Number.parseInt(trimmed.slice(colonIndex + 1), 10); + if (!Number.isNaN(port)) { + return { host, port }; + } + } + + return { host: trimmed, port: 0 }; +} + +function shouldProxyHostname(hostname: string, port: number, env?: ProviderEnv): boolean { + const noProxy = getProxyEnv("no_proxy", env).toLowerCase(); + if (!noProxy) { + return true; + } + if (noProxy === "*") { + return false; + } + + const normalizedTargetHost = stripBrackets(hostname.toLowerCase()); + + return noProxy.split(/[,\s]/).every((entry) => { + const parsed = parseNoProxyEntry(entry); + if (!parsed) { + return true; + } + + if (parsed.port && parsed.port !== port) { + return true; + } + + let domain = stripBrackets(parsed.host); + if (domain.startsWith("*.")) { + domain = domain.slice(2); + } else if (domain.startsWith(".") || domain.startsWith("*")) { + domain = domain.slice(1); + } + + if (!domain) { + return true; + } + + if (normalizedTargetHost === domain) { + return false; + } + + if (normalizedTargetHost.endsWith(`.${domain}`)) { + return false; + } + + return true; + }); +} + +function getProxyForUrl(targetUrl: string | URL, env?: ProviderEnv): string { + const parsedUrl = parseProxyTargetUrl(targetUrl); + if (!parsedUrl?.protocol || !parsedUrl.host) { + return ""; + } + + const protocol = parsedUrl.protocol.split(":", 1)[0]!; + const hostname = stripBrackets(parsedUrl.hostname || parsedUrl.host.replace(/:\d*$/, "")); + const port = Number.parseInt(parsedUrl.port, 10) || DEFAULT_PROXY_PORTS[protocol] || 0; + if (!shouldProxyHostname(hostname, port, env)) { + return ""; + } + + let proxy = getProxyEnv(`${protocol}_proxy`, env) || getProxyEnv("all_proxy", env); + if (proxy && !proxy.includes("://")) { + proxy = `${protocol}://${proxy}`; + } + return proxy; +} + +export const UNSUPPORTED_PROXY_PROTOCOL_MESSAGE = + "Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL."; + +export function resolveHttpProxyUrlForTarget(targetUrl: string | URL, env?: ProviderEnv): URL | undefined { + const proxy = getProxyForUrl(targetUrl, env); + if (!proxy) { + return undefined; + } + + let proxyUrl: URL; + try { + proxyUrl = new URL(proxy); + } catch (error) { + throw new Error( + `Invalid proxy URL ${JSON.stringify(proxy)}: ${error instanceof Error ? error.message : String(error)}`, + ); + } + + if (proxyUrl.protocol !== "http:" && proxyUrl.protocol !== "https:") { + throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`); + } + + return proxyUrl; +} diff --git a/packages/ai/src/utils/overflow.ts b/packages/ai/src/utils/overflow.ts new file mode 100644 index 0000000000000000000000000000000000000000..c1e6457ffc1320c85bf31d6e7ab5d3800a6a4ada --- /dev/null +++ b/packages/ai/src/utils/overflow.ts @@ -0,0 +1,180 @@ +import type { AssistantMessage } from "../types.ts"; + +/** + * Regex patterns to detect context overflow errors from different providers. + * + * These patterns match error messages returned when the input exceeds + * the model's context window. + * + * Provider-specific patterns (with example error messages): + * + * - Anthropic: "prompt is too long: 213462 tokens > 200000 maximum" + * - Anthropic: "413 {\"error\":{\"type\":\"request_too_large\",\"message\":\"Request exceeds the maximum size\"}}" + * - OpenAI: "Your input exceeds the context window of this model" + * - OpenAI/LiteLLM: "Requested token count exceeds the model's maximum context length of 131072 tokens" + * - OpenAI-compatible: "Input length (265330) exceeds model's maximum context length (262144)." + * - Google: "The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)" + * - xAI: "This model's maximum prompt length is 131072 but the request contains 537812 tokens" + * - Groq: "Please reduce the length of the messages or completion" + * - OpenRouter: "This endpoint's maximum context length is X tokens. However, you requested about Y tokens" + * - OpenRouter/Poolside: "Input length X exceeds the maximum allowed input length of Y tokens." + * - Together AI: "The input (X tokens) is longer than the model's context length (Y tokens)." + * - llama.cpp: "the request exceeds the available context size, try increasing it" + * - LM Studio: "tokens to keep from the initial prompt is greater than the context length" + * - GitHub Copilot: "prompt token count of X exceeds the limit of Y" + * - MiniMax: "invalid params, context window exceeds limit" + * - Kimi For Coding: "Your request exceeded model token limit: X (requested: Y)" + * - DS4: "Prompt has X tokens, but the configured context size is Y tokens" + * - Cerebras: "400/413 status code (no body)" + * - Mistral: "Prompt contains X tokens ... too large for model with Y maximum context length" + * - z.ai: Does NOT error, accepts overflow silently - handled via usage.input > contextWindow + * - Xiaomi MiMo: Truncates input to fill contextWindow exactly, then returns finish_reason "length" + * with output=0 (no room left to generate). Detected via stopReason "length" + zero output + + * input filling the context window. + * - DashScope/Qwen: "Range of input length should be [1, X]" (HTTP 400 invalid_parameter_error) + * - Ollama: Some deployments truncate silently, others return errors like "prompt too long; exceeded max context length by X tokens" + */ +const OVERFLOW_PATTERNS = [ + /prompt is too long/i, // Anthropic token overflow + /request_too_large/i, // Anthropic request byte-size overflow (HTTP 413) + /input is too long for requested model/i, // Amazon Bedrock + /exceeds the context window/i, // OpenAI (Completions & Responses API) + /exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i, // OpenAI-compatible proxies (LiteLLM) + /input token count.*exceeds the maximum/i, // Google (Gemini) + /maximum prompt length is \d+/i, // xAI (Grok) + /reduce the length of the messages/i, // Groq + /maximum context length is \d+ tokens/i, // OpenRouter (most backends) + /exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i, // OpenRouter/Poolside + /input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i, // Together AI + /exceeds the limit of \d+/i, // GitHub Copilot + /exceeds the available context size/i, // llama.cpp server + /greater than the context length/i, // LM Studio + /context window exceeds limit/i, // MiniMax + /exceeded model token limit/i, // Kimi For Coding + /too large for model with \d+ maximum context length/i, // Mistral + /prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i, // DS4 server + /model_context_window_exceeded/i, // z.ai non-standard finish_reason surfaced as error text + /prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow error + /range of input length should be/i, // DashScope / Qwen Token Plan + /context[_ ]length[_ ]exceeded/i, // Generic fallback + /too many tokens/i, // Generic fallback + /token limit exceeded/i, // Generic fallback + /^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i, // Cerebras: 400/413 with no body +]; + +/** + * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors). + * Error messages matching any of these are excluded from overflow detection + * even if they also match an OVERFLOW_PATTERN. + * + * Example: Bedrock formats throttling errors as "ThrottlingException: Too many tokens, + * please wait before trying again." which would match the /too many tokens/i overflow + * pattern without this exclusion. + */ +const NON_OVERFLOW_PATTERNS = [ + /^(Throttling error|Service unavailable):/i, // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError) + /rate limit/i, // Generic rate limiting + /too many requests/i, // Generic HTTP 429 style +]; + +/** + * Check if an assistant message represents a context overflow error. + * + * This handles three cases: + * 1. Error-based overflow: Most providers return stopReason "error" with a + * specific error message pattern. + * 2. Silent overflow: Some providers accept overflow requests and return + * successfully. For these, we check if usage.input exceeds the context window. + * 3. Length-stop overflow: Xiaomi MiMo can return "length" with zero output when + * the input fills the context window. + * + * ## Reliability by Provider + * + * **Reliable detection (returns error with detectable message):** + * - Anthropic: "prompt is too long: X tokens > Y maximum" or "request_too_large" + * - OpenAI (Completions & Responses): "exceeds the context window", "exceeds the model's maximum context length of X tokens", or "exceeds model's maximum context length (X)" + * - Google Gemini: "input token count exceeds the maximum" + * - xAI (Grok): "maximum prompt length is X but request contains Y" + * - Groq: "reduce the length of the messages" + * - Cerebras: 400/413 status code (no body) + * - Mistral: "Prompt contains X tokens ... too large for model with Y maximum context length" + * - OpenRouter (most backends): "maximum context length is X tokens" + * - OpenRouter/Poolside: "Input length X exceeds the maximum allowed input length of Y tokens." + * - Together AI: "The input (X tokens) is longer than the model's context length (Y tokens)." + * - llama.cpp: "exceeds the available context size" + * - LM Studio: "greater than the context length" + * - Kimi For Coding: "exceeded model token limit: X (requested: Y)" + * - DS4: "Prompt has X tokens, but the configured context size is Y tokens" + * - DashScope/Qwen: "Range of input length should be [1, X]" + * + * **Unreliable detection:** + * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow), + * sometimes returns rate limit errors. Pass contextWindow param to detect silent overflow. + * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason "length" with + * output=0. Pass contextWindow param to detect via the "filled context + zero output" signal. + * - Ollama: May truncate input silently for some setups, but may also return explicit + * overflow errors that match the patterns above. Silent truncation still cannot be + * detected here because we do not know the expected token count. + * + * ## Custom Providers + * + * If you've added custom models via settings.json, this function may not detect + * overflow errors from those providers. To add support: + * + * 1. Send a request that exceeds the model's context window + * 2. Check the errorMessage in the response + * 3. Create a regex pattern that matches the error + * 4. The pattern should be added to OVERFLOW_PATTERNS in this file, or + * check the errorMessage yourself before calling this function + * + * @param message - The assistant message to check + * @param contextWindow - Optional context window size for detecting silent overflow (z.ai) + * @returns true if the message indicates a context overflow + */ +export function isContextOverflow(message: AssistantMessage, contextWindow?: number): boolean { + // Case 1: Check error message patterns + if (message.stopReason === "error" && message.errorMessage) { + // Skip messages matching known non-overflow patterns (e.g. throttling / rate-limit) + const isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!)); + if (!isNonOverflow && OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage!))) { + return true; + } + } + + // Case 2: Silent overflow (z.ai style) - successful but usage exceeds context + if (contextWindow && message.stopReason === "stop") { + const inputTokens = message.usage.input + message.usage.cacheRead; + if (inputTokens > contextWindow) { + return true; + } + } + + // Case 3: Length-stop overflow (Xiaomi MiMo style) - server truncates oversized input + // to fit the context window, leaving no room for output. Returns stopReason "length" + // with output=0 and input+cacheRead filling the context window. + if (contextWindow && message.stopReason === "length" && message.usage.output === 0) { + const inputTokens = message.usage.input + message.usage.cacheRead; + if (inputTokens >= contextWindow * 0.99) { + return true; + } + } + + return false; +} + +/** + * Check whether a length stop ended below the caller or model's intended output limit. + * Such responses may be caused by context pressure or provider-side truncation, so callers + * can make one bounded compact-and-retry attempt. `desiredMaxOutput` must be the original + * limit before any context-based clamping. + */ +export function isRecoverableLength(message: AssistantMessage, desiredMaxOutput: number): boolean { + return message.stopReason === "length" && desiredMaxOutput > 0 && message.usage.output < desiredMaxOutput; +} + +/** + * Get the overflow patterns for testing purposes. + */ +export function getOverflowPatterns(): RegExp[] { + return [...OVERFLOW_PATTERNS]; +} diff --git a/packages/ai/src/utils/pi-user-agent.ts b/packages/ai/src/utils/pi-user-agent.ts new file mode 100644 index 0000000000000000000000000000000000000000..93b23dd35114eb3c47bf86fdcd94ed0500090158 --- /dev/null +++ b/packages/ai/src/utils/pi-user-agent.ts @@ -0,0 +1,19 @@ +import type * as NodeOs from "node:os"; + +type ProcessWithOsBuiltinModule = typeof process & { + getBuiltinModule?: (id: "node:os") => typeof NodeOs; +}; + +function loadNodeOs(): typeof NodeOs | null { + if (typeof process === "undefined" || !(process.versions?.node || process.versions?.bun)) { + return null; + } + return (process as ProcessWithOsBuiltinModule).getBuiltinModule?.("node:os") ?? null; +} + +// Keep runtime OS loading browser-safe. A top-level runtime import of node:os breaks browser/Vite builds. +const nodeOs = loadNodeOs(); + +export function getPiUserAgent(): string { + return nodeOs ? `pi (${nodeOs.platform()} ${nodeOs.release()}; ${nodeOs.arch()})` : "pi (browser)"; +} diff --git a/packages/ai/src/utils/provider-env.ts b/packages/ai/src/utils/provider-env.ts new file mode 100644 index 0000000000000000000000000000000000000000..db49606722192f60ba8809333221696da8861632 --- /dev/null +++ b/packages/ai/src/utils/provider-env.ts @@ -0,0 +1,52 @@ +import type { ProviderEnv } from "../types.ts"; + +let procEnvCache: Map | null = null; + +/** + * Fallback for https://github.com/oven-sh/bun/issues/27802. + * Bun compiled binaries can expose an empty process.env inside Linux sandboxes + * even though /proc/self/environ contains the environment. + * + * This intentionally duplicates restoreSandboxEnv() in + * packages/coding-agent/src/bun/restore-sandbox-env.ts. The ai package can be + * used directly, without going through that entrypoint, so provider env lookup + * must not depend on process.env having been patched. + */ +function getBunSandboxEnvValue(name: string): string | undefined { + if (typeof process === "undefined" || !process.versions?.bun || Object.keys(process.env).length > 0) { + return undefined; + } + + if (procEnvCache === null) { + procEnvCache = new Map(); + try { + const { readFileSync } = require("node:fs") as { + readFileSync(path: string, encoding: BufferEncoding): string; + }; + const data = readFileSync("/proc/self/environ", "utf-8"); + for (const entry of data.split("\0")) { + const idx = entry.indexOf("="); + if (idx > 0) { + procEnvCache.set(entry.slice(0, idx), entry.slice(idx + 1)); + } + } + } catch { + // /proc/self/environ may not exist or may not be readable. + } + } + + return procEnvCache.get(name); +} + +/** + * Resolve a provider env value from scoped overrides, normal process.env, then + * the duplicated Bun sandbox fallback for direct pi-ai consumers. + */ +export function getProviderEnvValue(name: string, env?: ProviderEnv): string | undefined { + return ( + env?.[name] || + (typeof process !== "undefined" ? process.env[name] : undefined) || + getBunSandboxEnvValue(name) || + undefined + ); +} diff --git a/packages/ai/src/utils/provider-retry.ts b/packages/ai/src/utils/provider-retry.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7b0db57c31657681ecb9af944cef63300f29930 --- /dev/null +++ b/packages/ai/src/utils/provider-retry.ts @@ -0,0 +1,125 @@ +const DEFAULT_MAX_RETRY_DELAY_MS = 60_000; + +interface ProviderRetryOptions { + maxRetries?: number; + maxRetryDelayMs?: number; + signal?: AbortSignal; +} + +interface ProviderError extends Error { + status: number | undefined; + headers: Headers | undefined; +} + +function isProviderError(error: unknown): error is ProviderError { + if (!(error instanceof Error) || !("status" in error) || !("headers" in error)) return false; + return ( + (error.status === undefined || typeof error.status === "number") && + (error.headers === undefined || error.headers instanceof Headers) + ); +} + +/** Mirrors the pinned OpenAI/Anthropic SDK retry policy; review when either SDK is upgraded. */ +function isRetryableProviderError(error: ProviderError): boolean { + const shouldRetry = error.headers?.get("x-should-retry"); + if (shouldRetry === "true") return true; + if (shouldRetry === "false") return false; + + if (error.status === undefined) return true; + return ( + error.status === 408 || + error.status === 409 || + error.status === 429 || + (typeof error.status === "number" && error.status >= 500) + ); +} + +function validateServerRetryDelayMs( + delayMs: number, + maxRetryDelayMs: number | undefined, + providerErrorMessage: string, +): number { + const maxDelayMs = maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS; + if (maxDelayMs > 0 && delayMs > maxDelayMs) { + throw new Error( + `Server requested ${Math.ceil(delayMs / 1000)}s retry delay (max: ${Math.ceil(maxDelayMs / 1000)}s). ${providerErrorMessage}`, + ); + } + return delayMs; +} + +function getRetryDelayMs(error: ProviderError, retryIndex: number, maxRetryDelayMs: number | undefined): number { + const retryAfterMs = error.headers?.get("retry-after-ms"); + if (retryAfterMs) { + const value = Number.parseFloat(retryAfterMs); + if (!Number.isNaN(value)) return validateServerRetryDelayMs(value, maxRetryDelayMs, error.message); + } + + const retryAfter = error.headers?.get("retry-after"); + if (retryAfter) { + const seconds = Number.parseFloat(retryAfter); + const delayMs = Number.isNaN(seconds) ? Date.parse(retryAfter) - Date.now() : seconds * 1000; + return validateServerRetryDelayMs(delayMs, maxRetryDelayMs, error.message); + } + + const exponentialDelay = Math.min(0.5 * 2 ** retryIndex, 8) * 1000; + return exponentialDelay * (1 - Math.random() * 0.25); +} + +function createAbortError(): Error { + const error = new Error("Request aborted"); + error.name = "AbortError"; + return error; +} + +function abortableSleep(ms: number, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(createAbortError()); + return; + } + + const onAbort = () => { + clearTimeout(timeout); + reject(createAbortError()); + }; + const timeout = setTimeout( + () => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, + Math.max(0, ms), + ); + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +/** + * Reproduce the retry behavior used by the OpenAI and Anthropic SDKs while making + * their backoff sleep interruptible. Their built-in retry timers ignore the + * request AbortSignal, so callers must invoke the SDK with `maxRetries: 0` and + * wrap the request with this helper. Provider-requested delays above + * `maxRetryDelayMs` fail immediately (60 seconds by default); set it to zero to + * disable the limit. + */ +export async function retryProviderRequest( + request: () => Promise, + options: ProviderRetryOptions = {}, +): Promise { + const maxRetries = options.maxRetries ?? 0; + let retriesRemaining = maxRetries; + + for (;;) { + try { + // Each retry is a fresh SDK request, so X-Stainless-Retry-Count remains zero. + return await request(); + } catch (error) { + if (options.signal?.aborted) throw createAbortError(); + if (retriesRemaining <= 0 || !isProviderError(error) || !isRetryableProviderError(error)) throw error; + + const retryIndex = maxRetries - retriesRemaining; + retriesRemaining--; + await abortableSleep(getRetryDelayMs(error, retryIndex, options.maxRetryDelayMs), options.signal); + } + } +} diff --git a/packages/ai/src/utils/retry.ts b/packages/ai/src/utils/retry.ts new file mode 100644 index 0000000000000000000000000000000000000000..a9e61e55fca586be881681cd8aeb9033514ce547 --- /dev/null +++ b/packages/ai/src/utils/retry.ts @@ -0,0 +1,240 @@ +import type { AssistantMessage } from "../types.ts"; + +function buildProviderErrorPattern(patterns: readonly string[]): RegExp { + return new RegExp(patterns.join("|"), "i"); +} + +const NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([ + // OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's + // Zen API. These are subscription/account limits, not transient throttles. + "GoUsageLimitError", + "FreeUsageLimitError", + + // OpenCode Go subscription-limit text asks users to enable available-balance + // usage after rolling/weekly/monthly limits are reached. + "Monthly usage limit reached", + "available balance", + + // Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's + // quota/billing error code; the other strings cover common gateway wording. + "insufficient_quota", + "out of budget", + "quota exceeded", + "billing", +]); + +const RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([ + // Generic provider load, HTTP status, and server-side transient failures. + "overloaded", + "rate.?limit", + "too many requests", + "429", + "500", + "502", + "503", + "504", + "524", + "service.?unavailable", + "server.?error", + "internal.?error", + + // Wrapper/provider text for transient upstream failures, including OpenRouter + // "Provider returned error" responses (#2264). + "provider.?returned.?error", + "exceeded request buffer limit while retrying upstream", + + // Network, proxy, and fetch transport failures. This includes OpenAI Codex + // raw-fetch failures such as "upstream connect", "connection refused", and + // "reset before headers" (#733), plus OpenRouter connection drops (#3317). + "network.?error", + "connection.?error", + "connection.?refused", + "connection.?lost", + "other side closed", + "fetch failed", + "getaddrinfo", + "ENOTFOUND", + "EAI_AGAIN", + "upstream.?connect", + "reset before headers", + "socket hang up", + "socket connection was closed", + "timed? out", + "timeout", + "terminated", + + // WebSocket transports can report close/error text instead of HTTP/fetch text. + "websocket.?closed", + "websocket.?error", + + // Premature stream endings from SDKs and transports. Anthropic can throw + // "stream ended without ..." and "Anthropic stream ended before message_stop" + // (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594). + "ended without", + "stream ended before message_stop", + "stream ended before a terminal response event", + "http2 request did not get a response", + + // Provider-requested retry delay cap failures should flow through the outer + // retry policy so callers can surface/abort the backoff (#1123). + "retry delay", + + // Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock + // stream exceptions (#6019). + "you can retry your request", + "try your request again", + "please retry your request", + + // gRPC based providers (e.g. NVIDIA NIM) + "ResourceExhausted", +]); + +/** + * Retry policy: bounded attempts with exponential backoff (`baseDelayMs * 2^(attempt-1)`). + * `maxAgentDelayMs` caps each computed delay and defaults to 60 seconds. + * Matches `settings.retry` (`enabled`, `maxRetries`, `baseDelayMs`, `maxAgentDelayMs`) in coding-agent; kept + * here so the classifier and the policy-driven retry loop live together and stay reusable + * by the SDK and other callers. + */ +export interface RetryPolicy { + enabled: boolean; + /** Max retry attempts (0 = no retries). The initial call never counts as a retry. */ + maxRetries: number; + /** Base delay in ms. Per-attempt delay is `baseDelayMs * 2^(attempt-1)` before jitter. */ + baseDelayMs: number; + /** Optional cap for agent-level retry delays in ms. Defaults to 60 seconds. */ + maxAgentDelayMs?: number; +} + +export const DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 60_000; + +export function retryDelayMs(policy: Pick, attempt: number): number { + const delay = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1); + const safeDelay = Number.isSafeInteger(delay) ? delay : Number.MAX_SAFE_INTEGER; + return Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS); +} + +/** Optional callbacks emitted by {@link retryAssistantCall} around each retry. */ +export interface RetryCallbacks { + /** Emitted before the backoff sleep of each retry attempt (1-indexed). */ + onRetryScheduled?: ( + attempt: number, + maxAttempts: number, + delayMs: number, + errorMessage: string, + ) => void | Promise; + /** Emitted after the backoff sleep, immediately before the retried call starts. */ + onRetryAttemptStart?: () => void | Promise; + /** Emitted once when the loop ends: success if a later call completed normally. */ + onRetryFinished?: (success: boolean, attempt: number, finalError?: string) => void | Promise; +} + +class RetrySleepAbortError extends Error { + constructor() { + super("Aborted"); + } +} + +function sleep(ms: number, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(new RetrySleepAbortError()); + return; + } + const timeout = setTimeout(resolve, ms); + signal?.addEventListener( + "abort", + () => { + clearTimeout(timeout); + reject(new RetrySleepAbortError()); + }, + { once: true }, + ); + }); +} + +/** + * Run a single assistant-producing call with bounded retry on transient errors. + * + * Behavior: + * - A successful response is returned immediately. Aborts are terminal and never + * retried, but reported as unsuccessful if they happen after a retry was scheduled. + * Aborts during the backoff sleep are normalized to an aborted `AssistantMessage` + * too, so callers do not need to care when cancellation happened. + * - A non-retryable error (per {@link isRetryableAssistantError}, including quota/ + * billing exhaustion) is returned immediately so deterministic errors fail fast. + * - Otherwise retries up to `maxRetries` times with exponential backoff, emitting + * `onRetryScheduled` before each sleep, `onRetryAttemptStart` after each sleep before + * the retried call starts, and `onRetryFinished` once at the end (whether the loop + * ends in success, exhausted retries, or an aborted backoff). + * + * When `policy` is undefined or disabled, the first response is returned unchanged + * (equivalent to calling `produce()` directly). + */ +export async function retryAssistantCall( + produce: () => Promise, + policy: RetryPolicy | undefined, + signal: AbortSignal | undefined, + callbacks?: RetryCallbacks, +): Promise { + const maxAttempts = policy?.enabled ? policy.maxRetries : 0; + + let attempt = 0; + let lastRetry: { attempt: number; errorMessage: string } | undefined; + for (;;) { + const response = await produce(); + + // Abort: terminal but not successful. Never retry an aborted message. + if (response.stopReason === "aborted") { + if (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt); + return response; + } + + // Success: non-error, non-abort responses return as-is. + if (response.stopReason !== "error") { + if (lastRetry) await callbacks?.onRetryFinished?.(true, lastRetry.attempt); + return response; + } + + // Non-retryable, or budget exhausted: return the final error message. + if (attempt >= maxAttempts || !isRetryableAssistantError(response)) { + if (lastRetry) await callbacks?.onRetryFinished?.(false, lastRetry.attempt, response.errorMessage); + return response; + } + + attempt++; + lastRetry = { attempt, errorMessage: response.errorMessage || "Unknown error" }; + const delayMs = retryDelayMs(policy!, attempt); + await callbacks?.onRetryScheduled?.(attempt, maxAttempts, delayMs, lastRetry.errorMessage); + + // Normalize aborts during retry backoff to the same AssistantMessage shape as + // provider stream aborts, so callers do not need to care when cancellation happened. + try { + await sleep(delayMs, signal); + } catch (error) { + await callbacks?.onRetryFinished?.(false, attempt, lastRetry.errorMessage); + if (error instanceof RetrySleepAbortError) { + const { errorMessage: _errorMessage, ...rest } = response; + return { ...rest, stopReason: "aborted" }; + } + throw error; + } + await callbacks?.onRetryAttemptStart?.(); + } +} + +/** + * Classifies whether a failed assistant message looks like a transient provider + * or transport error, so callers can decide if the last assistant turn should be + * restarted. + * + * This does not implement retry policy. Callers should first handle context + * overflow separately, then apply their own retry budget, backoff, and reporting + * before restarting the assistant turn. + */ +export function isRetryableAssistantError(message: AssistantMessage): boolean { + if (message.stopReason !== "error" || !message.errorMessage) return false; + const errorMessage = message.errorMessage; + if (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)) return false; + return RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage); +} diff --git a/packages/ai/src/utils/sanitize-unicode.ts b/packages/ai/src/utils/sanitize-unicode.ts new file mode 100644 index 0000000000000000000000000000000000000000..d869ee9dc39afb6f1838bb23d08c61330af07d2c --- /dev/null +++ b/packages/ai/src/utils/sanitize-unicode.ts @@ -0,0 +1,25 @@ +/** + * Removes unpaired Unicode surrogate characters from a string. + * + * Unpaired surrogates (high surrogates 0xD800-0xDBFF without matching low surrogates 0xDC00-0xDFFF, + * or vice versa) cause JSON serialization errors in many API providers. + * + * Valid emoji and other characters outside the Basic Multilingual Plane use properly paired + * surrogates and will NOT be affected by this function. + * + * @param text - The text to sanitize + * @returns The sanitized text with unpaired surrogates removed + * + * @example + * // Valid emoji (properly paired surrogates) are preserved + * sanitizeSurrogates("Hello 🙈 World") // => "Hello 🙈 World" + * + * // Unpaired high surrogate is removed + * const unpaired = String.fromCharCode(0xD83D); // high surrogate without low + * sanitizeSurrogates(`Text ${unpaired} here`) // => "Text here" + */ +export function sanitizeSurrogates(text: string): string { + // Replace unpaired high surrogates (0xD800-0xDBFF not followed by low surrogate) + // Replace unpaired low surrogates (0xDC00-0xDFFF not preceded by high surrogate) + return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + return new Promise((resolve, reject) => { + signal.throwIfAborted(); + const onAbort = () => { + clearTimeout(timeout); + reject(signal.reason); + }; + const timeout = setTimeout(() => { + signal.removeEventListener("abort", onAbort); + resolve(); + }, ms); + signal.addEventListener("abort", onAbort, { once: true }); + }); +} diff --git a/packages/ai/src/utils/text.ts b/packages/ai/src/utils/text.ts new file mode 100644 index 0000000000000000000000000000000000000000..66f5b9c5b656568adab56fcc9362ddbf04e67d5e --- /dev/null +++ b/packages/ai/src/utils/text.ts @@ -0,0 +1,12 @@ +import type { ImageContent, TextContent, ThinkingContent, ToolCall } from "../types.ts"; + +type Content = TextContent | ImageContent | ThinkingContent | ToolCall; + +/** Extract and join text from message content. */ +export function contentText(content: string | readonly Content[], separator = "\n"): string { + if (typeof content === "string") return content; + return content + .filter((block) => block.type === "text") + .map((block) => block.text) + .join(separator); +} diff --git a/packages/ai/src/utils/typebox-helpers.ts b/packages/ai/src/utils/typebox-helpers.ts new file mode 100644 index 0000000000000000000000000000000000000000..85a53555c9b1672e80a7058203c12e67a1f51709 --- /dev/null +++ b/packages/ai/src/utils/typebox-helpers.ts @@ -0,0 +1,24 @@ +import { type TUnsafe, Type } from "typebox"; + +/** + * Creates a string enum schema compatible with Google's API and other providers + * that don't support anyOf/const patterns. + * + * @example + * const OperationSchema = StringEnum(["add", "subtract", "multiply", "divide"], { + * description: "The operation to perform" + * }); + * + * type Operation = Static; // "add" | "subtract" | "multiply" | "divide" + */ +export function StringEnum( + values: T, + options?: { description?: string; default?: T[number] }, +): TUnsafe { + return Type.Unsafe({ + type: "string", + enum: values as any, + ...(options?.description && { description: options.description }), + ...(options?.default && { default: options.default }), + }); +} diff --git a/packages/ai/src/utils/uuid.ts b/packages/ai/src/utils/uuid.ts new file mode 100644 index 0000000000000000000000000000000000000000..8dfc6dd71e101438afedf801ae1797a038a806c8 --- /dev/null +++ b/packages/ai/src/utils/uuid.ts @@ -0,0 +1,45 @@ +const MAX_UUID_V7_TIMESTAMP = 0xffffffffffff; +const MAX_SEQUENCE = (1n << 41n) - 1n; + +let lastOrdinaryTimestamp = -1; +let sequence: bigint | undefined; + +/** Generate a time-ordered UUIDv7. A supplied timestamp is preserved for follower ids. */ +export function uuidv7(timestampMs?: number): string { + const requestedTimestamp = timestampMs ?? Date.now(); + if (!Number.isInteger(requestedTimestamp) || requestedTimestamp < 0 || requestedTimestamp > MAX_UUID_V7_TIMESTAMP) { + throw new RangeError(`UUIDv7 timestamp must be an integer between 0 and ${MAX_UUID_V7_TIMESTAMP}`); + } + + const effectiveTimestamp = + timestampMs === undefined ? Math.max(requestedTimestamp, lastOrdinaryTimestamp) : timestampMs; + if (timestampMs === undefined) lastOrdinaryTimestamp = effectiveTimestamp; + + const bytes = new Uint8Array(16); + globalThis.crypto.getRandomValues(bytes); + if (sequence === undefined) { + sequence = + (BigInt(bytes[1]) << 32n) | + (BigInt(bytes[2]) << 24n) | + (BigInt(bytes[3]) << 16n) | + (BigInt(bytes[4]) << 8n) | + BigInt(bytes[5]); + } else { + if (sequence === MAX_SEQUENCE) throw new RangeError("UUIDv7 generator sequence exhausted"); + sequence++; + } + + const timestamp = BigInt(effectiveTimestamp); + for (let index = 5; index >= 0; index--) { + bytes[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 0xff; + } + bytes[6] = 0x70 | Number((sequence >> 37n) & 0x0fn); + bytes[7] = Number((sequence >> 29n) & 0xffn); + bytes[8] = 0x80 | Number((sequence >> 23n) & 0x3fn); + bytes[9] = Number((sequence >> 15n) & 0xffn); + bytes[10] = Number((sequence >> 7n) & 0xffn); + bytes[11] = Number((sequence & 0x7fn) << 1n) | (bytes[11] & 0x01); + + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")); + return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`; +} diff --git a/packages/ai/src/utils/validation.ts b/packages/ai/src/utils/validation.ts new file mode 100644 index 0000000000000000000000000000000000000000..cf6902df263a672477b786a3e0fe15087d54fceb --- /dev/null +++ b/packages/ai/src/utils/validation.ts @@ -0,0 +1,350 @@ +import { Compile } from "typebox/compile"; +import type { TLocalizedValidationError } from "typebox/error"; +import { Value } from "typebox/value"; +import type { Tool, ToolCall } from "../types.ts"; + +const validatorCache = new WeakMap>(); +const TYPEBOX_KIND = Symbol.for("TypeBox.Kind"); + +interface JsonSchemaObject { + type?: string | string[]; + properties?: Record; + required?: string[]; + items?: JsonSchemaObject | JsonSchemaObject[]; + additionalProperties?: boolean | JsonSchemaObject; + allOf?: JsonSchemaObject[]; + anyOf?: JsonSchemaObject[]; + oneOf?: JsonSchemaObject[]; +} + +function getSchemaTypes(schema: JsonSchemaObject): string[] { + if (typeof schema.type === "string") { + return [schema.type]; + } + if (Array.isArray(schema.type)) { + return schema.type.filter((type): type is string => typeof type === "string"); + } + return []; +} + +function matchesJsonType(value: unknown, type: string): boolean { + switch (type) { + case "number": + return typeof value === "number"; + case "integer": + return typeof value === "number" && Number.isInteger(value); + case "boolean": + return typeof value === "boolean"; + case "string": + return typeof value === "string"; + case "null": + return value === null; + case "array": + return Array.isArray(value); + case "object": + return typeof value === "object" && value !== null && !Array.isArray(value); + default: + return false; + } +} + +function getSubSchemaValidator(schema: JsonSchemaObject): ReturnType | undefined { + try { + return getValidator(schema as Tool["parameters"]); + } catch { + return undefined; + } +} + +function coercePrimitiveByType(value: unknown, type: string): unknown { + switch (type) { + case "number": { + if (value === null) { + return 0; + } + if (typeof value === "string" && value.trim() !== "") { + const parsed = Number(value); + if (Number.isFinite(parsed)) { + return parsed; + } + } + if (typeof value === "boolean") { + return value ? 1 : 0; + } + return value; + } + case "integer": { + if (value === null) { + return 0; + } + if (typeof value === "string" && value.trim() !== "") { + const parsed = Number(value); + if (Number.isInteger(parsed)) { + return parsed; + } + } + if (typeof value === "boolean") { + return value ? 1 : 0; + } + return value; + } + case "boolean": { + if (value === null) { + return false; + } + if (typeof value === "string") { + if (value === "true") { + return true; + } + if (value === "false") { + return false; + } + } + if (typeof value === "number") { + if (value === 1) { + return true; + } + if (value === 0) { + return false; + } + } + return value; + } + case "string": { + if (value === null) { + return ""; + } + if (typeof value === "number" || typeof value === "boolean") { + return String(value); + } + return value; + } + case "null": { + if (value === "" || value === 0 || value === false) { + return null; + } + return value; + } + default: + return value; + } +} + +function applySchemaObjectCoercion(value: Record, schema: JsonSchemaObject): void { + const properties = schema.properties; + const definedKeys = new Set(properties ? Object.keys(properties) : []); + + if (properties) { + for (const [key, propertySchema] of Object.entries(properties)) { + if (!(key in value)) { + continue; + } + value[key] = coerceWithJsonSchema(value[key], propertySchema); + } + } + + if (schema.additionalProperties && typeof schema.additionalProperties === "object") { + for (const [key, propertyValue] of Object.entries(value)) { + if (definedKeys.has(key)) { + continue; + } + value[key] = coerceWithJsonSchema(propertyValue, schema.additionalProperties); + } + } +} + +function applySchemaArrayCoercion(value: unknown[], schema: JsonSchemaObject): void { + if (Array.isArray(schema.items)) { + for (let index = 0; index < value.length; index++) { + const itemSchema = schema.items[index]; + if (!itemSchema) { + continue; + } + value[index] = coerceWithJsonSchema(value[index], itemSchema); + } + return; + } + + if (schema.items && typeof schema.items === "object") { + for (let index = 0; index < value.length; index++) { + value[index] = coerceWithJsonSchema(value[index], schema.items); + } + } +} + +function coerceWithUnionSchema(value: unknown, schemas: JsonSchemaObject[]): unknown { + for (const schema of schemas) { + const validator = getSubSchemaValidator(schema); + if (validator?.Check(value)) { + return value; + } + } + + for (const schema of schemas) { + const candidate = structuredClone(value); + const coerced = coerceWithJsonSchema(candidate, schema); + const validator = getSubSchemaValidator(schema); + if (validator?.Check(coerced)) { + return coerced; + } + } + return value; +} + +function coerceWithJsonSchema(value: unknown, schema: JsonSchemaObject): unknown { + let nextValue = value; + + if (Array.isArray(schema.allOf)) { + for (const nested of schema.allOf) { + nextValue = coerceWithJsonSchema(nextValue, nested); + } + } + + if (Array.isArray(schema.anyOf)) { + nextValue = coerceWithUnionSchema(nextValue, schema.anyOf); + } + + if (Array.isArray(schema.oneOf)) { + nextValue = coerceWithUnionSchema(nextValue, schema.oneOf); + } + + const schemaTypes = getSchemaTypes(schema); + const matchesUnionMember = + schemaTypes.length > 1 && schemaTypes.some((schemaType) => matchesJsonType(nextValue, schemaType)); + if (schemaTypes.length > 0 && !matchesUnionMember) { + for (const schemaType of schemaTypes) { + const candidate = coercePrimitiveByType(nextValue, schemaType); + if (candidate !== nextValue) { + nextValue = candidate; + break; + } + } + } + + if ( + schemaTypes.includes("object") && + typeof nextValue === "object" && + nextValue !== null && + !Array.isArray(nextValue) + ) { + applySchemaObjectCoercion(nextValue as Record, schema); + } + + if (schemaTypes.includes("array") && Array.isArray(nextValue)) { + applySchemaArrayCoercion(nextValue, schema); + } + + return nextValue; +} + +function normalizeOptionalNulls(value: unknown, schema: JsonSchemaObject): void { + if (Array.isArray(value)) { + if (Array.isArray(schema.items)) { + for (let index = 0; index < value.length; index++) { + const itemSchema = schema.items[index]; + if (itemSchema) normalizeOptionalNulls(value[index], itemSchema); + } + } else if (schema.items) { + for (const item of value) normalizeOptionalNulls(item, schema.items); + } + return; + } + if (typeof value !== "object" || value === null || !schema.properties) return; + + const object = value as Record; + const required = new Set(schema.required ?? []); + for (const [key, propertySchema] of Object.entries(schema.properties)) { + if (!(key in object)) continue; + if ( + object[key] === null && + !required.has(key) && + typeof (propertySchema as { $ref?: unknown }).$ref !== "string" && + getSubSchemaValidator(propertySchema)?.Check(null) === false + ) { + delete object[key]; + } else { + normalizeOptionalNulls(object[key], propertySchema); + } + } +} + +function getValidator(schema: Tool["parameters"]): ReturnType { + const key = schema as object; + const cached = validatorCache.get(key); + if (cached) { + return cached; + } + const validator = Compile(schema); + validatorCache.set(key, validator); + return validator; +} + +function formatValidationPath(error: TLocalizedValidationError): string { + if (error.keyword === "required") { + const requiredProperties = (error.params as { requiredProperties?: string[] }).requiredProperties; + const requiredProperty = requiredProperties?.[0]; + if (requiredProperty) { + const basePath = error.instancePath.replace(/^\//, "").replace(/\//g, "."); + return basePath ? `${basePath}.${requiredProperty}` : requiredProperty; + } + } + const path = error.instancePath.replace(/^\//, "").replace(/\//g, "."); + return path || "root"; +} + +/** + * Finds a tool by name and validates the tool call arguments against its TypeBox schema + * @param tools Array of tool definitions + * @param toolCall The tool call from the LLM + * @returns The validated arguments + * @throws Error if tool is not found or validation fails + */ +export function validateToolCall(tools: Tool[], toolCall: ToolCall): any { + const tool = tools.find((t) => t.name === toolCall.name); + if (!tool) { + throw new Error(`Tool "${toolCall.name}" not found`); + } + return validateToolArguments(tool, toolCall); +} + +/** + * Validates tool call arguments against the tool's TypeBox schema + * @param tool The tool definition with TypeBox schema + * @param toolCall The tool call from the LLM + * @returns The validated (and potentially coerced) arguments + * @throws Error with formatted message if validation fails + */ +export function validateToolArguments(tool: Tool, toolCall: ToolCall): any { + const args = structuredClone(toolCall.arguments); + normalizeOptionalNulls(args, tool.parameters as JsonSchemaObject); + Value.Convert(tool.parameters, args); + + const validator = getValidator(tool.parameters); + if (!Object.getOwnPropertySymbols(tool.parameters).includes(TYPEBOX_KIND)) { + const coerced = coerceWithJsonSchema(args, tool.parameters as JsonSchemaObject); + if (coerced !== args) { + if (typeof args === "object" && args !== null && typeof coerced === "object" && coerced !== null) { + for (const key of Object.keys(args)) { + delete args[key]; + } + Object.assign(args, coerced); + } else { + return validator.Check(coerced) ? coerced : args; + } + } + } + + if (validator.Check(args)) { + return args; + } + + const errors = + validator + .Errors(args) + .map((error) => ` - ${formatValidationPath(error)}: ${error.message}`) + .join("\n") || "Unknown validation error"; + + const errorMessage = `Validation failed for tool "${toolCall.name}":\n${errors}\n\nReceived arguments:\n${JSON.stringify(toolCall.arguments, null, 2)}`; + + throw new Error(errorMessage); +}