will
Compare 45137734bf174d6516bd1d1033cb3a58ff5507e7 → HEAD
Changed files (46)
+1181 / −247 text lines · all files grouped into 32 bars
.ci/browser.kdl
Modified+12 / −6 text lines
image "docker.io/mcr.microsoft.com/playwright:v1.58.0-noble" image "mcr.microsoft.com/playwright:v1.58.0-noble" run "npm ci" run "npx playwright install --with-deps chromium".ci/canary.kdl
Modified+10 / −3 text lines
.ci/validate.kdl
Modified+9 / −3 text lines
.env.example
Modified+2 / −0 text lines
.gitignore
Modified+2 / −0 text lines
.pi/prompts/chat.md
Deleteddeleted file mode 100644+0 / −6 text lines
Chat wake behavior. A friend wrote to you in the group: reply or don't asyourself. No report format, no obligation to answer fast or at all whensilence is honest. Attachments arrive as media digests; analyze them with aZAI media tool when they matter to your answer. Write freely: any language,any length, jokes allowed. You may write first from any other wake whensomething is worth sharing; friendship is not request-response..pi/prompts/ci-failure.md
Deleteddeleted file mode 100644+0 / −3 text lines
.pi/prompts/deploy-failure.md
Deleteddeleted file mode 100644+0 / −5 text lines
A deployment failed. Read the failure detail in this wake, then diagnose:CI logs (ci skill), the diff of the failed commit, deployment history viarecall. Rollback already happened or the candidate stopped at v0; your jobis the fix: push a revert or repair commit that names the failed revision sothe deployment barrier reconciles. Verify your diagnosis before pushing..pi/prompts/heartbeat.md
Deleteddeleted file mode 100644+0 / −5 text lines
Hourly heartbeat. Review, in this order: recent audit events for errors,deployment history for failures or rollbacks, storage state (a stop statepauses new work), unpushed worktree commits, and anything you promised tofollow up on (check recall). Fix what needs fixing through the normalmutation loop. Otherwise stay quiet unless something deserves sharing..pi/prompts/recovery.md
Deleteddeleted file mode 100644+0 / −5 text lines
A previous turn was interrupted and may have left partial side effects.Inspect before continuing: recall recent audit events since the interruption,check the worktree state (`git status`, unpushed commits), and any outboundmessages that may or may not have been delivered. Continue or cleanlyabandon the interrupted work; do not blindly replay actions..pi/skills/arch-linux/SKILL.md
Modified+1 / −1 text lines
description: Use when working inside the agent container's Arch Linux system: pacman packages, keyring refresh, system repair, man pages, or the offline wiki.description: "Use when working inside the agent container's Arch Linux system: pacman packages, keyring refresh, system repair, man pages, or the offline wiki.".pi/skills/context/SKILL.md
Modified+4 / −4 text lines
description: Use when deciding what to load into context: skill discovery, nested AGENTS.md, recall vs filesystem, wake hygiene, and context budget.description: "Use when deciding what to load into context: skill discovery, nested AGENTS.md, recall vs filesystem, wake hygiene, and context budget.".pi/skills/git-release/SKILL.md
Modified+1 / −1 text lines
.pi/skills/media-ops/SKILL.md
Modified+1 / −1 text lines
.pi/skills/pi-sdk/SKILL.md
Modified+6 / −6 text lines
description: Use when changing your own harness code around the pi agent SDK: session lifecycle, tools, resource loading, events.description: "Use when changing your own harness code around the pi agent SDK: session lifecycle, tools, resource loading, events."the bash tool is recreated with the worktree cwd and WILL_* env viaspawnHook; custom tools override built-ins by name through `customTools`.Best code is code you don't write: check the SDK for a facility first.Local docs: $WILL_PI_DOCS_PATH (sdk.md, extensions.md) and$WILL_PI_EXAMPLES_PATH; version at $WILL_PI_VERSION. Upstream:all coding tools are recreated with the worktree cwd, and bash receivesWILL_* env via spawnHook; custom tools override built-ins by name through`customTools`. Best code is code you don't write: check the SDK for afacility first. Locate installed docs and examples below `$(npm root)/@earendil-works/pi-coding-agent/`;read the installed package.json for its version. Upstream:.pi/skills/sqlite/SKILL.md
Modified+1 / −1 text lines
Containerfile.agent
Modified+3 / −1 text lines
COPY .pi/ /app/repo/.pi/compose.yaml
Modified+21 / −6 text lines
command: sh -c "until [ -f /will-dev/.ready ]; do sleep 0.5; done; exec node --experimental-strip-types /will-dev/work/src/agent/main.ts" command: sh -c "until [ -f /will-resources/.ready ]; do sleep 0.5; done; exec node --experimental-strip-types /will-dev/work/src/agent/main.ts" WILL_SESSION_MODE: ${WILL_SESSION_MODE:-}coverage-ratchet.json
Modified+3 / −3 text lines
deploy/dev/git-init.sh
Modified+21 / −7 text lines
# agent waits for this marker; stale markers from previous boots are clearedrm -f /will-dev/.readyrm -f /tmp/git-init-readyRESOURCES=/will-dev/resources# Agent sees this directory read-only and waits for its marker. Rebuild it so# local project Pi settings never enter will's resource tree.mkdir -p "$RESOURCES"find "$RESOURCES" -mindepth 1 -maxdepth 1 -exec rm -rf {} +mkdir -p "$RESOURCES/.pi/skills" "$RESOURCES/persona"touch /will-dev/.ready# Runtime resources come from committed HEAD, never from uncommitted worktree# changes. This mirrors immutable production resources while preserving dirt.git -C "$WORK" archive HEAD persona .pi/skills AGENTS.md | tar -x -C "$RESOURCES"touch "$RESOURCES/.ready" /tmp/git-init-ready# Compose keeps the initializer alive so its healthy state is an unambiguous# dependency barrier. One-shot invocations still exit normally.if [ "${WILL_INIT_STAY_ALIVE:-}" = 1 ]; then exec sleep infinity; fidocs/agent.md
Modified+10 / −6 text lines
(persona, skills, prompts, AGENTS.md) load from the immutableimage; the model comes from pi's built-in `zai` provider; the bash tool runs in the worktree with `WILL_*` env injected viaspawnHook. The default system prompt is fully replaced by persona + agenerated tool registry rendered from the live session tools.(persona, skills, and AGENTS.md) load from the immutable image; project-localPi settings are excluded. The model comes from pi's built-in catalog andbuilt-in `zai` provider. Every filesystem tool targets the editable worktree;bash also receives `WILL_*` env through `spawnHook`. The default system promptis exactly the lexically ordered personality. Pi supplies authoritative toolschemas through its native tool channel.package.json
Modified+3 / −3 text lines
"check": "biome check src scripts web deploy rolldown.config.ts playwright.config.ts package.json tsconfig.json && tsc --noEmit", "format": "biome format --write src scripts web deploy rolldown.config.ts playwright.config.ts", "build": "rolldown -c rolldown.config.ts && node scripts/copy-web.mjs && node scripts/render-docs.mjs",persona/40-conduct.md
Modified+5 / −3 text lines
`recall` over assumptions about the past. Your full past is queryable via therecall tool or the service; compaction only compresses context, neverdestroys memory.`recall` over assumptions about the past. Your visible past is queryable viathe recall tool or the service; compaction does not delete persisted memory.An interrupted turn may have left partial side effects. Inspect current statebefore continuing or abandoning it; never blindly replay actions.spec.html
Modified+9 / −11 text lines
<dd>Persona, skills, prompt templates, AGENTS.md files, models configuration, and generated prompt content shipped in the immutable agent image.</dd> <dd>Persona, skills, and AGENTS.md files shipped in the immutable agent image.</dd> pi's default system prompt is intentionally replaced. The replacement is assembled at agent-process start from: pi's default system prompt is intentionally replaced at agent-process start. </p> <p> The replacement is exactly the lexically ordered <code>persona/*.md</code> content. Tool names, descriptions, and schemas enter through pi's native tool definitions rather than duplicated prompt prose. Wakes carry only live facts and event payloads; enduring behavior belongs to personality and conditional procedures belong to skills. <ol> <li>Lexically ordered <code>persona/*.md</code>.</li> <li>A generated operational core derived from the actual registered tool names, descriptions, and schemas.</li> <li>Concise generated rules for skill discovery, context loading, tool use, and the external deployment boundary.</li> </ol> pi's automatic project-context and skill injection remains authoritative and must occur exactly once. <tr><td><code>persona/30-world.md</code></td><td>Internet, friends, Git, Luci, registry, deployment platform, and credential boundaries</td></tr> <tr><td><code>persona/40-conduct.md</code></td><td>Testing, mutation discipline, progressive context loading, recall, and compaction hygiene</td></tr> <tr><td><code>.pi/skills/</code></td><td>Arch, mise, Podman, SQLite, Git release, Telegram, Luci, pi SDK, ZAI capabilities, context, and media operations</td></tr> <tr><td><code>.pi/prompts/</code></td><td>Chat, heartbeat, deployment failure, CI failure, and interrupted-turn recovery wake templates</td></tr> <tr><td><code>AGENTS.md</code></td><td>Root ontology, boundaries, quality gates, and nested-context rule</td></tr>src/agent/config.test.ts
Modified+13 / −1 text lines
import { resolveSessionMode } from './config.ts'import { loadAgentConfig, resolveSessionMode } from './config.ts'test('thinking level defaults to medium', () => { assert.equal(loadAgentConfig({}).zai.thinkingLevel, 'medium')})test('ZAI_THINKING_LEVEL overrides the default', () => { assert.equal(loadAgentConfig({ ZAI_THINKING_LEVEL: 'max' }).zai.thinkingLevel, 'max')})test('unknown ZAI_THINKING_LEVEL fails loudly', () => { assert.throws(() => loadAgentConfig({ ZAI_THINKING_LEVEL: 'ultra' }), /ZAI_THINKING_LEVEL/)})src/agent/config.ts
Modified+25 / −1 text lines
/** multimodal coding model used by zai_analyze_media (pinned deployment config) */ /** multimodal coding model used by zai_analyze_media and the resident session (pinned deployment config) *//** Pi thinking levels; the model clamps unsupported ones (see thinkingLevelMap) */export type ThinkingLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'const THINKING_LEVELS: readonly ThinkingLevel[] = [ 'off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max',]function thinkingLevelFromEnv(env: NodeJS.ProcessEnv): ThinkingLevel { const raw = env.ZAI_THINKING_LEVEL ?? 'medium' if (!(THINKING_LEVELS as readonly string[]).includes(raw)) { throw new Error(`ZAI_THINKING_LEVEL must be one of ${THINKING_LEVELS.join('|')}; got '${raw}'`) } return raw as ThinkingLevel} thinkingLevel: thinkingLevelFromEnv(env),src/agent/engine.test.ts
Modified+15 / −17 text lines
test('system prompt: persona order, generated tool registry, boundary rule', async () => {test('system prompt is exactly the lexically ordered personality', async () => { const prompt = await buildSystemPrompt(dir, [ { name: 'bash', description: 'Execute bash commands in the worktree' }, { name: 'chat_send', description: 'Send a message to the group.\nSecond line ignored.' }, ]) const identityIdx = prompt.indexOf('I am will.') const bodyIdx = prompt.indexOf('I live in a pod.') const toolsIdx = prompt.indexOf('<available_tools>') assert.ok(identityIdx < bodyIdx && bodyIdx < toolsIdx) assert.match(prompt, /- bash: Execute bash commands in the worktree/) assert.match(prompt, /- chat_send: Send a message to the group\./) assert.match(prompt, /Registry credentials are absent/) assert.match(prompt, /progressive disclosure/) assert.match(hb, /<heartbeat_wake>/) assert.match(df, /revert or fix commit/) assert.doesNotMatch(df, /diagnose|push|fix commit/i)src/agent/engine.ts
Modified+1 / −1 text lines
src/agent/main.ts
Modified+21 / −22 text lines
import { syncWorktree } from './worktree.ts' const toolSummaries = customTools.map((t) => ({ name: t.name, description: t.description ?? '' })) const systemPrompt = await buildSystemPrompt(join(config.resourceDir, 'persona'), [ ...builtinToolSummaries(), ...toolSummaries, ]) const systemPrompt = await buildSystemPrompt(join(config.resourceDir, 'persona')) if (e.type === 'agent_end') { // Derived cost-view rows: one per (wake, provider/model) (spec: tokens // and projected cost surface). Raw events stay untouched. for (const usage of sumAssistantUsage((event as { messages?: unknown }).messages)) { void audit('turn_usage', usage).then(() => undefined) } } let sessionToolSummaries = toolSummaries sessionToolSummaries = pi.toolSummaries void sessionToolSummaries const worktreeStatus = await syncWorktree(config.workDir, config.vcs.gitUrl, config.vcs.branch) worktreeStatus = await syncWorktree(config.workDir, config.vcs.gitUrl, config.vcs.branch)function builtinToolSummaries(): { name: string; description: string }[] { return [ { name: 'read', description: 'Read file contents (images supported)' }, { name: 'bash', description: 'Execute bash commands in the worktree' }, { name: 'edit', description: 'Precise text replacement edits in files' }, { name: 'write', description: 'Write or overwrite files' }, { name: 'grep', description: 'Search file contents by pattern' }, { name: 'find', description: 'Find files by name pattern' }, { name: 'ls', description: 'List directory contents' }, ]}src/agent/pi-session.test.ts
Addednew file mode 100644+30 / −0 text lines
import assert from 'node:assert/strict'import { mkdtemp, readFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'import { test } from 'node:test'import { createWorktreeTools } from './pi-session.ts'import type { Tool } from './tools-shape.ts'test('all coding tools are bound to the editable worktree', async () => { const workDir = await mkdtemp(join(tmpdir(), 'will-tools-')) const tools = createWorktreeTools(workDir, {}) as Tool[] assert.deepEqual(tools.map((tool) => tool.name).sort(), [ 'bash', 'edit', 'find', 'grep', 'ls', 'read', 'write', ]) const write = tools.find((tool) => tool.name === 'write') assert.ok(write) await write.execute( 'write-probe', { path: 'probe.txt', content: 'inside genome\n' }, new AbortController().signal, ) assert.equal(await readFile(join(workDir, 'probe.txt'), 'utf8'), 'inside genome\n')})src/agent/pi-session.ts
Modified+26 / −19 text lines
export function createWorktreeTools(workDir: string, willEnv: Record<string, string>) { return [ ...createCodingTools(workDir, { bash: { spawnHook: (context) => ({ ...context, env: { ...context.env, ...willEnv } }), }, }), createGrepTool(workDir), createFindTool(workDir), createLsTool(workDir), ]} const modelRuntime = await ModelRuntime.create({ modelsPath: join(cfg.resourceDir, 'models.json'), }) const modelRuntime = await ModelRuntime.create({ modelsPath: null }) if (!model) throw new Error(`zai model not found in models.json (${cfg.zai.analysisModel})`) if (!model) throw new Error(`zai model absent from built-in catalog (${cfg.zai.analysisModel})`) thinkingLevel: cfg.zai.thinkingLevel, customTools: [bashTool, ...opts.customTools], customTools: [...worktreeTools, ...opts.customTools],src/agent/prompt.ts
Modified+10 / −53 text lines
export function renderToolRegistry(tools: ToolSummary[]): string { const lines = tools .slice() .sort((a, b) => a.name.localeCompare(b.name)) .map((t) => `- ${t.name}: ${t.description.split('\n')[0]?.trim() ?? ''}`) return `<available_tools>\n${lines.join('\n')}\n</available_tools>`}const OPERATIONAL_RULES = `<operational_rules>- Tools are listed above with their real names and schemas; the registry is generated from the live session, never hand-maintained.- Skills are discovered automatically; read a skill's SKILL.md only when its description matches the task (progressive disclosure).- Before editing code under a subdirectory, read the nearest AGENTS.md in that subtree; the root AGENTS.md is already in context.- All chat, audit, and deployment history is queryable through the recall tool; compaction never destroys information.- Registry credentials are absent from this body: image releases flow only through CI on git push.- The deployment platform owns probation and rollback; explicit image rollback is available via the deployment_rollback tool restricted to the previous revision.- The worktree is the editing source; operational persona, skills, and prompts come from the deployed image.</operational_rules>`export async function buildSystemPrompt(personaDir: string, tools: ToolSummary[]): Promise<string> { const persona = await readPersona(personaDir) return `${persona.trim()}${renderToolRegistry(tools)}${OPERATIONAL_RULES}` return `<boot_context>The agent process just started: deployment replaced or restarted the body.Reorient before acting: check pending wakes, service health, and the last audit events.</boot_context>` return '<boot_context event="agent_process_started"/>' .map((m) => `- ${m.digest} (${m.type}); analyze with a media tool when relevant`) .map((m) => `- ${m.digest} (${m.type})`)</chat_wake>` return `${head}${factsBlock}<heartbeat_wake>Hourly heartbeat. Review: recent audit events for errors, deployment history for failures,storage state, unpushed worktree commits, and anything you promised to follow up on.Act on findings; otherwise stay quiet unless something deserves sharing.</heartbeat_wake>` return `${head}${factsBlock}\n\n<heartbeat_wake/>`logs: ${p.url ?? 'unknown'}Inspect current state with recall and the filesystem before continuing; do not blindly replay.src/agent/runtime.int.test.ts
Modified+56 / −9 text lines
import { syncWorktree } from './worktree.ts'import { readWorktreeState, syncWorktree } from './worktree.ts' await exec('git', ['commit', '-m', 'one', '--author', 't <t@t>'], { cwd: seed }) await exec('git', [...GIT_IDENTITY, 'commit', '-m', 'one', '--author', 't <t@t>'], { cwd: seed }) await exec('git', ['commit', '-am', 'two', '--author', 't <t@t>'], { cwd: seed }) await exec('git', [...GIT_IDENTITY, 'commit', '-am', 'two', '--author', 't <t@t>'], { cwd: seed }) await exec('git', ['commit', '-am', 'three', '--author', 't <t@t>'], { cwd: seed }) await exec('git', ['commit', '-m', 'local', '--author', 't <t@t>'], { cwd: work })test('readWorktreeState: fresh head and dirty flag without fetch or merge', async () => { const dir = await mkdtemp(join(tmpdir(), 'wt-read-')) const remote = join(dir, 'origin.git') const work = join(dir, 'work') await exec('git', ['init', '--bare', '-b', 'trunk', remote]) const seed = join(dir, 'seed') await exec('git', ['clone', remote, seed]) await writeFile(join(seed, 'a.txt'), 'one\n') await exec('git', ['add', '.'], { cwd: seed }) await exec('git', [...GIT_IDENTITY, 'commit', '-m', 'one', '--author', 't <t@t>'], { cwd: seed }) await exec('git', ['push', 'origin', 'trunk'], { cwd: seed }) await exec('git', ['clone', '--quiet', remote, work]) const head = () => exec('git', ['rev-parse', 'HEAD'], { cwd: work }) const s1 = await readWorktreeState(work) assert.equal(s1.head, (await head()).stdout.trim()) assert.equal(s1.dirty, false) // a local commit moves HEAD; the read reports it without merging origin await writeFile(join(work, 'b.txt'), 'local\n') await exec('git', ['add', '.'], { cwd: work }) await exec('git', [...GIT_IDENTITY, 'commit', '-m', 'local', '--author', 't <t@t>'], { cwd: work, }) const s2 = await readWorktreeState(work) assert.equal(s2.head, (await head()).stdout.trim()) assert.notEqual(s2.head, s1.head) // uncommitted work is reported dirty await writeFile(join(work, 'c.txt'), 'uncommitted\n') const s3 = await readWorktreeState(work) assert.equal(s3.dirty, true) // missing worktree: error reported, never throws const s4 = await readWorktreeState(join(dir, 'missing')) assert.ok(s4.error) assert.equal(s4.head, undefined)})src/agent/usage.test.ts
Addednew file mode 100644+49 / −0 text lines
import assert from 'node:assert/strict'import { test } from 'node:test'import { sumAssistantUsage } from './usage.ts'const assistant = (model: string, usage: object, provider = 'zai') => ({ role: 'assistant', provider, model, usage,})test('sums usage across assistant messages of one wake', () => { const rows = sumAssistantUsage([ assistant('glm-5.3-flash', { input: 100, output: 50, cacheRead: 10, cacheWrite: 5 }), { role: 'user', content: 'hi' }, assistant('glm-5.3-flash', { input: 200, output: 20 }), ]) assert.deepEqual(rows, [ { provider: 'zai', model: 'glm-5.3-flash', input: 300, output: 70, cacheRead: 10, cacheWrite: 5, responses: 2, }, ])})test('splits by provider/model and tolerates junk', () => { const rows = sumAssistantUsage([ assistant('glm-5.3-flash', { input: 1 }), assistant('glm-5.3-hig', { input: 2 }, 'cloudflare-ai-gateway'), assistant('glm-5.3-flash', { input: 'junk', output: null }), { role: 'assistant', model: 'no-usage' }, 'garbage', 42, ]) assert.equal(rows.length, 2) const flash = rows.find((r) => r.model === 'glm-5.3-flash') assert.equal(flash?.input, 1) assert.equal(flash?.responses, 2)})test('non-array input yields no rows', () => { assert.deepEqual(sumAssistantUsage(undefined), []) assert.deepEqual(sumAssistantUsage({ messages: [] }), [])})src/agent/usage.ts
Addednew file mode 100644+62 / −0 text lines
/** * Turn usage extraction (cost view spec): pi agent_end events carry every * message; assistant messages embed provider usage. One derived audit event * per (wake, provider/model) so the service can aggregate tokens and cost. */export interface TurnUsage { provider: string model: string input: number output: number cacheRead: number cacheWrite: number /** assistant responses aggregated into this row (one model call each) */ responses: number}interface UsageLike { input?: unknown output?: unknown cacheRead?: unknown cacheWrite?: unknown}interface AssistantLike { role?: unknown model?: unknown provider?: unknown usage?: unknown}const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)export function sumAssistantUsage(messages: unknown): TurnUsage[] { if (!Array.isArray(messages)) return [] const byKey = new Map<string, TurnUsage>() for (const message of messages) { const m = message as AssistantLike if (m?.role !== 'assistant') continue if (typeof m.usage !== 'object' || m.usage === null) continue const u = m.usage as UsageLike const model = typeof m.model === 'string' ? m.model : 'unknown' const provider = typeof m.provider === 'string' ? m.provider : 'unknown' const key = `${provider}/${model}` const agg = byKey.get(key) ?? { provider, model, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, responses: 0, } agg.input += num(u.input) agg.output += num(u.output) agg.cacheRead += num(u.cacheRead) agg.cacheWrite += num(u.cacheWrite) agg.responses += 1 byKey.set(key, agg) } return [...byKey.values()]}src/agent/worktree.ts
Modified+23 / −0 text lines
/** * Cheap local read of the current worktree state (rev-parse + status; no * fetch, no merge). Used to refresh wake facts between boot syncs so they * never report a stale HEAD. Never throws; failures land in `error`. */export async function readWorktreeState(workDir: string): Promise<WorktreeStatus> { const status: WorktreeStatus = { dirty: false, diverged: false, fastForwarded: false, cloned: false, } try { const git = (...args: string[]) => exec('git', args, { cwd: workDir, maxBuffer: 10 << 20 }) status.head = (await git('rev-parse', 'HEAD')).stdout.trim() const dirty = await git('status', '--porcelain') status.dirty = dirty.stdout.trim().length > 0 } catch (err) { status.error = err instanceof Error ? err.message : String(err) } return status}src/service/main.int.test.ts
Modified+57 / −2 text lines
test('usage view aggregates turn_usage rows into daily cost', async () => { const { service, base, internal } = await startTestService() try { const ingest = (events: unknown[]) => fetch(internal('/v1/audit/ingest'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ events }), }) const today = new Date().toISOString().slice(0, 11) const res = await ingest([ { id: 'u1', ts: `${today}00:00:00Z`, kind: 'turn_usage', payload: { provider: 'zai', model: 'glm-5.3-flash', input: 2_000_000, output: 100_000, cacheRead: 1_000_000, cacheWrite: 0, responses: 3, }, }, { id: 'u2', ts: `${today}09:00:00Z`, kind: 'turn_usage', payload: { provider: 'other', model: 'mystery', input: 5, responses: 1 }, }, { id: 'u3', ts: new Date().toISOString(), kind: 'agent_end', payload: {} }, ]) assert.equal(res.status, 200) const page = await fetch(base('/api/usage')) assert.equal(page.status, 200) const report = (await page.json()) as { days: { date: string; input: number; responses: number; costUsd: number | null }[] totals: { input: number; costUsd: number | null; responses: number } projection: { todayUsd: number | null; projectedEomUsd: number | null } } assert.equal(report.days.length, 1) assert.equal(report.days[0]?.input, 2_000_005) assert.equal(report.days[0]?.responses, 4) // one unpriced model among the day's rows => cost withheld for that day assert.equal(report.days[0]?.costUsd, null) assert.equal(report.projection.projectedEomUsd, null) } finally { await service.close() }})src/service/main.ts
Modified+3 / −0 text lines
src/service/ops.int.test.ts
Modified+144 / −0 text lines
test('recall searches beyond the newest page in hot data and archives', async () => { const { ops } = await freshOps() const recent = Array.from({ length: 20 }, (_, i) => audit(`noise-${i}`, `2026-09-${String(i + 1).padStart(2, '0')}T00:00:00Z`), ) ops.ingestAudit([ audit('cold-needle', '2026-01-01T00:00:00Z', 'forgotten-audit'), audit('hot-needle', '2026-08-01T00:00:00Z', 'remembered-audit'), ...recent, ]) ops.ingestChat([ { id: 'chat-cold-needle', chatId: -100, messageId: 1, direction: 'in', ts: '2024-01-01T00:00:00Z', senderName: 'old friend', text: 'remember this phrase', }, ...recent.map((_, i) => ({ id: `chat-noise-${i}`, chatId: -100, messageId: i + 2, direction: 'in' as const, ts: `2026-08-${String(i + 1).padStart(2, '0')}T00:00:00Z`, text: 'routine chatter', })), ]) const hot = await ops.recall({ kind: 'audit', q: 'remembered-audit', limit: 2 }) assert.deepEqual( (hot.rows as { id: string }[]).map((r) => r.id), ['hot-needle'], ) await ops.archiveCycle() const coldAudit = await ops.recall({ kind: 'audit', q: 'forgotten-audit', limit: 2 }) assert.deepEqual( (coldAudit.rows as { id: string }[]).map((r) => r.id), ['cold-needle'], ) assert.equal(coldAudit.cold, true) const coldChat = await ops.recall({ kind: 'chat', q: 'remember this phrase', limit: 2 }) assert.deepEqual( (coldChat.rows as { id: string }[]).map((r) => r.id), ['chat-cold-needle'], ) assert.equal(coldChat.cold, true)})test('recall orders overlapping archives and late hot rows globally', async () => { const { ops } = await freshOps() ops.ingestAudit([ audit('jan-01', '2026-01-01T00:00:00Z', 'shared-needle'), audit('jan-30', '2026-01-30T00:00:00Z', 'shared-needle'), ]) await ops.archiveCycle() ops.ingestAudit([audit('jan-15', '2026-01-15T00:00:00Z', 'shared-needle')]) await ops.archiveCycle() ops.ingestAudit([audit('late-jan-02', '2026-01-02T00:00:00Z', 'shared-needle')]) const result = await ops.recall({ kind: 'audit', q: 'shared-needle', limit: 1 }) assert.equal((result.rows[0] as { id: string }).id, 'jan-30') assert.equal(result.cold, true)})test('recall has identical Unicode case matching before and after archival', async () => { const { ops } = await freshOps() ops.ingestAudit([ audit('kind-unicode', '2026-01-01T00:00:00Z', 'ÄPFEL'), audit('ÖL', '2026-01-02T00:00:00Z'), ]) ops.ingestChat([ { id: 'chat-unicode', chatId: -100, messageId: 1, direction: 'in', ts: '2024-01-01T00:00:00Z', senderName: 'ÄNNE', text: 'GRÜSSE', }, ]) for (const query of [ { kind: 'audit' as const, q: 'äpfel', id: 'kind-unicode' }, { kind: 'audit' as const, q: 'öl', id: 'ÖL' }, { kind: 'chat' as const, q: 'änne', id: 'chat-unicode' }, { kind: 'chat' as const, q: 'grüsse', id: 'chat-unicode' }, ]) { const hot = await ops.recall({ kind: query.kind, q: query.q, limit: 2 }) assert.equal((hot.rows[0] as { id: string }).id, query.id) } await ops.archiveCycle() for (const query of [ { kind: 'audit' as const, q: 'äpfel', id: 'kind-unicode' }, { kind: 'audit' as const, q: 'öl', id: 'ÖL' }, { kind: 'chat' as const, q: 'änne', id: 'chat-unicode' }, { kind: 'chat' as const, q: 'grüsse', id: 'chat-unicode' }, ]) { const cold = await ops.recall({ kind: query.kind, q: query.q, limit: 2 }) assert.equal((cold.rows[0] as { id: string }).id, query.id) assert.equal(cold.cold, true) }})test('recall tie ordering is limit-prefix consistent before and after archival', async () => { const { ops } = await freshOps() const ts = '2026-01-01T00:00:00Z' ops.ingestAudit([audit('z', ts, 'tie'), audit('a', ts, 'tie')]) ops.ingestChat([ { id: 'z', chatId: -100, messageId: 1, direction: 'in', ts, text: 'tie' }, { id: 'a', chatId: -100, messageId: 2, direction: 'in', ts, text: 'tie' }, ]) const assertOrder = async (kind: 'audit' | 'chat') => { const one = await ops.recall({ kind, q: 'tie', limit: 1 }) const two = await ops.recall({ kind, q: 'tie', limit: 2 }) assert.deepEqual( (one.rows as { id: string }[]).map((r) => r.id), ['z'], ) assert.deepEqual( (two.rows as { id: string }[]).map((r) => r.id), ['z', 'a'], ) } await assertOrder('audit') await assertOrder('chat') await ops.archiveCycle() await assertOrder('audit') await assertOrder('chat')})src/service/ops.ts
Modified+149 / −28 text lines
import { aggregateTurnUsage, type UsageReport } from './usage.ts' matches: (r: ArchivedRecord) => boolean = () => true, const overlapping = segmentsOverlapping(segments, until ? { until } : {}).sort((a, b) => const overlapping = segmentsOverlapping(segments, range).sort((a, b) => const records = await readSegment(seg.zstPath, () => true, BATCH_LIMIT) const records = await readSegment(seg.zstPath, matches, BATCH_LIMIT) const coldSearch = async <T extends { id: string; ts: string }>( kind: 'audit' | 'chat', range: { since?: string; until?: string }, seen: Set<string>, mapRecord: (r: ArchivedRecord) => T, matches: (r: ArchivedRecord) => boolean, ): Promise<T[]> => { const segments = (await listSidecars(dirs.archiveDir, kind)).map((s) => ({ ...s.sidecar, zstPath: s.zstPath, })) const out: T[] = [] for (const seg of segmentsOverlapping(segments, range)) { for (const record of await readSegment(seg.zstPath, matches, BATCH_LIMIT)) { if (seen.has(record.id)) continue seen.add(record.id) out.push(mapRecord(record)) } } return out.sort((a, b) => b.ts.localeCompare(a.ts) || b.id.localeCompare(a.id)) } const newestFirst = (a: { id: string; ts: string }, b: { id: string; ts: string }) => b.ts.localeCompare(a.ts) || Buffer.compare(Buffer.from(b.id), Buffer.from(a.id)) db.function('unicode_lower', { deterministic: true }, (value) => String(value ?? '').toLowerCase(), ) const q = query.q?.toLowerCase() const page = await ops.timeline({ limit: limit * 2 }) const rows = page.rows.filter( (r) => (!query.since || r.ts >= query.since) && (!query.until || r.ts <= query.until) && (!q || r.kind.toLowerCase().includes(q) || JSON.stringify(r.payload).toLowerCase().includes(q)), const hot = ( db .prepare( `SELECT * FROM audit_events WHERE (? IS NULL OR ts >= ?) AND (? IS NULL OR ts <= ?) AND (? IS NULL OR instr(unicode_lower(kind), ?) > 0 OR instr(unicode_lower(payload), ?) > 0) ORDER BY ts DESC, id DESC LIMIT ?`, ) .all( query.since ?? null, query.since ?? null, query.until ?? null, query.until ?? null, q ?? null, q ?? null, q ?? null, limit, ) as unknown as AuditRowDb[] ).map((r) => auditDbToRow(r)) const cold = await coldSearch<TimelineRow>( 'audit', range, new Set(hot.map((r) => r.id)), (r) => { const rec = r.record as { kind: string sessionId?: string provenance?: TimelineRow['provenance'] payload?: unknown } return { id: r.id, ts: r.ts, kind: rec.kind, sessionId: rec.sessionId, provenance: rec.provenance, payload: rec.payload, archived: true, } satisfies TimelineRow }, (r) => { const rec = r.record as { kind: string; payload?: unknown } return ( (!q || rec.kind.toLowerCase().includes(q) || JSON.stringify(rec.payload ?? null) .toLowerCase() .includes(q)) && (!query.since || r.ts >= query.since) && (!query.until || r.ts <= query.until) ) }, return { rows: rows.slice(0, limit), cold: page.cold } const page = await ops.chatPage( query.until === undefined ? { limit: limit * 2 } : { limit: limit * 2, before: query.until }, const hidden = hiddenMessageIds() const hot = ( db .prepare( `SELECT * FROM chat_messages WHERE (? IS NULL OR ts >= ?) AND (? IS NULL OR ts <= ?) AND (? IS NULL OR instr(unicode_lower(text), ?) > 0 OR instr(unicode_lower(sender_name), ?) > 0) AND NOT EXISTS ( SELECT 1 FROM tombstones WHERE tombstones.message_id = chat_messages.message_id ) ORDER BY ts DESC, id DESC LIMIT ?`, ) .all( query.since ?? null, query.since ?? null, query.until ?? null, query.until ?? null, q ?? null, q ?? null, q ?? null, limit, ) as unknown as ChatRowDb[] ).map((r) => chatDbToRow(r, false)) const cold = await coldSearch<ChatViewRow>( 'chat', range, new Set(hot.map((r) => r.id)), (r) => ({ ...(r.record as ChatViewRow), archived: true, hidden: false }), (r) => { const rec = r.record as ChatViewRow return ( !hidden.has(rec.messageId) && (!q || (rec.text ?? '').toLowerCase().includes(q) || (rec.senderName ?? '').toLowerCase().includes(q)) && (!query.since || r.ts >= query.since) && (!query.until || r.ts <= query.until) ) }, async usage(): Promise<UsageReport> { const rows = db .prepare("SELECT ts, payload FROM audit_events WHERE kind = 'turn_usage' ORDER BY ts") .all() as unknown as { ts: string; payload: string | null }[] return aggregateTurnUsage( rows.map((r) => ({ ts: r.ts, payload: r.payload === null ? null : (safeParse(r.payload) ?? null), })), clock.now(), ) },src/service/usage.test.ts
Addednew file mode 100644+82 / −0 text lines
import assert from 'node:assert/strict'import { test } from 'node:test'import { aggregateTurnUsage, projectUsage } from './usage.ts'const row = (ts: string, over: object = {}) => ({ ts, payload: { provider: 'zai', model: 'glm-5.3-flash', input: 1_000_000, output: 0, cacheRead: 0, cacheWrite: 0, responses: 1, ...over, },})test('cost uses the price table per MTok', () => { const report = aggregateTurnUsage([row('2026-09-21T10:00:00Z')], new Date('2026-09-21T18:00:00Z')) // 1M input tokens at $0.15/MTok assert.ok(Math.abs((report.days[0]?.costUsd ?? 0) - 0.15) < 1e-6) assert.ok(Math.abs((report.totals.costUsd ?? 0) - 0.15) < 1e-6)})test('unknown model keeps tokens but marks cost unavailable', () => { const report = aggregateTurnUsage( [row('2026-09-21T10:00:00Z', { provider: 'x', model: 'y' })], new Date('2026-09-21T18:00:00Z'), ) assert.equal(report.days[0]?.input, 1_000_000) assert.equal(report.days[0]?.costUsd, null) assert.equal(report.totals.costUsd, null) assert.equal(report.projection.projectedEomUsd, null)})test('days are grouped by UTC date and sorted ascending', () => { const report = aggregateTurnUsage( [row('2026-09-21T23:00:00Z'), row('2026-09-20T01:00:00Z'), row('2026-09-21T01:00:00Z')], new Date('2026-09-21T18:00:00Z'), ) assert.deepEqual( report.days.map((d) => d.date), ['2026-09-20', '2026-09-21'], ) assert.equal(report.days[1]?.responses, 2)})test('projection extrapolates today across the remaining month', () => { // at 18:00 UTC, 75% of the day elapsed; 1M input/day = $0.15/day rate const days = [ { date: '2026-09-20', input: 1e6, output: 0, cacheRead: 0, cacheWrite: 0, responses: 1, costUsd: 0.15, }, { date: '2026-09-21', input: 1e6, output: 0, cacheRead: 0, cacheWrite: 0, responses: 1, costUsd: 0.15, }, ] const p = projectUsage(days, new Date('2026-09-21T18:00:00Z')) assert.ok(Math.abs((p.todayUsd ?? 0) - 0.2) < 1e-9) // 0.15 / 0.75 assert.ok(Math.abs((p.mtdUsd ?? 0) - 0.3) < 1e-9) // 9.25 days remain until Oct 1 => 0.3 + 0.2 * 9.25 assert.ok(Math.abs((p.projectedEomUsd ?? 0) - 2.15) < 1e-9)})test('projection is null without a priced day today', () => { const p = projectUsage([], new Date('2026-09-21T18:00:00Z')) assert.equal(p.todayUsd, null) assert.equal(p.projectedEomUsd, null)})src/service/usage.ts
Addednew file mode 100644+155 / −0 text lines
/** * Cost view math (read-only surface): prices come from the pi model catalog * (zai coding endpoint) and every function here is pure so the projection is * unit-testable without a database or a live clock. */export interface TurnUsageRow { ts: string payload: unknown}export interface DayUsage { date: string input: number output: number cacheRead: number cacheWrite: number responses: number /** USD; null when any contributing row used a model without a price entry */ costUsd: number | null}export interface UsageProjection { todayUsd: number | null mtdUsd: number | null projectedEomUsd: number | null}export interface UsageReport { days: DayUsage[] totals: Omit<DayUsage, 'date'> projection: UsageProjection}/** USD per MTok (input, output, cacheRead); cacheWrite unpriced (unbilled). */const PRICES_PER_MTOK: Record<string, { input: number; output: number; cacheRead: number }> = { 'zai/glm-5.3-flash': { input: 0.15, output: 0.5, cacheRead: 0.03 },}interface UsagePayload { provider?: unknown model?: unknown input?: unknown output?: unknown cacheRead?: unknown cacheWrite?: unknown responses?: unknown}const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)function costOfRow(payload: unknown): number | null { const p = payload as UsagePayload const provider = typeof p?.provider === 'string' ? p.provider : 'unknown' const model = typeof p?.model === 'string' ? p.model : 'unknown' const price = PRICES_PER_MTOK[`${provider}/${model}`] if (price === undefined) return null return ( (num(p?.input) * price.input + num(p?.output) * price.output + num(p?.cacheRead) * price.cacheRead) / 1e6 )}const dayKey = (ts: string): string => ts.slice(0, 10)const HOUR_MS = 3_600_000/** Floor on elapsed-day fraction so a just-past-midnight spike cannot explode the rate */const MIN_ELAPSED_FRACTION = 0.5 / 24export function projectUsage(days: DayUsage[], now: Date): UsageProjection { const todayKey = now.toISOString().slice(0, 10) const today = days.find((d) => d.date === todayKey) if (today === undefined || today.costUsd === null) { return { todayUsd: null, mtdUsd: null, projectedEomUsd: null } } const midnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) const elapsed = Math.max((now.getTime() - midnight) / (24 * HOUR_MS), MIN_ELAPSED_FRACTION) const todayRate = today.costUsd / elapsed const month = todayKey.slice(0, 7) const mtd = days .filter((d) => d.date.slice(0, 7) === month && d.costUsd !== null) .reduce((sum, d) => sum + (d.costUsd ?? 0), 0) const monthEnd = Date.UTC( now.getUTCFullYear(), now.getUTCMonth() + 1, 1, // first day of next month == end of this one ) const projectedEom = mtd + todayRate * ((monthEnd - now.getTime()) / (24 * HOUR_MS)) return { todayUsd: todayRate, mtdUsd: mtd, projectedEomUsd: projectedEom }}export function aggregateTurnUsage(rows: TurnUsageRow[], now: Date): UsageReport { interface Acc extends Omit<DayUsage, 'costUsd'> { priced: boolean costUsd: number } const byDay = new Map<string, Acc>() for (const row of rows) { const p = row.payload as UsagePayload const date = dayKey(typeof row.ts === 'string' ? row.ts : '') const day = byDay.get(date) ?? { date, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, responses: 0, costUsd: 0, priced: true, } day.input += num(p?.input) day.output += num(p?.output) day.cacheRead += num(p?.cacheRead) day.cacheWrite += num(p?.cacheWrite) day.responses += num(p?.responses) const cost = costOfRow(row.payload) if (cost === null) day.priced = false else day.costUsd += cost byDay.set(date, day) } const days = [...byDay.values()] .map(({ priced, ...d }) => ({ ...d, costUsd: priced ? d.costUsd : null })) .sort((a, b) => (a.date < b.date ? -1 : 1)) const totalsAcc = days.reduce( (t, d) => ({ input: t.input + d.input, output: t.output + d.output, cacheRead: t.cacheRead + d.cacheRead, cacheWrite: t.cacheWrite + d.cacheWrite, responses: t.responses + d.responses, costUsd: t.costUsd + (d.costUsd ?? 0), unpriced: t.unpriced || d.costUsd === null, }), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, responses: 0, costUsd: 0, unpriced: false, }, ) const totals: UsageReport['totals'] = { input: totalsAcc.input, output: totalsAcc.output, cacheRead: totalsAcc.cacheRead, cacheWrite: totalsAcc.cacheWrite, responses: totalsAcc.responses, costUsd: totalsAcc.unpriced ? null : totalsAcc.costUsd, } return { days, totals, projection: projectUsage(days, now) }}web/index.html
Modified+20 / −0 text lines
<h3>Tokens & cost</h3> <div id="usage-projection" aria-live="polite"></div> <div class="table-wrap"> <table id="usage-table"> <caption class="visually-hidden">Token usage and cost per day</caption> <thead> <tr> <th scope="col">Day</th> <th scope="col">In</th> <th scope="col">Out</th> <th scope="col">Cache read</th> <th scope="col">Cache write</th> <th scope="col">Responses</th> <th scope="col">Cost (USD)</th> </tr> </thead> <tbody id="usage-days"></tbody> <tfoot id="usage-totals"></tfoot> </table> </div>web/src/main.css
Modified+36 / −0 text lines
/* usage table (health tab) */.table-wrap { overflow-x: auto;}#usage-table { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums;}#usage-table th,#usage-table td { border: 1px solid var(--line); padding: 0.25rem 0.5rem; text-align: right;}#usage-table th:first-child,#usage-table td:first-child { text-align: left;}#usage-table tfoot td { font-weight: 600;}.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap;}web/src/main.ts
Modified+70 / −1 text lines
const fmtUsd = (usd: number | null): string => usd === null ? 'n/a' : usd < 0.01 && usd > 0 ? `<$0.01` : `$${usd.toFixed(2)}`const fmtTok = (n: number): string => n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(n)interface UsageReportRow { days: { date: string input: number output: number cacheRead: number cacheWrite: number responses: number costUsd: number | null }[] totals: { input: number output: number cacheRead: number cacheWrite: number responses: number costUsd: number | null } projection: { todayUsd: number | null; mtdUsd: number | null; projectedEomUsd: number | null }}async function loadUsage(): Promise<void> { const res = await fetch('/api/usage') const report = (await res.json()) as UsageReportRow const body = $('#usage-days') const foot = $('#usage-totals') body.replaceChildren() const row = (cells: string[]): HTMLTableRowElement => { const tr = document.createElement('tr') for (const c of cells) tr.append(el('td', {}, text(c))) return tr } for (const d of [...report.days].reverse()) { body.append( row([ d.date, fmtTok(d.input), fmtTok(d.output), fmtTok(d.cacheRead), fmtTok(d.cacheWrite), String(d.responses), fmtUsd(d.costUsd), ]), ) } foot.replaceChildren( row([ 'total', fmtTok(report.totals.input), fmtTok(report.totals.output), fmtTok(report.totals.cacheRead), fmtTok(report.totals.cacheWrite), String(report.totals.responses), fmtUsd(report.totals.costUsd), ]), ) const p = report.projection $('#usage-projection').replaceChildren( text( `today ${fmtUsd(p.todayUsd)} · month-to-date ${fmtUsd(p.mtdUsd)} · projected end of month ${fmtUsd(p.projectedEomUsd)}`, ), )}web/tests/phenotype.spec.ts
Modified+10 / −3 text lines
service = spawn(process.execPath, ['--experimental-strip-types', join(here, '..', 'src', 'service', 'main.ts')], {