chompyy 0.1.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -8
- package/THIRD_PARTY_NOTICES.md +29 -1
- package/dist/appstate.js +121 -4
- package/dist/away.js +191 -25
- package/dist/blueprint.js +102 -7
- package/dist/board.js +143 -15
- package/dist/catalog.js +81 -0
- package/dist/claudesettings.js +23 -0
- package/dist/cli.js +804 -55
- package/dist/coldstart.js +208 -0
- package/dist/config.js +43 -8
- package/dist/costs.js +162 -0
- package/dist/deps.js +124 -0
- package/dist/dream.js +422 -0
- package/dist/duration.js +3 -3
- package/dist/gate.js +40 -5
- package/dist/history.js +308 -0
- package/dist/live.js +255 -0
- package/dist/livequota.js +42 -5
- package/dist/macapp.js +25 -2
- package/dist/pacing.js +189 -0
- package/dist/permissions.js +106 -0
- package/dist/picture.js +124 -0
- package/dist/picturetype.js +208 -0
- package/dist/preflight.js +168 -0
- package/dist/projects.js +5 -4
- package/dist/quota.js +31 -5
- package/dist/refresh.js +290 -0
- package/dist/report.js +41 -21
- package/dist/review.js +111 -11
- package/dist/runner.js +318 -10
- package/dist/taste.js +528 -0
- package/dist/tokens.js +75 -0
- package/dist/tokenstore.js +61 -0
- package/dist/trace.js +284 -0
- package/dist/triggers.js +193 -0
- package/dist/usage.js +467 -0
- package/dist/vendor/codeburn/prices.js +45 -0
- package/dist/verify.js +150 -0
- package/dist/verifycard.js +146 -0
- package/dist/workspace.js +132 -18
- package/package.json +4 -2
- package/skills/taste/SKILL.md +4 -1
- package/vendor/diagram-design/LICENSE +21 -0
- package/vendor/diagram-design/SKILL.md +399 -0
- package/vendor/diagram-design/UPSTREAM.md +18 -0
- package/vendor/diagram-design/assets/example-arc-diagram.html +111 -0
- package/vendor/diagram-design/assets/example-architecture-containment.html +205 -0
- package/vendor/diagram-design/assets/example-architecture-delta.html +193 -0
- package/vendor/diagram-design/assets/example-architecture.html +183 -0
- package/vendor/diagram-design/assets/example-axonometric-plan-campus.html +108 -0
- package/vendor/diagram-design/assets/example-axonometric-plan-coffee-shop.html +121 -0
- package/vendor/diagram-design/assets/example-axonometric-plan-warehouse.html +127 -0
- package/vendor/diagram-design/assets/example-axonometric-plan.html +114 -0
- package/vendor/diagram-design/assets/example-bar.html +129 -0
- package/vendor/diagram-design/assets/example-beeswarm.html +384 -0
- package/vendor/diagram-design/assets/example-box-plot.html +127 -0
- package/vendor/diagram-design/assets/example-bubble.html +147 -0
- package/vendor/diagram-design/assets/example-bump.html +142 -0
- package/vendor/diagram-design/assets/example-data-flow.html +143 -0
- package/vendor/diagram-design/assets/example-datalake.html +269 -0
- package/vendor/diagram-design/assets/example-db-schema.html +302 -0
- package/vendor/diagram-design/assets/example-dependency.html +224 -0
- package/vendor/diagram-design/assets/example-deployment.html +190 -0
- package/vendor/diagram-design/assets/example-dp-integration.html +81 -0
- package/vendor/diagram-design/assets/example-dp-security-matrix.html +88 -0
- package/vendor/diagram-design/assets/example-er.html +202 -0
- package/vendor/diagram-design/assets/example-event-modeling.html +64 -0
- package/vendor/diagram-design/assets/example-exploded-ai-stack.html +85 -0
- package/vendor/diagram-design/assets/example-exploded-keyboard.html +84 -0
- package/vendor/diagram-design/assets/example-exploded-phone.html +83 -0
- package/vendor/diagram-design/assets/example-exploded-unboxing.html +84 -0
- package/vendor/diagram-design/assets/example-exploded.html +83 -0
- package/vendor/diagram-design/assets/example-fishbone.html +152 -0
- package/vendor/diagram-design/assets/example-flowchart.html +163 -0
- package/vendor/diagram-design/assets/example-gantt.html +137 -0
- package/vendor/diagram-design/assets/example-heatmap.html +224 -0
- package/vendor/diagram-design/assets/example-high-level-vertical.html +325 -0
- package/vendor/diagram-design/assets/example-high-level.html +301 -0
- package/vendor/diagram-design/assets/example-import-drawio.html +185 -0
- package/vendor/diagram-design/assets/example-import-excalidraw.html +70 -0
- package/vendor/diagram-design/assets/example-import-mermaid.html +70 -0
- package/vendor/diagram-design/assets/example-import-plantuml.html +107 -0
- package/vendor/diagram-design/assets/example-it-state.html +128 -0
- package/vendor/diagram-design/assets/example-journey.html +148 -0
- package/vendor/diagram-design/assets/example-kanban.html +174 -0
- package/vendor/diagram-design/assets/example-layers.html +123 -0
- package/vendor/diagram-design/assets/example-line.html +111 -0
- package/vendor/diagram-design/assets/example-loop.html +100 -0
- package/vendor/diagram-design/assets/example-marimekko.html +148 -0
- package/vendor/diagram-design/assets/example-medallion.html +159 -0
- package/vendor/diagram-design/assets/example-nested.html +136 -0
- package/vendor/diagram-design/assets/example-org-chart.html +45 -0
- package/vendor/diagram-design/assets/example-polar.html +116 -0
- package/vendor/diagram-design/assets/example-process.html +64 -0
- package/vendor/diagram-design/assets/example-pyramid.html +119 -0
- package/vendor/diagram-design/assets/example-quadrant-consultant.html +166 -0
- package/vendor/diagram-design/assets/example-quadrant.html +135 -0
- package/vendor/diagram-design/assets/example-radar.html +139 -0
- package/vendor/diagram-design/assets/example-requirement-traceability.html +122 -0
- package/vendor/diagram-design/assets/example-ridgeline.html +104 -0
- package/vendor/diagram-design/assets/example-sankey.html +150 -0
- package/vendor/diagram-design/assets/example-sbgn.html +213 -0
- package/vendor/diagram-design/assets/example-scatter.html +141 -0
- package/vendor/diagram-design/assets/example-sequence-oauth.html +227 -0
- package/vendor/diagram-design/assets/example-sequence.html +222 -0
- package/vendor/diagram-design/assets/example-service-blueprint.html +185 -0
- package/vendor/diagram-design/assets/example-slopegraph.html +119 -0
- package/vendor/diagram-design/assets/example-state-lifecycle.html +92 -0
- package/vendor/diagram-design/assets/example-state.html +147 -0
- package/vendor/diagram-design/assets/example-steps.html +78 -0
- package/vendor/diagram-design/assets/example-story-map.html +184 -0
- package/vendor/diagram-design/assets/example-streamgraph.html +99 -0
- package/vendor/diagram-design/assets/example-swimlane.html +172 -0
- package/vendor/diagram-design/assets/example-timeline.html +135 -0
- package/vendor/diagram-design/assets/example-tree-block-decomposition.html +151 -0
- package/vendor/diagram-design/assets/example-tree.html +173 -0
- package/vendor/diagram-design/assets/example-treemap.html +107 -0
- package/vendor/diagram-design/assets/example-uml-class.html +188 -0
- package/vendor/diagram-design/assets/example-unit-grid.html +141 -0
- package/vendor/diagram-design/assets/example-venn.html +110 -0
- package/vendor/diagram-design/assets/example-wardley.html +153 -0
- package/vendor/diagram-design/assets/example-waterfall.html +129 -0
- package/vendor/diagram-design/assets/template-dark.html +99 -0
- package/vendor/diagram-design/assets/template.html +100 -0
- package/vendor/diagram-design/references/layout-budget.md +103 -0
- package/vendor/diagram-design/references/output-spec.md +277 -0
- package/vendor/diagram-design/references/primitive-annotation.md +36 -0
- package/vendor/diagram-design/references/primitive-sketchy.md +43 -0
- package/vendor/diagram-design/references/primitives-core.md +146 -0
- package/vendor/diagram-design/references/semantic-patterns.md +154 -0
- package/vendor/diagram-design/references/style-guide.md +234 -0
- package/vendor/diagram-design/references/type-architecture-delta.md +143 -0
- package/vendor/diagram-design/references/type-architecture.md +117 -0
- package/vendor/diagram-design/references/type-axonometric-plan.md +83 -0
- package/vendor/diagram-design/references/type-bar.md +108 -0
- package/vendor/diagram-design/references/type-data-flow.md +371 -0
- package/vendor/diagram-design/references/type-db-schema.md +48 -0
- package/vendor/diagram-design/references/type-dependency.md +113 -0
- package/vendor/diagram-design/references/type-deployment.md +45 -0
- package/vendor/diagram-design/references/type-dp-integration.md +407 -0
- package/vendor/diagram-design/references/type-dp-security-matrix.md +379 -0
- package/vendor/diagram-design/references/type-er.md +25 -0
- package/vendor/diagram-design/references/type-event-modeling.md +36 -0
- package/vendor/diagram-design/references/type-exploded.md +115 -0
- package/vendor/diagram-design/references/type-fishbone.md +75 -0
- package/vendor/diagram-design/references/type-flowchart.md +23 -0
- package/vendor/diagram-design/references/type-gantt.md +45 -0
- package/vendor/diagram-design/references/type-heatmap.md +80 -0
- package/vendor/diagram-design/references/type-high-level.md +470 -0
- package/vendor/diagram-design/references/type-it-state.md +468 -0
- package/vendor/diagram-design/references/type-journey.md +55 -0
- package/vendor/diagram-design/references/type-kanban.md +49 -0
- package/vendor/diagram-design/references/type-layers.md +26 -0
- package/vendor/diagram-design/references/type-line.md +337 -0
- package/vendor/diagram-design/references/type-loop.md +223 -0
- package/vendor/diagram-design/references/type-medallion.md +356 -0
- package/vendor/diagram-design/references/type-nested.md +22 -0
- package/vendor/diagram-design/references/type-org-chart.md +44 -0
- package/vendor/diagram-design/references/type-polar.md +136 -0
- package/vendor/diagram-design/references/type-process.md +490 -0
- package/vendor/diagram-design/references/type-pyramid.md +33 -0
- package/vendor/diagram-design/references/type-quadrant.md +81 -0
- package/vendor/diagram-design/references/type-radar.md +82 -0
- package/vendor/diagram-design/references/type-requirement-traceability.md +45 -0
- package/vendor/diagram-design/references/type-sankey.md +75 -0
- package/vendor/diagram-design/references/type-sbgn.md +80 -0
- package/vendor/diagram-design/references/type-scatter.md +276 -0
- package/vendor/diagram-design/references/type-sequence.md +130 -0
- package/vendor/diagram-design/references/type-service-blueprint.md +103 -0
- package/vendor/diagram-design/references/type-state.md +30 -0
- package/vendor/diagram-design/references/type-steps.md +180 -0
- package/vendor/diagram-design/references/type-story-map.md +46 -0
- package/vendor/diagram-design/references/type-swimlane.md +22 -0
- package/vendor/diagram-design/references/type-timeline.md +20 -0
- package/vendor/diagram-design/references/type-tree.md +24 -0
- package/vendor/diagram-design/references/type-treemap.md +137 -0
- package/vendor/diagram-design/references/type-uml-class.md +65 -0
- package/vendor/diagram-design/references/type-unit-grid.md +63 -0
- package/vendor/diagram-design/references/type-venn.md +26 -0
- package/vendor/diagram-design/references/type-wardley.md +39 -0
- package/vendor/diagram-design/references/type-waterfall.md +75 -0
- package/vendor/diagram-design/scripts/self_check.py +1177 -0
- package/vendor/diagram-design/scripts/verify_geometry.py +696 -0
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
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
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.
|
|
3
|
+
// `chompyy tick` checks them; `chompyy triggers on` installs a macOS LaunchAgent that runs the tick every
|
|
4
|
+
// 5 minutes. Nothing fires until you turn triggers on. The budget gate still decides every card.
|
|
5
|
+
import { execFileSync } from 'node:child_process';
|
|
6
|
+
import { existsSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
7
|
+
import { homedir } from 'node:os';
|
|
8
|
+
import { dirname, join } from 'node:path';
|
|
9
|
+
import { budgetGate } from './gate.js';
|
|
10
|
+
import { homePath, readJson, writeJson } from './home.js';
|
|
11
|
+
import { windowView } from './quota.js';
|
|
12
|
+
const statePath = () => homePath('triggers.json');
|
|
13
|
+
export const loadTriggerState = () => readJson(statePath(), { fired: [] });
|
|
14
|
+
export function markFired(key, now, why) {
|
|
15
|
+
const s = loadTriggerState();
|
|
16
|
+
s.fired = [...s.fired.filter((k) => k !== key), key].slice(-50);
|
|
17
|
+
s.lastTickAt = now.toISOString();
|
|
18
|
+
s.lastDecision = why;
|
|
19
|
+
writeJson(statePath(), s);
|
|
20
|
+
}
|
|
21
|
+
export function noteTick(now, why) {
|
|
22
|
+
writeJson(statePath(), { ...loadTriggerState(), lastTickAt: now.toISOString(), lastDecision: why });
|
|
23
|
+
}
|
|
24
|
+
/** "23:30" → minutes after midnight; throws on anything else. */
|
|
25
|
+
export function parseClock(text) {
|
|
26
|
+
const m = text.trim().match(/^(\d{1,2}):(\d{2})$/);
|
|
27
|
+
if (!m || Number(m[1]) > 23 || Number(m[2]) > 59)
|
|
28
|
+
throw new Error(`Bedtime must look like 23:30, not "${text}".`);
|
|
29
|
+
return Number(m[1]) * 60 + Number(m[2]);
|
|
30
|
+
}
|
|
31
|
+
/** If `now` is within the bedtime window, the local date the bedtime started on (handles windows past midnight). */
|
|
32
|
+
export function bedtimeKey(now, bedtime, windowMin) {
|
|
33
|
+
const start = parseClock(bedtime);
|
|
34
|
+
const minutes = now.getHours() * 60 + now.getMinutes();
|
|
35
|
+
let since = minutes - start;
|
|
36
|
+
const day = new Date(now);
|
|
37
|
+
if (since < 0) {
|
|
38
|
+
since += 24 * 60; // bedtime was yesterday evening
|
|
39
|
+
day.setDate(day.getDate() - 1);
|
|
40
|
+
}
|
|
41
|
+
if (since >= windowMin)
|
|
42
|
+
return null;
|
|
43
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
44
|
+
return `bedtime:${day.getFullYear()}-${pad(day.getMonth() + 1)}-${pad(day.getDate())}`;
|
|
45
|
+
}
|
|
46
|
+
/** Leave this much before the reset so the last card isn't cut off by a fresh window. */
|
|
47
|
+
const RESET_MARGIN_MS = 2 * 60_000;
|
|
48
|
+
const MIN_RUN_MS = 10 * 60_000;
|
|
49
|
+
const FIVE_HOURS_MS = 5 * 3600_000;
|
|
50
|
+
/** Should a trigger start an away run now? Pure: the tick reads state, this decides. */
|
|
51
|
+
export function decideTrigger(now, snap, config, fired, approved, awayRunning) {
|
|
52
|
+
if (awayRunning)
|
|
53
|
+
return { fire: false, why: 'an away run is already going' };
|
|
54
|
+
if (approved === 0)
|
|
55
|
+
return { fire: false, why: 'no approved cards' };
|
|
56
|
+
const gate = budgetGate(snap, config, now);
|
|
57
|
+
if (!gate.ok)
|
|
58
|
+
return { fire: false, why: `gate closed: ${gate.reasons.join('; ')}` };
|
|
59
|
+
const five = windowView(snap?.fiveHour, now);
|
|
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)
|
|
63
|
+
return { fire: false, why: '5h window unknown' };
|
|
64
|
+
const untilReset = (five.known ? five.msLeft : FIVE_HOURS_MS) - RESET_MARGIN_MS;
|
|
65
|
+
if (five.known && config.lastHourTrigger && five.msLeft <= 60 * 60_000) {
|
|
66
|
+
const key = `last-hour:${five.resetsAt}`;
|
|
67
|
+
if (fired.includes(key))
|
|
68
|
+
return { fire: false, why: 'last-hour already ran for this window' };
|
|
69
|
+
if (five.leftPct < config.lastHourMinLeftPct)
|
|
70
|
+
return { fire: false, why: `last hour, but only ${Math.round(five.leftPct)}% left (under ${config.lastHourMinLeftPct}%)` };
|
|
71
|
+
if (untilReset < MIN_RUN_MS)
|
|
72
|
+
return { fire: false, why: 'too close to the reset to finish a card' };
|
|
73
|
+
return { fire: true, kind: 'last-hour', durationMs: untilReset, key, why: `last hour before the reset with ${Math.round(five.leftPct)}% left` };
|
|
74
|
+
}
|
|
75
|
+
if (config.bedtime) {
|
|
76
|
+
const key = bedtimeKey(now, config.bedtime, config.bedtimeWindowMin);
|
|
77
|
+
if (key) {
|
|
78
|
+
if (fired.includes(key))
|
|
79
|
+
return { fire: false, why: 'bedtime already ran tonight' };
|
|
80
|
+
if (untilReset < MIN_RUN_MS)
|
|
81
|
+
return { fire: false, why: 'too close to the reset to finish a card' };
|
|
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' };
|
|
83
|
+
}
|
|
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
|
+
}
|
|
92
|
+
return { fire: false, why: 'no trigger due' };
|
|
93
|
+
}
|
|
94
|
+
// ---------- the away lock (a trigger and a manual away must not run the same cards) ----------
|
|
95
|
+
export function lockPath() {
|
|
96
|
+
return homePath('away.lock');
|
|
97
|
+
}
|
|
98
|
+
function alive(pid) {
|
|
99
|
+
try {
|
|
100
|
+
process.kill(pid, 0);
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
return err.code === 'EPERM';
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** The pid of a running away, or null. A lock left by a dead process doesn't count. */
|
|
108
|
+
export function awayRunning() {
|
|
109
|
+
const lock = readJson(lockPath(), null);
|
|
110
|
+
return lock?.pid && lock.pid !== process.pid && alive(lock.pid) ? lock.pid : null;
|
|
111
|
+
}
|
|
112
|
+
/** Take the lock or throw. Returns a release function. */
|
|
113
|
+
export function takeAwayLock(now, why) {
|
|
114
|
+
const other = awayRunning();
|
|
115
|
+
if (other)
|
|
116
|
+
throw new Error(`Another away run is going (pid ${other}). Wait for it, or stop it first.`);
|
|
117
|
+
writeJson(lockPath(), { pid: process.pid, at: now.toISOString(), why });
|
|
118
|
+
return () => {
|
|
119
|
+
const lock = readJson(lockPath(), null);
|
|
120
|
+
if (lock?.pid === process.pid)
|
|
121
|
+
rmSync(lockPath(), { force: true });
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
// ---------- LaunchAgent ----------
|
|
125
|
+
export const AGENT_LABEL = 'dev.chompyy.tick';
|
|
126
|
+
export function agentPath() {
|
|
127
|
+
return join(homedir(), 'Library', 'LaunchAgents', `${AGENT_LABEL}.plist`);
|
|
128
|
+
}
|
|
129
|
+
const xml = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
130
|
+
export function launchAgentPlist(opts) {
|
|
131
|
+
const env = Object.entries(opts.env)
|
|
132
|
+
.map(([k, v]) => ` <key>${xml(k)}</key><string>${xml(v)}</string>`)
|
|
133
|
+
.join('\n');
|
|
134
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
135
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
136
|
+
<plist version="1.0">
|
|
137
|
+
<dict>
|
|
138
|
+
<key>Label</key><string>${AGENT_LABEL}</string>
|
|
139
|
+
<key>ProgramArguments</key>
|
|
140
|
+
<array>
|
|
141
|
+
<string>${xml(opts.node)}</string>
|
|
142
|
+
<string>${xml(opts.script)}</string>
|
|
143
|
+
<string>tick</string>
|
|
144
|
+
</array>
|
|
145
|
+
<key>StartInterval</key><integer>${opts.intervalSec ?? 300}</integer>
|
|
146
|
+
<key>RunAtLoad</key><false/>
|
|
147
|
+
<key>StandardOutPath</key><string>${xml(opts.log)}</string>
|
|
148
|
+
<key>StandardErrorPath</key><string>${xml(opts.log)}</string>
|
|
149
|
+
<key>EnvironmentVariables</key>
|
|
150
|
+
<dict>
|
|
151
|
+
${env}
|
|
152
|
+
</dict>
|
|
153
|
+
</dict>
|
|
154
|
+
</plist>
|
|
155
|
+
`;
|
|
156
|
+
}
|
|
157
|
+
function launchctl(args) {
|
|
158
|
+
execFileSync('launchctl', args, { stdio: 'ignore' });
|
|
159
|
+
}
|
|
160
|
+
/** Install (or reinstall) the LaunchAgent that runs `chompyy tick` every 5 minutes. */
|
|
161
|
+
export function installAgent() {
|
|
162
|
+
if (process.platform !== 'darwin')
|
|
163
|
+
throw new Error('Triggers run from a macOS LaunchAgent; on other systems, run `chompyy tick` from cron every 5 minutes.');
|
|
164
|
+
const path = agentPath();
|
|
165
|
+
const env = { PATH: process.env.PATH ?? '/usr/bin:/bin' };
|
|
166
|
+
if (process.env.CHOMPYY_HOME)
|
|
167
|
+
env.CHOMPYY_HOME = process.env.CHOMPYY_HOME;
|
|
168
|
+
if (process.env.HOME)
|
|
169
|
+
env.HOME = process.env.HOME;
|
|
170
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
171
|
+
writeFileSync(path, launchAgentPlist({ node: process.execPath, script: process.argv[1], log: homePath('tick.log'), env }));
|
|
172
|
+
const domain = `gui/${process.getuid?.() ?? 501}`;
|
|
173
|
+
try {
|
|
174
|
+
launchctl(['bootout', `${domain}/${AGENT_LABEL}`]);
|
|
175
|
+
}
|
|
176
|
+
catch { }
|
|
177
|
+
launchctl(['bootstrap', domain, path]);
|
|
178
|
+
return path;
|
|
179
|
+
}
|
|
180
|
+
export function uninstallAgent() {
|
|
181
|
+
const path = agentPath();
|
|
182
|
+
if (!existsSync(path))
|
|
183
|
+
return false;
|
|
184
|
+
try {
|
|
185
|
+
launchctl(['bootout', `gui/${process.getuid?.() ?? 501}/${AGENT_LABEL}`]);
|
|
186
|
+
}
|
|
187
|
+
catch { }
|
|
188
|
+
rmSync(path, { force: true });
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
export function agentInstalled() {
|
|
192
|
+
return existsSync(agentPath());
|
|
193
|
+
}
|