chompyy 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -3
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/dist/appstate.js +81 -5
- package/dist/away.js +93 -16
- package/dist/blueprint.js +102 -7
- package/dist/board.js +110 -12
- package/dist/catalog.js +81 -0
- package/dist/cli.js +444 -56
- package/dist/coldstart.js +2 -1
- package/dist/config.js +7 -7
- package/dist/deps.js +124 -0
- package/dist/detect.js +511 -0
- package/dist/dream.js +422 -0
- package/dist/duration.js +3 -3
- package/dist/gate.js +11 -5
- package/dist/live.js +255 -0
- package/dist/livequota.js +27 -4
- package/dist/macapp.js +25 -2
- package/dist/pacing.js +5 -0
- package/dist/permissions.js +106 -0
- package/dist/picture.js +13 -6
- package/dist/picturetype.js +208 -0
- package/dist/preflight.js +168 -0
- package/dist/premise.js +122 -0
- package/dist/projects.js +3 -2
- package/dist/refresh.js +290 -0
- package/dist/report.js +3 -0
- package/dist/review.js +66 -9
- package/dist/runner.js +56 -8
- package/dist/taste.js +34 -13
- package/dist/tokens.js +75 -0
- package/dist/tokenstore.js +61 -0
- package/dist/trace.js +284 -0
- package/dist/triggers.js +16 -5
- package/dist/usage.js +467 -0
- package/dist/vendor/codeburn/prices.js +45 -0
- package/dist/verify.js +24 -5
- package/dist/verifycard.js +146 -0
- package/dist/workspace.js +132 -18
- package/package.json +3 -2
package/dist/taste.js
CHANGED
|
@@ -115,13 +115,15 @@ export function signalWeight(s) {
|
|
|
115
115
|
return Array.isArray(s.raw.toFive) && s.raw.toFive.length ? 3 : s.raw.reason ? 2 : 1;
|
|
116
116
|
if (s.kind === 'answer')
|
|
117
117
|
return 1;
|
|
118
|
+
if (s.kind === 'chat')
|
|
119
|
+
return 2;
|
|
118
120
|
return 0;
|
|
119
121
|
}
|
|
120
122
|
/** One line per signal, for the distiller prompt and for "why do you think that?". */
|
|
121
123
|
export function describeSignal(s, max = 400) {
|
|
122
|
-
const cut = (v) => {
|
|
124
|
+
const cut = (v, n = max) => {
|
|
123
125
|
const t = String(v ?? '').replace(/\s+/g, ' ').trim();
|
|
124
|
-
return t.length >
|
|
126
|
+
return t.length > n ? `${t.slice(0, n - 1)}…` : t;
|
|
125
127
|
};
|
|
126
128
|
const card = s.card ? `card #${s.card} "${s.title ?? ''}"` : '';
|
|
127
129
|
switch (s.kind) {
|
|
@@ -135,6 +137,10 @@ export function describeSignal(s, max = 400) {
|
|
|
135
137
|
return `${s.raw.outcome === 'undone' ? 'undid' : 'kept'} the result of ${card}`;
|
|
136
138
|
case 'answer':
|
|
137
139
|
return `answered the questions of ${card}: "${cut(s.raw.text)}"`;
|
|
140
|
+
case 'chat': {
|
|
141
|
+
const where = String(s.raw.workspace ?? '').split('/').pop() || 'a session';
|
|
142
|
+
return `said in a session in ${where} on ${s.at.slice(0, 10)}: "${cut(s.raw.quote)}"${s.raw.why ? ` (${cut(s.raw.why, 200)})` : ''}`;
|
|
143
|
+
}
|
|
138
144
|
default:
|
|
139
145
|
return `${s.kind} ${card}`;
|
|
140
146
|
}
|
|
@@ -146,16 +152,19 @@ export function receipts(signals) {
|
|
|
146
152
|
const verb = s.kind === 'outcome' ? (s.raw.outcome === 'undone' ? 'undid' : 'kept')
|
|
147
153
|
: s.kind === 'blueprint-edit' ? 'edited the blueprint of'
|
|
148
154
|
: s.kind === 'rating' ? (Array.isArray(s.raw.toFive) && s.raw.toFive.length ? 'asked for a change on' : 'rated')
|
|
149
|
-
: s.kind === 'answer' ? 'answered' : s.kind;
|
|
155
|
+
: s.kind === 'answer' ? 'answered' : s.kind === 'chat' ? 'said it in sessions on' : s.kind;
|
|
150
156
|
const ids = groups.get(verb) ?? [];
|
|
151
|
-
|
|
152
|
-
|
|
157
|
+
const label = s.card ? `#${s.card}` : s.kind === 'chat' ? s.at.slice(5, 10) : '';
|
|
158
|
+
if (label && !ids.includes(label))
|
|
159
|
+
ids.push(label);
|
|
153
160
|
groups.set(verb, ids);
|
|
154
161
|
}
|
|
155
162
|
return [...groups].map(([verb, ids]) => `${verb} ${ids.join(', ')}`).join(' · ');
|
|
156
163
|
}
|
|
157
164
|
/** A preference needs this many separate cards before Chompyy asks (FEATURES §7: 3 confirmations). */
|
|
158
165
|
export const MIN_CARDS = 3;
|
|
166
|
+
/** …or this many separate everyday sessions where you said it (the nightly read; "a mistake made a second time"). */
|
|
167
|
+
export const MIN_SESSIONS = 2;
|
|
159
168
|
export function storePath() {
|
|
160
169
|
return homePath('preferences.json');
|
|
161
170
|
}
|
|
@@ -174,17 +183,27 @@ export function getPref(store, id) {
|
|
|
174
183
|
export function distinctCards(evidence, byId) {
|
|
175
184
|
return new Set(evidence.map((id) => byId.get(id)?.card).filter(Boolean)).size;
|
|
176
185
|
}
|
|
186
|
+
/** Separate everyday sessions behind it (chat signals from the nightly read). */
|
|
187
|
+
export function distinctSessions(evidence, byId) {
|
|
188
|
+
return new Set(evidence.map((id) => byId.get(id)).filter((s) => s?.kind === 'chat').map((s) => String(s.raw.session))).size;
|
|
189
|
+
}
|
|
190
|
+
/** Separate places it was seen: cards plus sessions. */
|
|
191
|
+
export function sightings(evidence, byId) {
|
|
192
|
+
return distinctCards(evidence, byId) + distinctSessions(evidence, byId);
|
|
193
|
+
}
|
|
177
194
|
/** Strength for ordering questions: separate cards first, then how concrete the signals are. */
|
|
178
195
|
export function strength(p, byId) {
|
|
179
196
|
const weight = p.evidence.reduce((sum, id) => sum + (byId.get(id) ? signalWeight(byId.get(id)) : 0), 0);
|
|
180
|
-
return
|
|
197
|
+
return sightings(p.evidence, byId) * 10 + weight + (p.stated ? 5 : 0);
|
|
181
198
|
}
|
|
182
199
|
/** Promote candidates with enough evidence; wake snoozed ones that gained a card. */
|
|
183
200
|
export function promote(p, byId) {
|
|
184
201
|
const cards = distinctCards(p.evidence, byId);
|
|
185
|
-
|
|
202
|
+
const sessions = distinctSessions(p.evidence, byId);
|
|
203
|
+
const enough = cards >= MIN_CARDS || sessions >= MIN_SESSIONS || cards + sessions >= MIN_CARDS || (p.stated && cards >= 1);
|
|
204
|
+
if (p.status === 'candidate' && enough)
|
|
186
205
|
p.status = 'ready';
|
|
187
|
-
if (p.status === 'snoozed' && cards > (p.snoozedAtCards ?? 0))
|
|
206
|
+
if (p.status === 'snoozed' && cards + sessions > (p.snoozedAtCards ?? 0))
|
|
188
207
|
p.status = 'ready';
|
|
189
208
|
}
|
|
190
209
|
// ---------- the distiller ----------
|
|
@@ -193,10 +212,12 @@ export function distillPrompt(signals, prefs) {
|
|
|
193
212
|
const muted = prefs.filter((p) => p.status === 'muted' || (p.status === 'retired' && !p.validFrom));
|
|
194
213
|
return `You learn one developer's taste: how they like an agent to do work. Below are signals from cards an agent
|
|
195
214
|
ran for them unattended: their ratings and reasons, "what would have made it a 5?" picks, edits they made to a
|
|
196
|
-
blueprint before approving it, results they kept or undid, and answers to the agent's questions.
|
|
215
|
+
blueprint before approving it, results they kept or undid, and answers to the agent's questions. Also things
|
|
216
|
+
they said to their AI in everyday coding sessions ("said in a session"), in their exact words, each with what
|
|
217
|
+
the nightly read thought it showed. The same point said in different sessions is one preference: cite them all.
|
|
197
218
|
|
|
198
219
|
Find preferences that would change what an agent does in a DIFFERENT task next week. A preference must be
|
|
199
|
-
supported by the signals you cite. Prefer patterns across separate cards. A reason the person wrote or a
|
|
220
|
+
supported by the signals you cite. Prefer patterns across separate cards or sessions. A reason the person wrote or a
|
|
200
221
|
change they picked counts as "stated". Write each as an instruction to an agent, at most 20 words, e.g.
|
|
201
222
|
"Don't add tests unless the blueprint asks for them". Write "noticed" as one sentence to the person saying
|
|
202
223
|
"you", with the receipts, e.g. "You undid 3 cards that added tests you didn't ask for."
|
|
@@ -309,7 +330,7 @@ export function retire(p, because, now, against = []) {
|
|
|
309
330
|
/** Signals the distiller should read: governed, about cards, not yet seen. */
|
|
310
331
|
export function newSignals(store, signals, governed) {
|
|
311
332
|
const seen = store.seenThrough ?? 0;
|
|
312
|
-
return signals.filter((s) => Number(s.id.slice(1)) > seen && s
|
|
333
|
+
return signals.filter((s) => Number(s.id.slice(1)) > seen && signalWeight(s) > 0 && (s.kind === 'chat' || (s.card && governed.has(s.card))));
|
|
313
334
|
}
|
|
314
335
|
/** Read new signals with the model and update preferences.json. Runs at most once per call; nothing to read = no model call. */
|
|
315
336
|
export async function distill(board, runner, opts) {
|
|
@@ -369,7 +390,7 @@ export function answerPreference(id, answer, now) {
|
|
|
369
390
|
}
|
|
370
391
|
else if (answer === 'not-now') {
|
|
371
392
|
p.status = 'snoozed';
|
|
372
|
-
p.snoozedAtCards =
|
|
393
|
+
p.snoozedAtCards = sightings(p.evidence, byId);
|
|
373
394
|
}
|
|
374
395
|
else {
|
|
375
396
|
p.status = 'muted';
|
|
@@ -456,7 +477,7 @@ export function formatPrefs(store, signals) {
|
|
|
456
477
|
const out = [];
|
|
457
478
|
for (const status of order) {
|
|
458
479
|
for (const p of store.prefs.filter((x) => x.status === status)) {
|
|
459
|
-
out.push(`${p.id.padEnd(4)} ${STATUS_LABEL[status].padEnd(15)} [${p.scope}] ${p.text} (${distinctCards(p.evidence, byId)} cards)`);
|
|
480
|
+
out.push(`${p.id.padEnd(4)} ${STATUS_LABEL[status].padEnd(15)} [${p.scope}] ${p.text} (${distinctCards(p.evidence, byId)} cards, ${distinctSessions(p.evidence, byId)} sessions)`);
|
|
460
481
|
}
|
|
461
482
|
}
|
|
462
483
|
out.push('', `Why: chompyy taste why <id> · answer: taste yes|not-now|never <id> · retire: taste retire <id>`);
|
package/dist/tokens.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Exact tokens per run (2026-11-19): what a card really used, from the run's own stream (the `result` event
|
|
2
|
+
// Claude Code prints at the end), instead of "5-hour % before vs after", which is whole points only, mixes in
|
|
3
|
+
// your own use at the same time, and goes blank when the window resets mid-run. Tagged per run, the way
|
|
4
|
+
// Langfuse tags each interaction; the base for honest cost estimates later.
|
|
5
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
6
|
+
/** Adds up every `result` event in a stream (a resumed or multi-result run has more than one). */
|
|
7
|
+
export class TokenTally {
|
|
8
|
+
t = null;
|
|
9
|
+
cost = 0;
|
|
10
|
+
feed(event) {
|
|
11
|
+
const e = event;
|
|
12
|
+
if (e?.type !== 'result' || !e.usage)
|
|
13
|
+
return;
|
|
14
|
+
const t = (this.t ??= { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, thinking: 0, costUsd: 0, turns: 0, models: [] });
|
|
15
|
+
const u = e.usage;
|
|
16
|
+
t.input += u.input_tokens ?? 0;
|
|
17
|
+
t.output += u.output_tokens ?? 0;
|
|
18
|
+
t.cacheRead += u.cache_read_input_tokens ?? 0;
|
|
19
|
+
t.cacheWrite += u.cache_creation_input_tokens ?? 0;
|
|
20
|
+
t.thinking += u.output_tokens_details?.thinking_tokens ?? 0;
|
|
21
|
+
this.cost += e.total_cost_usd ?? 0; // rounded once, at the end
|
|
22
|
+
t.costUsd = Math.round(this.cost * 10_000) / 10_000;
|
|
23
|
+
t.turns += e.num_turns ?? 0;
|
|
24
|
+
for (const m of Object.keys(e.modelUsage ?? {}))
|
|
25
|
+
if (!t.models.includes(m))
|
|
26
|
+
t.models.push(m);
|
|
27
|
+
}
|
|
28
|
+
total() {
|
|
29
|
+
return this.t ?? undefined;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Tokens from a saved stream log (`<run>.stream.jsonl`), e.g. for runs recorded before this existed. */
|
|
33
|
+
export function tokensFromStream(path) {
|
|
34
|
+
if (!existsSync(path))
|
|
35
|
+
return undefined;
|
|
36
|
+
const tally = new TokenTally();
|
|
37
|
+
for (const line of readFileSync(path, 'utf8').split('\n')) {
|
|
38
|
+
if (!line.includes('"type":"result"'))
|
|
39
|
+
continue;
|
|
40
|
+
try {
|
|
41
|
+
tally.feed(JSON.parse(line));
|
|
42
|
+
}
|
|
43
|
+
catch { }
|
|
44
|
+
}
|
|
45
|
+
return tally.total();
|
|
46
|
+
}
|
|
47
|
+
export const totalTokens = (t) => t.input + t.output + t.cacheRead + t.cacheWrite;
|
|
48
|
+
/** 1234 → "1.2k", 670000 → "670k", 1_500_000 → "1.5M". */
|
|
49
|
+
export function compact(n) {
|
|
50
|
+
if (n < 1000)
|
|
51
|
+
return String(n);
|
|
52
|
+
if (n < 1_000_000)
|
|
53
|
+
return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0).replace(/\.0$/, '')}k`;
|
|
54
|
+
return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`;
|
|
55
|
+
}
|
|
56
|
+
/** "670k tokens (7.2k out · 609k cache read · 54k cache write · 26 in) · $0.70 at API prices · 14 turns" */
|
|
57
|
+
export function formatTokens(t) {
|
|
58
|
+
const parts = [`${compact(t.output)} out`, `${compact(t.cacheRead)} cache read`, `${compact(t.cacheWrite)} cache write`, `${compact(t.input)} in`];
|
|
59
|
+
return `${compact(totalTokens(t))} tokens (${parts.join(' · ')}) · $${t.costUsd.toFixed(2)} at API prices · ${t.turns} turn${t.turns === 1 ? '' : 's'}`;
|
|
60
|
+
}
|
|
61
|
+
/** The stream log next to a run's text log. */
|
|
62
|
+
export const streamPathFor = (logPath) => logPath.replace(/\.log$/, '.stream.jsonl');
|
|
63
|
+
/** Two runs' tokens added up (several calls in one nightly read). */
|
|
64
|
+
export function addTokens(a, b) {
|
|
65
|
+
return {
|
|
66
|
+
input: a.input + b.input,
|
|
67
|
+
output: a.output + b.output,
|
|
68
|
+
cacheRead: a.cacheRead + b.cacheRead,
|
|
69
|
+
cacheWrite: a.cacheWrite + b.cacheWrite,
|
|
70
|
+
thinking: a.thinking + b.thinking,
|
|
71
|
+
costUsd: Math.round((a.costUsd + b.costUsd) * 10000) / 10000,
|
|
72
|
+
turns: a.turns + b.turns,
|
|
73
|
+
models: [...new Set([...a.models, ...b.models])],
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Filling in exact tokens for runs recorded before tokens.ts existed: every away run since 2026-11-17 saved its
|
|
2
|
+
// whole stream (`<started>.stream.jsonl`), and the stream's result event has the exact counts.
|
|
3
|
+
import { existsSync, renameSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { cardDir, loadBoard, updateBoard } from './board.js';
|
|
6
|
+
import { readRuns, runsPath } from './costs.js';
|
|
7
|
+
import { homePath } from './home.js';
|
|
8
|
+
import { streamPathFor, tokensFromStream } from './tokens.js';
|
|
9
|
+
const stamp = (ms) => new Date(ms).toISOString().replace(/[:.]/g, '-');
|
|
10
|
+
/** Where a run's stream log is: next to its log, in the old runs/<id>/ folder, or in the card's own folder. */
|
|
11
|
+
function streamFor(r, workspace) {
|
|
12
|
+
const name = `${stamp(Date.parse(r.at) - r.durationMs)}.stream.jsonl`;
|
|
13
|
+
for (const dir of [homePath('runs', r.card), cardDir({ id: r.card, workspace })]) {
|
|
14
|
+
const p = join(dir, name);
|
|
15
|
+
if (existsSync(p))
|
|
16
|
+
return p;
|
|
17
|
+
}
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
/** Fill in `tokens` on board runs and runs.jsonl records that lack it. Returns how many runs.jsonl records got them. */
|
|
21
|
+
export function backfillTokens() {
|
|
22
|
+
const board = loadBoard();
|
|
23
|
+
const ws = new Map(board.cards.map((c) => [c.id, c.workspace]));
|
|
24
|
+
if (board.cards.some((c) => c.run && !c.run.tokens && c.logPath)) {
|
|
25
|
+
updateBoard((b) => {
|
|
26
|
+
for (const c of b.cards) {
|
|
27
|
+
if (!c.run || c.run.tokens || !c.logPath)
|
|
28
|
+
continue;
|
|
29
|
+
const t = tokensFromStream(streamPathFor(c.logPath));
|
|
30
|
+
if (t)
|
|
31
|
+
c.run.tokens = t;
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
const runs = readRuns();
|
|
36
|
+
let filled = 0;
|
|
37
|
+
for (const r of runs) {
|
|
38
|
+
if (r.tokens)
|
|
39
|
+
continue;
|
|
40
|
+
const p = streamFor(r, ws.get(r.card));
|
|
41
|
+
const t = p ? tokensFromStream(p) : undefined;
|
|
42
|
+
if (t) {
|
|
43
|
+
r.tokens = t;
|
|
44
|
+
filled++;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (filled) {
|
|
48
|
+
const path = runsPath();
|
|
49
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
50
|
+
writeFileSync(tmp, runs.map((r) => JSON.stringify(r)).join('\n') + '\n');
|
|
51
|
+
renameSync(tmp, path);
|
|
52
|
+
}
|
|
53
|
+
return filled;
|
|
54
|
+
}
|
|
55
|
+
export function median(xs) {
|
|
56
|
+
if (!xs.length)
|
|
57
|
+
return 0;
|
|
58
|
+
const s = [...xs].sort((a, b) => a - b);
|
|
59
|
+
const m = Math.floor(s.length / 2);
|
|
60
|
+
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
|
61
|
+
}
|
package/dist/trace.js
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
// One conversation, turn by turn: where its tokens went (pillar A). A subset of codeburn's `sessions --why`
|
|
2
|
+
// (src/session-why.ts, MIT): turns → requests → tool steps, cost split by token kind, and two estimated
|
|
3
|
+
// findings, "carry" (a big tool result or paste re-read by every later request until a compaction) and
|
|
4
|
+
// "prefix" (the startup context every request re-reads). Laid out like a Langfuse trace in the app.
|
|
5
|
+
//
|
|
6
|
+
// Reads the session file on demand and keeps nothing. Your own prompts are shown only for workspaces you ticked
|
|
7
|
+
// for the nightly read (like titles in the usage ledger); tool output is only measured, never shown.
|
|
8
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
9
|
+
import { basename, join } from 'node:path';
|
|
10
|
+
import { projectsDir } from './dream.js';
|
|
11
|
+
import { priceOf } from './usage.js';
|
|
12
|
+
/** codeburn WHY_RULES: a result this big is worth a finding; a first prompt this big is a heavy prefix. */
|
|
13
|
+
export const TRACE_RULES = { carryTokens: 10_000, prefixTokens: 40_000, charsPerToken: 4, imageTokens: 1_600 };
|
|
14
|
+
/**
|
|
15
|
+
* Rough tokens of a tool result. Images count as images (~1.6k tokens at most for Claude), not as their base64
|
|
16
|
+
* text: screenshots read with Read made a 600k-character result look like 150k tokens (2026-11-21).
|
|
17
|
+
*/
|
|
18
|
+
export function resultTokens(content) {
|
|
19
|
+
if (typeof content === 'string')
|
|
20
|
+
return { tokens: Math.round(content.length / TRACE_RULES.charsPerToken), chars: content.length };
|
|
21
|
+
if (!Array.isArray(content))
|
|
22
|
+
return { tokens: 0, chars: 0 };
|
|
23
|
+
let tokens = 0;
|
|
24
|
+
let chars = 0;
|
|
25
|
+
for (const b of content) {
|
|
26
|
+
if (b?.type === 'image')
|
|
27
|
+
tokens += TRACE_RULES.imageTokens;
|
|
28
|
+
else if (b?.type === 'text') {
|
|
29
|
+
chars += (b.text ?? '').length;
|
|
30
|
+
tokens += Math.round((b.text ?? '').length / TRACE_RULES.charsPerToken);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return { tokens, chars };
|
|
34
|
+
}
|
|
35
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);
|
|
36
|
+
const zeroParts = () => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
|
|
37
|
+
const addParts = (a, b) => ({ input: a.input + b.input, output: a.output + b.output, cacheRead: a.cacheRead + b.cacheRead, cacheWrite: a.cacheWrite + b.cacheWrite });
|
|
38
|
+
const sumParts = (p) => p.input + p.output + p.cacheRead + p.cacheWrite;
|
|
39
|
+
/** The session file (and its subagents) for an id or the start of one. */
|
|
40
|
+
export function findSession(query, root = projectsDir()) {
|
|
41
|
+
if (!existsSync(root))
|
|
42
|
+
return null;
|
|
43
|
+
const q = query.trim();
|
|
44
|
+
for (const dir of readdirSync(root)) {
|
|
45
|
+
let names;
|
|
46
|
+
try {
|
|
47
|
+
names = readdirSync(join(root, dir));
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
const hit = names.find((n) => n.endsWith('.jsonl') && n.startsWith(q));
|
|
53
|
+
if (!hit)
|
|
54
|
+
continue;
|
|
55
|
+
const id = basename(hit, '.jsonl');
|
|
56
|
+
const sub = join(root, dir, id, 'subagents');
|
|
57
|
+
const helpers = existsSync(sub) ? readdirSync(sub).filter((n) => n.endsWith('.jsonl')).map((n) => join(sub, n)) : [];
|
|
58
|
+
return { main: join(root, dir, hit), helpers };
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
function readEntries(file) {
|
|
63
|
+
const out = [];
|
|
64
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
65
|
+
if (!line)
|
|
66
|
+
continue;
|
|
67
|
+
try {
|
|
68
|
+
out.push(JSON.parse(line));
|
|
69
|
+
}
|
|
70
|
+
catch { }
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
function toolLabel(input) {
|
|
75
|
+
const i = input ?? {};
|
|
76
|
+
return String(i.file_path ?? i.command ?? i.pattern ?? i.url ?? i.description ?? i.prompt ?? '').split('\n')[0].slice(0, 80);
|
|
77
|
+
}
|
|
78
|
+
/** One request's cost by token kind (each priced alone, so they add up to the request's cost). */
|
|
79
|
+
function partsCost(model, t) {
|
|
80
|
+
const p = (x) => priceOf(model, { input: 0, output: 0, cacheRead: 0, cacheWrite5m: 0, cacheWrite1h: 0, ...x }) ?? 0;
|
|
81
|
+
const parts = {
|
|
82
|
+
input: p({ input: t.input }),
|
|
83
|
+
output: p({ output: t.output }),
|
|
84
|
+
cacheRead: p({ cacheRead: t.cacheRead }),
|
|
85
|
+
cacheWrite: p({ cacheWrite5m: t.cacheWrite - t.write1h, cacheWrite1h: t.write1h }),
|
|
86
|
+
};
|
|
87
|
+
// Long-context tiers price the whole call by its full prompt: use the full call's price as the total.
|
|
88
|
+
const cost = priceOf(model, { input: t.input, output: t.output, cacheRead: t.cacheRead, cacheWrite5m: t.cacheWrite - t.write1h, cacheWrite1h: t.write1h }) ?? 0;
|
|
89
|
+
return { cost, parts };
|
|
90
|
+
}
|
|
91
|
+
/** Assistant rows → one request per message id (the largest copy), with all its tool calls. */
|
|
92
|
+
function requestsOf(entries, helper) {
|
|
93
|
+
const byId = new Map();
|
|
94
|
+
for (const e of entries) {
|
|
95
|
+
const m = e.message;
|
|
96
|
+
if (e.type !== 'assistant' || !m?.id || !m.usage || !m.model || m.model === '<synthetic>')
|
|
97
|
+
continue;
|
|
98
|
+
const u = m.usage;
|
|
99
|
+
const write = num(u.cache_creation_input_tokens);
|
|
100
|
+
const write1h = Math.min(write, num(u.cache_creation?.ephemeral_1h_input_tokens));
|
|
101
|
+
const tokens = { input: num(u.input_tokens), output: num(u.output_tokens), cacheRead: num(u.cache_read_input_tokens), cacheWrite: write };
|
|
102
|
+
const { cost, parts } = partsCost(m.model, { ...tokens, write1h });
|
|
103
|
+
const tools = Array.isArray(m.content)
|
|
104
|
+
? m.content
|
|
105
|
+
.filter((b) => b?.type === 'tool_use')
|
|
106
|
+
.map((b) => ({ id: String(b.id ?? ''), name: String(b.name ?? '?'), label: toolLabel(b.input), resultChars: 0, resultTokens: 0, isError: false }))
|
|
107
|
+
: [];
|
|
108
|
+
const key = `${m.id}:${String(e.requestId ?? '')}`;
|
|
109
|
+
const had = byId.get(key);
|
|
110
|
+
const size = sumParts(tokens);
|
|
111
|
+
if (had) {
|
|
112
|
+
// Same request logged once per content block: keep the largest usage, gather every tool call.
|
|
113
|
+
for (const t of tools)
|
|
114
|
+
if (!had.req.tools.some((x) => x.id === t.id))
|
|
115
|
+
had.req.tools.push(t);
|
|
116
|
+
if (size >= had.size)
|
|
117
|
+
Object.assign(had.req, { costUsd: cost, parts, tokens, context: tokens.input + tokens.cacheRead + tokens.cacheWrite });
|
|
118
|
+
had.size = Math.max(had.size, size);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
byId.set(key, {
|
|
122
|
+
size,
|
|
123
|
+
req: { at: String(e.timestamp ?? ''), model: m.model, costUsd: cost, parts, tokens, context: tokens.input + tokens.cacheRead + tokens.cacheWrite, tools, helper },
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
return [...byId.values()].map((x) => x.req);
|
|
127
|
+
}
|
|
128
|
+
function promptOf(e) {
|
|
129
|
+
if (e.type !== 'user' || e.isMeta || e.isCompactSummary)
|
|
130
|
+
return null;
|
|
131
|
+
const c = e.message?.content;
|
|
132
|
+
if (Array.isArray(c) && c.some((b) => b?.type === 'tool_result'))
|
|
133
|
+
return null;
|
|
134
|
+
const text = typeof c === 'string' ? c : Array.isArray(c) ? c.filter((b) => b?.type === 'text').map((b) => b.text ?? '').join('\n') : '';
|
|
135
|
+
const head = text.trimStart();
|
|
136
|
+
// Commands and system notes start with a tag; a paste does too, and is yours.
|
|
137
|
+
if (!head || (head.startsWith('<') && !head.startsWith('<pasted_content')) || head.startsWith('[Request interrupted'))
|
|
138
|
+
return null;
|
|
139
|
+
return { text, kind: text.length > 2000 || /<pasted_content|\[Pasted text/.test(text) ? 'pasted' : 'text' };
|
|
140
|
+
}
|
|
141
|
+
export function traceSession(query, opts = {}) {
|
|
142
|
+
const found = findSession(query);
|
|
143
|
+
if (!found)
|
|
144
|
+
return null;
|
|
145
|
+
const entries = readEntries(found.main);
|
|
146
|
+
const workspace = String(entries.find((e) => typeof e.cwd === 'string')?.cwd ?? '');
|
|
147
|
+
const show = opts.showPrompts ? opts.showPrompts(workspace) : true;
|
|
148
|
+
const session = basename(found.main, '.jsonl');
|
|
149
|
+
const title = opts.title ?? (entries.filter((e) => e.type === 'ai-title').map((e) => String(e.aiTitle ?? '')).pop() || null);
|
|
150
|
+
// Tool results: size and error, by tool_use id. Pastes: big prompts, by time.
|
|
151
|
+
const results = new Map();
|
|
152
|
+
for (const e of entries) {
|
|
153
|
+
const c = e.message?.content;
|
|
154
|
+
if (e.type !== 'user' || !Array.isArray(c))
|
|
155
|
+
continue;
|
|
156
|
+
for (const b of c) {
|
|
157
|
+
if (b?.type !== 'tool_result' || !b.tool_use_id)
|
|
158
|
+
continue;
|
|
159
|
+
results.set(b.tool_use_id, { ...resultTokens(b.content), isError: b.is_error === true, at: String(e.timestamp ?? '') });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const compactAt = entries.filter((e) => e.type === 'system' && e.subtype === 'compact_boundary').map((e) => String(e.timestamp ?? ''));
|
|
163
|
+
// Turns: each prompt starts one; requests (yours and helpers') fall into the turn running at their time.
|
|
164
|
+
const starts = [];
|
|
165
|
+
for (const e of entries) {
|
|
166
|
+
const p = promptOf(e);
|
|
167
|
+
if (p)
|
|
168
|
+
starts.push({ at: String(e.timestamp ?? ''), prompt: p });
|
|
169
|
+
}
|
|
170
|
+
const requests = [...requestsOf(entries, false), ...found.helpers.flatMap((f) => requestsOf(readEntries(f), true))].sort((a, b) => a.at.localeCompare(b.at));
|
|
171
|
+
for (const r of requests)
|
|
172
|
+
for (const t of r.tools) {
|
|
173
|
+
const res = results.get(t.id);
|
|
174
|
+
if (res)
|
|
175
|
+
Object.assign(t, { resultChars: res.chars, resultTokens: res.tokens, isError: res.isError });
|
|
176
|
+
}
|
|
177
|
+
if (!starts.length || (requests[0] && requests[0].at < starts[0].at))
|
|
178
|
+
starts.unshift({ at: requests[0]?.at ?? '', prompt: null });
|
|
179
|
+
const turns = starts.map((s, i) => {
|
|
180
|
+
const end = starts[i + 1]?.at ?? '';
|
|
181
|
+
const reqs = requests.filter((r) => r.at >= s.at && r.at < end);
|
|
182
|
+
const parts = reqs.reduce((p, r) => addParts(p, r.parts), zeroParts());
|
|
183
|
+
const last = reqs.at(-1)?.at;
|
|
184
|
+
return {
|
|
185
|
+
i: i + 1,
|
|
186
|
+
at: s.at,
|
|
187
|
+
prompt: s.prompt && show ? s.prompt.text.replace(/<\/?pasted_content[^>]*>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 160) : null,
|
|
188
|
+
promptKind: s.prompt ? s.prompt.kind : 'continued',
|
|
189
|
+
costUsd: reqs.reduce((n, r) => n + r.costUsd, 0),
|
|
190
|
+
parts,
|
|
191
|
+
tokens: reqs.reduce((n, r) => n + sumParts(r.tokens), 0),
|
|
192
|
+
requests: reqs,
|
|
193
|
+
contextPeak: Math.max(0, ...reqs.filter((r) => !r.helper).map((r) => r.context)),
|
|
194
|
+
durationMs: last ? Math.max(0, Date.parse(last) - Date.parse(s.at)) : 0,
|
|
195
|
+
compactedBefore: compactAt.some((c) => c <= s.at && c > (starts[i - 1]?.at ?? '')),
|
|
196
|
+
};
|
|
197
|
+
}).filter((t) => t.requests.length > 0);
|
|
198
|
+
const main = requests.filter((r) => !r.helper);
|
|
199
|
+
const findings = [];
|
|
200
|
+
// Estimate (codeburn "carry"): a big tool result is written to the cache once, then re-read by every later
|
|
201
|
+
// request until the next compaction.
|
|
202
|
+
const carryCost = (estimate, at) => {
|
|
203
|
+
const stop = compactAt.find((c) => c > at) ?? '';
|
|
204
|
+
const later = main.filter((r) => r.at > at && r.at < stop);
|
|
205
|
+
if (!later.length)
|
|
206
|
+
return null;
|
|
207
|
+
// Ground the estimate in what was recorded: a result can't add more than the next request wrote to the cache.
|
|
208
|
+
const tokens = Math.min(estimate, later[0].tokens.cacheWrite + later[0].tokens.input);
|
|
209
|
+
if (tokens < TRACE_RULES.carryTokens)
|
|
210
|
+
return null;
|
|
211
|
+
const write = priceOf(later[0].model, { input: 0, output: 0, cacheRead: 0, cacheWrite5m: 0, cacheWrite1h: tokens }) ?? 0;
|
|
212
|
+
const reads = later.slice(1).reduce((n, r) => n + (priceOf(r.model, { input: 0, output: 0, cacheRead: tokens, cacheWrite5m: 0, cacheWrite1h: 0 }) ?? 0), 0);
|
|
213
|
+
return { usd: write + reads, laterRequests: later.length, tokens };
|
|
214
|
+
};
|
|
215
|
+
for (const t of turns)
|
|
216
|
+
for (const r of t.requests)
|
|
217
|
+
for (const tool of r.tools) {
|
|
218
|
+
if (r.helper || tool.resultTokens < TRACE_RULES.carryTokens)
|
|
219
|
+
continue;
|
|
220
|
+
const c = carryCost(tool.resultTokens, results.get(tool.id)?.at ?? r.at);
|
|
221
|
+
const label = tool.label.startsWith('/') ? tool.label.split('/').slice(-2).join('/') : tool.label;
|
|
222
|
+
if (c)
|
|
223
|
+
findings.push({ kind: 'carry', turn: t.i, tool: tool.name, label, estimate: true, ...c });
|
|
224
|
+
}
|
|
225
|
+
// Estimate (codeburn "prefix"): the context the very first request already carried, re-read by later ones.
|
|
226
|
+
const first = main[0];
|
|
227
|
+
if (first && first.context >= TRACE_RULES.prefixTokens) {
|
|
228
|
+
const cached = first.tokens.cacheRead + first.tokens.cacheWrite;
|
|
229
|
+
const readers = main.slice(1).filter((r) => r.tokens.cacheRead >= cached);
|
|
230
|
+
const usd = first.parts.cacheWrite + readers.reduce((n, r) => n + (priceOf(r.model, { input: 0, output: 0, cacheRead: cached, cacheWrite5m: 0, cacheWrite1h: 0 }) ?? 0), 0);
|
|
231
|
+
findings.push({ kind: 'prefix', turn: 1, tokens: first.context, laterRequests: readers.length, usd, estimate: true });
|
|
232
|
+
}
|
|
233
|
+
findings.sort((a, b) => b.usd - a.usd);
|
|
234
|
+
const parts = turns.reduce((p, t) => addParts(p, t.parts), zeroParts());
|
|
235
|
+
const tokens = requests.reduce((p, r) => addParts(p, r.tokens), zeroParts());
|
|
236
|
+
const inputSide = tokens.input + tokens.cacheRead + tokens.cacheWrite;
|
|
237
|
+
return {
|
|
238
|
+
session,
|
|
239
|
+
title,
|
|
240
|
+
workspace,
|
|
241
|
+
start: requests[0]?.at ?? '',
|
|
242
|
+
end: requests.at(-1)?.at ?? '',
|
|
243
|
+
costUsd: requests.reduce((n, r) => n + r.costUsd, 0),
|
|
244
|
+
parts,
|
|
245
|
+
tokens: sumParts(tokens),
|
|
246
|
+
requests: requests.length,
|
|
247
|
+
cacheHitPct: inputSide ? Math.round((tokens.cacheRead / inputSide) * 100) : null,
|
|
248
|
+
compactions: compactAt.length,
|
|
249
|
+
turns,
|
|
250
|
+
findings: findings.slice(0, 12),
|
|
251
|
+
promptsHidden: !show,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
const usd = (n) => `$${n >= 100 ? Math.round(n) : n.toFixed(2)}`;
|
|
255
|
+
const k = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : String(n));
|
|
256
|
+
export function formatTrace(t) {
|
|
257
|
+
const peak = Math.max(1e-9, ...t.turns.map((x) => x.costUsd));
|
|
258
|
+
const lines = [
|
|
259
|
+
`${t.title ?? t.session} · ${t.workspace.split('/').pop()}`,
|
|
260
|
+
`${usd(t.costUsd)} at API prices · ${k(t.tokens)} tokens · ${t.requests} requests · ${t.turns.length} turns · cache hit ${t.cacheHitPct ?? '–'}% · ${t.compactions} compaction${t.compactions === 1 ? '' : 's'}`,
|
|
261
|
+
`Where it went: output ${usd(t.parts.output)} · cache read ${usd(t.parts.cacheRead)} · cache write ${usd(t.parts.cacheWrite)} · input ${usd(t.parts.input)}`,
|
|
262
|
+
];
|
|
263
|
+
if (t.findings.length) {
|
|
264
|
+
lines.push('', 'What ate the tokens (estimates):');
|
|
265
|
+
for (const f of t.findings) {
|
|
266
|
+
lines.push(f.kind === 'carry'
|
|
267
|
+
? ` ~${usd(f.usd)} turn ${f.turn}: ${f.tool} ${f.label ? `"${f.label}" ` : ''}brought in ~${k(f.tokens)} tokens, re-read by ${f.laterRequests} later requests`
|
|
268
|
+
: ` ~${usd(f.usd)} startup context of ~${k(f.tokens)} tokens, re-read by ${f.laterRequests} requests`);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
lines.push('', 'Turn by turn:');
|
|
272
|
+
for (const x of t.turns) {
|
|
273
|
+
const tools = new Map();
|
|
274
|
+
for (const r of x.requests)
|
|
275
|
+
for (const tool of r.tools)
|
|
276
|
+
tools.set(tool.name, (tools.get(tool.name) ?? 0) + 1);
|
|
277
|
+
const bar = '█'.repeat(Math.max(1, Math.round((x.costUsd / peak) * 16)));
|
|
278
|
+
const what = x.prompt ? `"${x.prompt.slice(0, 70)}${x.prompt.length > 70 ? '…' : ''}"` : x.promptKind === 'continued' ? '(continued)' : '(prompt hidden)';
|
|
279
|
+
lines.push(` ${String(x.i).padStart(3)} ${x.at.slice(11, 16)} ${usd(x.costUsd).padStart(7)} ${bar.padEnd(16)} ${x.requests.length} req · context ${k(x.contextPeak)}${x.compactedBefore ? ' · after compaction' : ''} · ${[...tools].map(([n, c]) => `${n}×${c}`).join(' ') || 'no tools'} ${what}`);
|
|
280
|
+
}
|
|
281
|
+
if (t.promptsHidden)
|
|
282
|
+
lines.push('', 'Prompts are hidden: this workspace is not ticked for the nightly read.');
|
|
283
|
+
return lines.join('\n');
|
|
284
|
+
}
|
package/dist/triggers.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
// Triggers (spec §5.2): start an away run on its own in the last hour before a 5-hour reset,
|
|
1
|
+
// Triggers (spec §5.2): start an away run on its own in the last hour before a 5-hour reset, at your bedtime,
|
|
2
|
+
// or (missed-reset, off by default) on the first tick after a reset that nothing used, e.g. the Mac was asleep.
|
|
2
3
|
// `chompyy tick` checks them; `chompyy triggers on` installs a macOS LaunchAgent that runs the tick every
|
|
3
4
|
// 5 minutes. Nothing fires until you turn triggers on. The budget gate still decides every card.
|
|
4
5
|
import { execFileSync } from 'node:child_process';
|
|
@@ -45,6 +46,7 @@ export function bedtimeKey(now, bedtime, windowMin) {
|
|
|
45
46
|
/** Leave this much before the reset so the last card isn't cut off by a fresh window. */
|
|
46
47
|
const RESET_MARGIN_MS = 2 * 60_000;
|
|
47
48
|
const MIN_RUN_MS = 10 * 60_000;
|
|
49
|
+
const FIVE_HOURS_MS = 5 * 3600_000;
|
|
48
50
|
/** Should a trigger start an away run now? Pure: the tick reads state, this decides. */
|
|
49
51
|
export function decideTrigger(now, snap, config, fired, approved, awayRunning) {
|
|
50
52
|
if (awayRunning)
|
|
@@ -55,10 +57,12 @@ export function decideTrigger(now, snap, config, fired, approved, awayRunning) {
|
|
|
55
57
|
if (!gate.ok)
|
|
56
58
|
return { fire: false, why: `gate closed: ${gate.reasons.join('; ')}` };
|
|
57
59
|
const five = windowView(snap?.fiveHour, now);
|
|
58
|
-
|
|
60
|
+
// A reset window that nothing has restarted (the gate let it through): a run starts a fresh 5-hour window.
|
|
61
|
+
const fresh = !five.known && five.reason === 'stale';
|
|
62
|
+
if (!five.known && !fresh)
|
|
59
63
|
return { fire: false, why: '5h window unknown' };
|
|
60
|
-
const untilReset = five.msLeft - RESET_MARGIN_MS;
|
|
61
|
-
if (config.lastHourTrigger && five.msLeft <= 60 * 60_000) {
|
|
64
|
+
const untilReset = (five.known ? five.msLeft : FIVE_HOURS_MS) - RESET_MARGIN_MS;
|
|
65
|
+
if (five.known && config.lastHourTrigger && five.msLeft <= 60 * 60_000) {
|
|
62
66
|
const key = `last-hour:${five.resetsAt}`;
|
|
63
67
|
if (fired.includes(key))
|
|
64
68
|
return { fire: false, why: 'last-hour already ran for this window' };
|
|
@@ -75,9 +79,16 @@ export function decideTrigger(now, snap, config, fired, approved, awayRunning) {
|
|
|
75
79
|
return { fire: false, why: 'bedtime already ran tonight' };
|
|
76
80
|
if (untilReset < MIN_RUN_MS)
|
|
77
81
|
return { fire: false, why: 'too close to the reset to finish a card' };
|
|
78
|
-
return { fire: true, kind: 'bedtime', durationMs: untilReset, key, why: `bedtime, ${Math.round(five.leftPct)}% of the window left` };
|
|
82
|
+
return { fire: true, kind: 'bedtime', durationMs: untilReset, key, why: five.known ? `bedtime, ${Math.round(five.leftPct)}% of the window left` : 'bedtime, a fresh window' };
|
|
79
83
|
}
|
|
80
84
|
}
|
|
85
|
+
// The reset passed while no away run (and no session) started a new window: only cards you already approved run.
|
|
86
|
+
if (fresh && config.missedReset) {
|
|
87
|
+
const key = `missed:${five.resetsAt}`;
|
|
88
|
+
if (fired.includes(key))
|
|
89
|
+
return { fire: false, why: 'missed-reset already ran for this reset' };
|
|
90
|
+
return { fire: true, kind: 'missed-reset', durationMs: untilReset, key, why: 'a 5-hour reset passed unused, a fresh window' };
|
|
91
|
+
}
|
|
81
92
|
return { fire: false, why: 'no trigger due' };
|
|
82
93
|
}
|
|
83
94
|
// ---------- the away lock (a trigger and a manual away must not run the same cards) ----------
|