@trazum/cli 3.0.1 → 3.0.3
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 +4 -1
- package/assets/trazum-statusline.sh +45 -0
- package/dist/base-cost.d.ts +173 -0
- package/dist/base-cost.d.ts.map +1 -0
- package/dist/base-cost.js +244 -0
- package/dist/base-cost.js.map +1 -0
- package/dist/bill-range.d.ts +118 -0
- package/dist/bill-range.d.ts.map +1 -0
- package/dist/bill-range.js +122 -0
- package/dist/bill-range.js.map +1 -0
- package/dist/command-help.d.ts +17 -0
- package/dist/command-help.d.ts.map +1 -0
- package/dist/command-help.js +69 -0
- package/dist/command-help.js.map +1 -0
- package/dist/filter.d.ts +7 -1
- package/dist/filter.d.ts.map +1 -1
- package/dist/filter.js +10 -18
- package/dist/filter.js.map +1 -1
- package/dist/gateway-metrics.d.ts +83 -0
- package/dist/gateway-metrics.d.ts.map +1 -0
- package/dist/gateway-metrics.js +181 -0
- package/dist/gateway-metrics.js.map +1 -0
- package/dist/gateway-server.d.ts +23 -5
- package/dist/gateway-server.d.ts.map +1 -1
- package/dist/gateway-server.js +26 -1
- package/dist/gateway-server.js.map +1 -1
- package/dist/gateway-spend.d.ts +11 -1
- package/dist/gateway-spend.d.ts.map +1 -1
- package/dist/gateway-spend.js +44 -32
- package/dist/gateway-spend.js.map +1 -1
- package/dist/git.d.ts +70 -0
- package/dist/git.d.ts.map +1 -1
- package/dist/git.js +145 -0
- package/dist/git.js.map +1 -1
- package/dist/i18n/en.d.ts.map +1 -1
- package/dist/i18n/en.js +358 -6
- package/dist/i18n/en.js.map +1 -1
- package/dist/i18n/es.d.ts +0 -1
- package/dist/i18n/es.d.ts.map +1 -1
- package/dist/i18n/es.js +456 -35
- package/dist/i18n/es.js.map +1 -1
- package/dist/i18n/types.d.ts +205 -0
- package/dist/i18n/types.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +942 -59
- package/dist/index.js.map +1 -1
- package/dist/loopback-guard.d.ts +37 -0
- package/dist/loopback-guard.d.ts.map +1 -0
- package/dist/loopback-guard.js +65 -0
- package/dist/loopback-guard.js.map +1 -0
- package/dist/markdown.d.ts +23 -0
- package/dist/markdown.d.ts.map +1 -1
- package/dist/markdown.js +105 -0
- package/dist/markdown.js.map +1 -1
- package/dist/plan-edits.d.ts +63 -0
- package/dist/plan-edits.d.ts.map +1 -0
- package/dist/plan-edits.js +96 -0
- package/dist/plan-edits.js.map +1 -0
- package/dist/proactive.d.ts +17 -2
- package/dist/proactive.d.ts.map +1 -1
- package/dist/proactive.js +16 -9
- package/dist/proactive.js.map +1 -1
- package/dist/receipt-send.d.ts +44 -0
- package/dist/receipt-send.d.ts.map +1 -0
- package/dist/receipt-send.js +71 -0
- package/dist/receipt-send.js.map +1 -0
- package/dist/serve.d.ts +7 -0
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +22 -1
- package/dist/serve.js.map +1 -1
- package/dist/session-guard.d.ts +210 -0
- package/dist/session-guard.d.ts.map +1 -0
- package/dist/session-guard.js +463 -0
- package/dist/session-guard.js.map +1 -0
- package/dist/task.d.ts +7 -1
- package/dist/task.d.ts.map +1 -1
- package/dist/task.js +7 -26
- package/dist/task.js.map +1 -1
- package/dist/waste.d.ts +25 -0
- package/dist/waste.d.ts.map +1 -0
- package/dist/waste.js +39 -0
- package/dist/waste.js.map +1 -0
- package/dist/zone.d.ts +27 -0
- package/dist/zone.d.ts.map +1 -0
- package/dist/zone.js +96 -0
- package/dist/zone.js.map +1 -0
- package/package.json +2 -2
- package/src/base-cost.ts +384 -0
- package/src/bill-range.ts +206 -0
- package/src/command-help.ts +65 -0
- package/src/filter.ts +11 -18
- package/src/gateway-metrics.ts +209 -0
- package/src/gateway-server.ts +43 -6
- package/src/gateway-spend.ts +45 -33
- package/src/git.ts +158 -0
- package/src/i18n/en.ts +424 -6
- package/src/i18n/es.ts +542 -35
- package/src/i18n/types.ts +208 -0
- package/src/index.ts +952 -58
- package/src/loopback-guard.ts +74 -0
- package/src/markdown.ts +117 -0
- package/src/plan-edits.ts +120 -0
- package/src/proactive.ts +22 -13
- package/src/receipt-send.ts +89 -0
- package/src/serve.ts +23 -1
- package/src/session-guard.ts +541 -0
- package/src/task.ts +8 -26
- package/src/waste.ts +42 -0
- package/src/zone.ts +95 -0
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `trazum session-guard`: a Claude Code hook that warns, then stops, at two
|
|
3
|
+
* dollar figures the person chose.
|
|
4
|
+
*
|
|
5
|
+
* It is built on the machinery `trazum proactive` already has, and borrows it
|
|
6
|
+
* rather than copying it:
|
|
7
|
+
*
|
|
8
|
+
* - **The same door for every write.** The settings file is changed through
|
|
9
|
+
* `applyChange` and read through `readJsonObject`, so the same refusals hold
|
|
10
|
+
* (a symbolic link, a file that changed since it was read, a file `JSON.parse`
|
|
11
|
+
* rejects) and the same backup is kept beside the file the first time.
|
|
12
|
+
* - **The same record of what was added.** `~/.trazum/proactive.json` gains a
|
|
13
|
+
* `guard` entry, so `uninstall` removes the hook and the containers this
|
|
14
|
+
* command created and leaves every hook that was the person's.
|
|
15
|
+
* - **The same reading of the session.** The running session's transcript is
|
|
16
|
+
* converted by `claudeCodeRecords`, as `from-claude-code` does, with its
|
|
17
|
+
* subagents' transcripts as the status line script reads them, and priced by
|
|
18
|
+
* `profileUsage` at the bundled, dated catalogue.
|
|
19
|
+
* - **The same place for state.** "The warning was given" is a file in the
|
|
20
|
+
* status line's cache directory, `TRAZUM_STATUSLINE_CACHE` or
|
|
21
|
+
* `$TMPDIR/trazum-statusline`. Nothing is written anywhere else.
|
|
22
|
+
*
|
|
23
|
+
* **The hook protocol.** Claude Code's hooks page, read on 2026-11-19
|
|
24
|
+
* (code.claude.com/docs/en/hooks), says:
|
|
25
|
+
*
|
|
26
|
+
* - A command hook gets `session_id` and `transcript_path` as JSON on stdin.
|
|
27
|
+
* - "Exit with code 2 to block the action. On events that can block, Claude Code
|
|
28
|
+
* stops the action: a `PreToolUse` hook blocks the tool call, for example, and
|
|
29
|
+
* a `UserPromptSubmit` hook rejects the prompt." Stderr is the reason, shown
|
|
30
|
+
* to Claude (PreToolUse) or as the block reason (UserPromptSubmit).
|
|
31
|
+
* - Exit 0 with no output is "no decision": the action goes ahead.
|
|
32
|
+
* - `systemMessage` in JSON on stdout at exit 0 is a "warning message shown to
|
|
33
|
+
* the user". Plain stdout on UserPromptSubmit is added as context for the
|
|
34
|
+
* model, which is why a warning is never printed as plain text: it would cost
|
|
35
|
+
* tokens and change what the model reads.
|
|
36
|
+
*
|
|
37
|
+
* So a stop is exit code 2 with the reason on stderr, on both events, and a
|
|
38
|
+
* warning is `{"systemMessage": ...}` on stdout with exit 0.
|
|
39
|
+
*
|
|
40
|
+
* **Nothing has a default.** Two thresholds and a failure policy are required,
|
|
41
|
+
* and a missing one is refused by name. A threshold is a decision about money
|
|
42
|
+
* and the policy is a decision about which failure to accept; neither is
|
|
43
|
+
* Trazum's to make.
|
|
44
|
+
*
|
|
45
|
+
* **Never $0 by guessing.** A transcript that cannot be read, a model with no
|
|
46
|
+
* price, or no transcript at all is "cannot tell". What happens then is
|
|
47
|
+
* `--on-cannot-tell`, with the meaning the gateway gives it: `fail-open` lets
|
|
48
|
+
* the work go on and says so, `fail-closed` stops it and says so. The one thing
|
|
49
|
+
* it never does is count the unpriced calls as free. When the calls that were
|
|
50
|
+
* priced already reach a threshold, that is a floor and the threshold holds.
|
|
51
|
+
*
|
|
52
|
+
* Nothing here sends anything anywhere.
|
|
53
|
+
*/
|
|
54
|
+
|
|
55
|
+
import { createHash } from 'node:crypto';
|
|
56
|
+
import { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';
|
|
57
|
+
import { join, resolve } from 'node:path';
|
|
58
|
+
import { claudeCodeRecords, FAILURE_POLICIES, formatUsd, profileUsage } from '@trazum/core';
|
|
59
|
+
import type { FailurePolicy, PricingCatalogue } from '@trazum/core';
|
|
60
|
+
import type { CliMessages } from './i18n/index.js';
|
|
61
|
+
import {
|
|
62
|
+
applyChange,
|
|
63
|
+
emptyManifest,
|
|
64
|
+
failure,
|
|
65
|
+
isObject,
|
|
66
|
+
jsonChange,
|
|
67
|
+
manifestEmpty,
|
|
68
|
+
manifestFrom,
|
|
69
|
+
pathsFor,
|
|
70
|
+
q,
|
|
71
|
+
readJsonObject,
|
|
72
|
+
removeEmptyDir,
|
|
73
|
+
shown,
|
|
74
|
+
stableRuntime,
|
|
75
|
+
undo,
|
|
76
|
+
} from './proactive.js';
|
|
77
|
+
import type { Change, Ctx, Finding, Manifest, Obj } from './proactive.js';
|
|
78
|
+
|
|
79
|
+
// --------------------------------------------------------------------------
|
|
80
|
+
// The thresholds
|
|
81
|
+
// --------------------------------------------------------------------------
|
|
82
|
+
|
|
83
|
+
export interface Thresholds {
|
|
84
|
+
warnUsd: number;
|
|
85
|
+
stopUsd: number;
|
|
86
|
+
policy: FailurePolicy;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export type ThresholdRefusal =
|
|
90
|
+
| { code: 'missing'; flags: string[] }
|
|
91
|
+
| { code: 'notAmount'; flag: string; given: string }
|
|
92
|
+
| { code: 'badPolicy'; given: string; allowed: string }
|
|
93
|
+
| { code: 'warnNotBelowStop' };
|
|
94
|
+
|
|
95
|
+
/** Both amounts and the policy, as given, or the first thing wrong with them. */
|
|
96
|
+
export function parseThresholds(given: {
|
|
97
|
+
warn: string | undefined;
|
|
98
|
+
stop: string | undefined;
|
|
99
|
+
policy: string | undefined;
|
|
100
|
+
}): { ok: true; thresholds: Thresholds } | { ok: false; refusal: ThresholdRefusal } {
|
|
101
|
+
const missing = [
|
|
102
|
+
...(given.warn === undefined ? ['--warn'] : []),
|
|
103
|
+
...(given.stop === undefined ? ['--stop'] : []),
|
|
104
|
+
...(given.policy === undefined ? ['--on-cannot-tell'] : []),
|
|
105
|
+
];
|
|
106
|
+
if (missing.length > 0) return { ok: false, refusal: { code: 'missing', flags: missing } };
|
|
107
|
+
const amount = (text: string): number | null => {
|
|
108
|
+
const value = /^\s*$/.test(text) ? Number.NaN : Number(text);
|
|
109
|
+
return Number.isFinite(value) && value > 0 ? value : null;
|
|
110
|
+
};
|
|
111
|
+
const warnUsd = amount(given.warn as string);
|
|
112
|
+
if (warnUsd === null) return { ok: false, refusal: { code: 'notAmount', flag: '--warn', given: given.warn as string } };
|
|
113
|
+
const stopUsd = amount(given.stop as string);
|
|
114
|
+
if (stopUsd === null) return { ok: false, refusal: { code: 'notAmount', flag: '--stop', given: given.stop as string } };
|
|
115
|
+
if (!(FAILURE_POLICIES as readonly string[]).includes(given.policy as string)) {
|
|
116
|
+
return { ok: false, refusal: { code: 'badPolicy', given: given.policy as string, allowed: FAILURE_POLICIES.join(', ') } };
|
|
117
|
+
}
|
|
118
|
+
if (warnUsd >= stopUsd) return { ok: false, refusal: { code: 'warnNotBelowStop' } };
|
|
119
|
+
return { ok: true, thresholds: { warnUsd, stopUsd, policy: given.policy as FailurePolicy } };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// --------------------------------------------------------------------------
|
|
123
|
+
// What the session has cost
|
|
124
|
+
// --------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
export type CannotTellCause = 'no-transcript' | 'unreadable' | 'unparseable' | 'skipped';
|
|
127
|
+
|
|
128
|
+
export type SessionCost =
|
|
129
|
+
| { kind: 'measured'; usd: number }
|
|
130
|
+
/** Some calls are on a model with no price: `usd` is what the priced ones cost, and the truth is more. */
|
|
131
|
+
| { kind: 'floor'; usd: number; unpricedModels: string[] }
|
|
132
|
+
| { kind: 'cannot-tell'; cause: CannotTellCause };
|
|
133
|
+
|
|
134
|
+
export async function jsonlFiles(folder: string): Promise<string[] | null> {
|
|
135
|
+
const info = await stat(folder).catch(() => null);
|
|
136
|
+
if (info === null || !info.isDirectory()) return [];
|
|
137
|
+
try {
|
|
138
|
+
const entries = await readdir(folder, { recursive: true, withFileTypes: true });
|
|
139
|
+
return entries
|
|
140
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith('.jsonl'))
|
|
141
|
+
.map((entry) => join(entry.parentPath, entry.name))
|
|
142
|
+
.sort();
|
|
143
|
+
} catch {
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* What the running session has cost so far, at the catalogue, or why that
|
|
150
|
+
* cannot be said.
|
|
151
|
+
*
|
|
152
|
+
* The transcript is the session's own file and its subagents' transcripts are
|
|
153
|
+
* in the folder beside it named after the session: the status line script reads
|
|
154
|
+
* them the same way, and says what leaving them out cost.
|
|
155
|
+
*/
|
|
156
|
+
export async function sessionCost(transcriptPath: unknown, catalogue: PricingCatalogue, on: Date): Promise<SessionCost> {
|
|
157
|
+
if (typeof transcriptPath !== 'string' || transcriptPath === '') return { kind: 'cannot-tell', cause: 'no-transcript' };
|
|
158
|
+
const files = [transcriptPath];
|
|
159
|
+
const subagents = await jsonlFiles(join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents'));
|
|
160
|
+
if (subagents === null) return { kind: 'cannot-tell', cause: 'unreadable' };
|
|
161
|
+
files.push(...subagents);
|
|
162
|
+
|
|
163
|
+
const lines: string[] = [];
|
|
164
|
+
let unparseable = 0;
|
|
165
|
+
for (const file of files) {
|
|
166
|
+
let text: string;
|
|
167
|
+
try {
|
|
168
|
+
text = await readFile(file, 'utf8');
|
|
169
|
+
} catch {
|
|
170
|
+
return { kind: 'cannot-tell', cause: 'unreadable' };
|
|
171
|
+
}
|
|
172
|
+
const conversion = claudeCodeRecords(text);
|
|
173
|
+
// A file with lines and none that parsed is not an empty session.
|
|
174
|
+
if (conversion.records.length === 0 && conversion.unparseable > 0 && conversion.otherLines === 0) unparseable += 1;
|
|
175
|
+
for (const record of conversion.records) lines.push(JSON.stringify(record));
|
|
176
|
+
}
|
|
177
|
+
if (unparseable > 0) return { kind: 'cannot-tell', cause: 'unparseable' };
|
|
178
|
+
|
|
179
|
+
const report = profileUsage(lines.length === 0 ? '' : `${lines.join('\n')}\n`, { catalogue, on });
|
|
180
|
+
if (report.skippedLines.length > 0) return { kind: 'cannot-tell', cause: 'skipped' };
|
|
181
|
+
if (report.unpricedModels.length > 0) return { kind: 'floor', usd: report.total.totalUsd, unpricedModels: report.unpricedModels };
|
|
182
|
+
return { kind: 'measured', usd: report.total.totalUsd };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// --------------------------------------------------------------------------
|
|
186
|
+
// The decision
|
|
187
|
+
// --------------------------------------------------------------------------
|
|
188
|
+
|
|
189
|
+
export type Decision =
|
|
190
|
+
| { action: 'allow' }
|
|
191
|
+
| { action: 'warn'; usd: number; atLeast: boolean }
|
|
192
|
+
| { action: 'block'; usd: number; atLeast: boolean }
|
|
193
|
+
| { action: 'allow-cannot-tell'; cause: CannotTellCause | 'unpriced'; models: string[] }
|
|
194
|
+
| { action: 'block-cannot-tell'; cause: CannotTellCause | 'unpriced'; models: string[] };
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Thresholds against cost, and the policy where the cost cannot be said.
|
|
198
|
+
*
|
|
199
|
+
* The comparison is "at or over": a session at exactly the stop figure is
|
|
200
|
+
* stopped. A floor counts as far as it goes: calls that were priced and already
|
|
201
|
+
* reach a threshold are a fact, and the unpriced ones can only add to it.
|
|
202
|
+
*/
|
|
203
|
+
export function decide(cost: SessionCost, thresholds: Thresholds): Decision {
|
|
204
|
+
if (cost.kind === 'cannot-tell') return cannotTell(cost.cause, [], thresholds.policy);
|
|
205
|
+
const atLeast = cost.kind === 'floor';
|
|
206
|
+
if (cost.usd >= thresholds.stopUsd) return { action: 'block', usd: cost.usd, atLeast };
|
|
207
|
+
if (cost.usd >= thresholds.warnUsd) return { action: 'warn', usd: cost.usd, atLeast };
|
|
208
|
+
if (cost.kind === 'floor') return cannotTell('unpriced', cost.unpricedModels, thresholds.policy);
|
|
209
|
+
return { action: 'allow' };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function cannotTell(cause: CannotTellCause | 'unpriced', models: string[], policy: FailurePolicy): Decision {
|
|
213
|
+
return policy === 'fail-closed' ? { action: 'block-cannot-tell', cause, models } : { action: 'allow-cannot-tell', cause, models };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// --------------------------------------------------------------------------
|
|
217
|
+
// "The warning was given", kept where the status line keeps its cache
|
|
218
|
+
// --------------------------------------------------------------------------
|
|
219
|
+
|
|
220
|
+
/** The status line's cache directory, as its script resolves it. */
|
|
221
|
+
export function stateDir(env: NodeJS.ProcessEnv): string {
|
|
222
|
+
return env.TRAZUM_STATUSLINE_CACHE || join(env.TMPDIR || '/tmp', 'trazum-statusline');
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** A session id is hashed for the file name: it came from stdin and is not a path. */
|
|
226
|
+
function markerPath(dir: string, session: string, kind: 'warned' | 'cannot-tell'): string {
|
|
227
|
+
return join(dir, `guard-${createHash('sha256').update(session).digest('hex').slice(0, 32)}.${kind}`);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export async function alreadyGiven(dir: string, session: string, kind: 'warned' | 'cannot-tell'): Promise<boolean> {
|
|
231
|
+
return stat(markerPath(dir, session, kind)).then(
|
|
232
|
+
() => true,
|
|
233
|
+
() => false,
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Never throws: a notice that cannot be remembered is given again, which is the safe direction. */
|
|
238
|
+
export async function remember(dir: string, session: string, kind: 'warned' | 'cannot-tell'): Promise<void> {
|
|
239
|
+
try {
|
|
240
|
+
await mkdir(dir, { recursive: true });
|
|
241
|
+
await writeFile(markerPath(dir, session, kind), '');
|
|
242
|
+
} catch {
|
|
243
|
+
/* given again next time */
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// --------------------------------------------------------------------------
|
|
248
|
+
// The lines in the settings file
|
|
249
|
+
// --------------------------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
/** The events the hook is wired to, both of which can block. */
|
|
252
|
+
export const GUARD_EVENTS = ['UserPromptSubmit', 'PreToolUse'] as const;
|
|
253
|
+
export type GuardEvent = (typeof GUARD_EVENTS)[number];
|
|
254
|
+
|
|
255
|
+
const amountText = (value: number): string => String(value);
|
|
256
|
+
|
|
257
|
+
/** The command written into the settings: the CLI that stays, then the exact thresholds. */
|
|
258
|
+
export function guardCommand(node: string, entry: string, thresholds: Thresholds): string {
|
|
259
|
+
return `${q(node)} ${q(entry)} session-guard check --warn ${amountText(thresholds.warnUsd)} --stop ${amountText(thresholds.stopUsd)} --on-cannot-tell ${thresholds.policy}`;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Whether a command is the one `guardCommand` writes, and what it carries.
|
|
264
|
+
*
|
|
265
|
+
* JSON has no comments, so a hook is Trazum's by being exactly this shape. A
|
|
266
|
+
* hook of the person's that merely mentions `session-guard` is not matched.
|
|
267
|
+
*/
|
|
268
|
+
export function parseGuardCommand(command: string): { node: string; entry: string; thresholds: Thresholds } | null {
|
|
269
|
+
const match = /^'([^']*)' '([^']*)' session-guard check --warn (\S+) --stop (\S+) --on-cannot-tell (fail-open|fail-closed)$/.exec(command);
|
|
270
|
+
if (match === null) return null;
|
|
271
|
+
const parsed = parseThresholds({ warn: match[3], stop: match[4], policy: match[5] });
|
|
272
|
+
if (!parsed.ok) return null;
|
|
273
|
+
const thresholds = parsed.thresholds;
|
|
274
|
+
if (guardCommand(match[1] as string, match[2] as string, thresholds) !== command) return null;
|
|
275
|
+
return { node: match[1] as string, entry: match[2] as string, thresholds };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const isOurs = (hook: unknown): boolean => isObject(hook) && typeof hook.command === 'string' && parseGuardCommand(hook.command) !== null;
|
|
279
|
+
|
|
280
|
+
export interface GuardView {
|
|
281
|
+
/** The thresholds of the hooks that are ours, by event; an event with none is absent. */
|
|
282
|
+
found: Partial<Record<GuardEvent, Thresholds>>;
|
|
283
|
+
/** The key whose shape this command cannot edit, when there is one. */
|
|
284
|
+
shape: string | null;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export function viewGuard(settings: Obj): GuardView {
|
|
288
|
+
const view: GuardView = { found: {}, shape: null };
|
|
289
|
+
if (!('hooks' in settings)) return view;
|
|
290
|
+
if (!isObject(settings.hooks)) return { found: {}, shape: 'hooks' };
|
|
291
|
+
for (const event of GUARD_EVENTS) {
|
|
292
|
+
if (!(event in settings.hooks)) continue;
|
|
293
|
+
const list = settings.hooks[event];
|
|
294
|
+
if (!Array.isArray(list)) return { found: {}, shape: `hooks.${event}` };
|
|
295
|
+
for (const entry of list) {
|
|
296
|
+
if (!isObject(entry) || !Array.isArray(entry.hooks)) continue;
|
|
297
|
+
for (const hook of entry.hooks) {
|
|
298
|
+
if (isOurs(hook)) view.found[event] = parseGuardCommand((hook as Obj).command as string)?.thresholds as Thresholds;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return view;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Adds the hook to each event, or rewrites ours there; touches no other hook. Returns the containers it created. */
|
|
306
|
+
export function withGuard(settings: Obj, command: string): string[] {
|
|
307
|
+
const created: string[] = [];
|
|
308
|
+
if (!('hooks' in settings)) {
|
|
309
|
+
settings.hooks = {};
|
|
310
|
+
created.push('hooks');
|
|
311
|
+
}
|
|
312
|
+
const hooks = settings.hooks as Obj;
|
|
313
|
+
for (const event of GUARD_EVENTS) {
|
|
314
|
+
if (!(event in hooks)) {
|
|
315
|
+
hooks[event] = [];
|
|
316
|
+
created.push(event);
|
|
317
|
+
}
|
|
318
|
+
const list = hooks[event] as unknown[];
|
|
319
|
+
let found = false;
|
|
320
|
+
for (const entry of list) {
|
|
321
|
+
if (!isObject(entry) || !Array.isArray(entry.hooks)) continue;
|
|
322
|
+
for (const hook of entry.hooks) {
|
|
323
|
+
if (isOurs(hook)) {
|
|
324
|
+
(hook as Obj).command = command;
|
|
325
|
+
found = true;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
// UserPromptSubmit takes no matcher; PreToolUse's matcher is the tool, and every tool is one.
|
|
330
|
+
if (!found) list.push({ ...(event === 'PreToolUse' ? { matcher: '*' } : {}), hooks: [{ type: 'command', command }] });
|
|
331
|
+
}
|
|
332
|
+
return created;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Removes exactly the hooks `withGuard` wrote, and the containers it made when they are empty. */
|
|
336
|
+
export function withoutGuard(settings: Obj, created: string[]): void {
|
|
337
|
+
if (!isObject(settings.hooks)) return;
|
|
338
|
+
const hooks = settings.hooks;
|
|
339
|
+
for (const event of GUARD_EVENTS) {
|
|
340
|
+
const list = hooks[event];
|
|
341
|
+
if (!Array.isArray(list)) continue;
|
|
342
|
+
const kept: unknown[] = [];
|
|
343
|
+
for (const entry of list) {
|
|
344
|
+
if (!isObject(entry) || !Array.isArray(entry.hooks)) {
|
|
345
|
+
kept.push(entry);
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
const remaining = entry.hooks.filter((hook) => !isOurs(hook));
|
|
349
|
+
if (remaining.length === entry.hooks.length) kept.push(entry);
|
|
350
|
+
else if (remaining.length > 0) {
|
|
351
|
+
entry.hooks = remaining;
|
|
352
|
+
kept.push(entry);
|
|
353
|
+
} else if (Object.keys(entry).some((key) => key !== 'matcher' && key !== 'hooks')) {
|
|
354
|
+
entry.hooks = [];
|
|
355
|
+
kept.push(entry);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
hooks[event] = kept;
|
|
359
|
+
if (kept.length === 0 && created.includes(event)) delete hooks[event];
|
|
360
|
+
}
|
|
361
|
+
if (Object.keys(hooks).length === 0 && created.includes('hooks')) delete settings.hooks;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// --------------------------------------------------------------------------
|
|
365
|
+
// The hook itself: `trazum session-guard check`
|
|
366
|
+
// --------------------------------------------------------------------------
|
|
367
|
+
|
|
368
|
+
export interface CheckResult {
|
|
369
|
+
/** What goes to standard output: JSON for Claude Code, or nothing. */
|
|
370
|
+
stdout: string;
|
|
371
|
+
/** What goes to standard error: the reason, when the exit code is 2. */
|
|
372
|
+
stderr: string;
|
|
373
|
+
/** 0 lets the action go on. 2 is the code the hooks page documents for blocking it. */
|
|
374
|
+
code: 0 | 2;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const SILENT: CheckResult = { stdout: '', stderr: '', code: 0 };
|
|
378
|
+
|
|
379
|
+
/** One hook call: the JSON Claude Code wrote on stdin, in; what to print and how to exit, out. */
|
|
380
|
+
export async function check(
|
|
381
|
+
stdin: string,
|
|
382
|
+
thresholds: Thresholds,
|
|
383
|
+
options: { catalogue: PricingCatalogue; env: NodeJS.ProcessEnv; now: Date; t: CliMessages },
|
|
384
|
+
): Promise<CheckResult> {
|
|
385
|
+
const { t } = options;
|
|
386
|
+
let input: unknown;
|
|
387
|
+
try {
|
|
388
|
+
input = JSON.parse(stdin);
|
|
389
|
+
} catch {
|
|
390
|
+
input = null;
|
|
391
|
+
}
|
|
392
|
+
const fields = isObject(input) ? input : {};
|
|
393
|
+
const session = typeof fields.session_id === 'string' ? fields.session_id : '';
|
|
394
|
+
|
|
395
|
+
let cost: SessionCost;
|
|
396
|
+
try {
|
|
397
|
+
cost = await sessionCost(fields.transcript_path, options.catalogue, options.now);
|
|
398
|
+
} catch {
|
|
399
|
+
// Whatever went wrong, it is not a session that cost nothing.
|
|
400
|
+
cost = { kind: 'cannot-tell', cause: 'unreadable' };
|
|
401
|
+
}
|
|
402
|
+
const decision = decide(cost, thresholds);
|
|
403
|
+
const dir = stateDir(options.env);
|
|
404
|
+
const usd = (value: number): string => formatUsd(value);
|
|
405
|
+
const message = (text: string): string => JSON.stringify({ systemMessage: text });
|
|
406
|
+
const why = (cause: CannotTellCause | 'unpriced', models: string[]): string =>
|
|
407
|
+
cause === 'unpriced' ? t.sessionGuard.unpriced(models.join(', ')) : t.sessionGuard.cause[cause]();
|
|
408
|
+
// A session with no id cannot be remembered, so it is told every time rather than never.
|
|
409
|
+
const given = async (kind: 'warned' | 'cannot-tell'): Promise<boolean> => session !== '' && (await alreadyGiven(dir, session, kind));
|
|
410
|
+
const note = async (kind: 'warned' | 'cannot-tell'): Promise<void> => {
|
|
411
|
+
if (session !== '') await remember(dir, session, kind);
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
switch (decision.action) {
|
|
415
|
+
case 'allow':
|
|
416
|
+
return SILENT;
|
|
417
|
+
case 'warn': {
|
|
418
|
+
if (await given('warned')) return SILENT;
|
|
419
|
+
await note('warned');
|
|
420
|
+
return {
|
|
421
|
+
...SILENT,
|
|
422
|
+
stdout: message(t.sessionGuard.warn(usd(decision.usd), usd(thresholds.warnUsd), usd(thresholds.stopUsd), decision.atLeast)),
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
case 'block':
|
|
426
|
+
return { stdout: '', stderr: t.sessionGuard.block(usd(decision.usd), usd(thresholds.stopUsd), decision.atLeast), code: 2 };
|
|
427
|
+
case 'allow-cannot-tell': {
|
|
428
|
+
if (await given('cannot-tell')) return SILENT;
|
|
429
|
+
await note('cannot-tell');
|
|
430
|
+
return { ...SILENT, stdout: message(t.sessionGuard.cannotTellOpen(why(decision.cause, decision.models))) };
|
|
431
|
+
}
|
|
432
|
+
case 'block-cannot-tell':
|
|
433
|
+
return { stdout: '', stderr: t.sessionGuard.cannotTellClosed(why(decision.cause, decision.models)), code: 2 };
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// --------------------------------------------------------------------------
|
|
438
|
+
// install, uninstall
|
|
439
|
+
// --------------------------------------------------------------------------
|
|
440
|
+
|
|
441
|
+
export type GuardPlan =
|
|
442
|
+
| { kind: 'refused'; message: string }
|
|
443
|
+
| { kind: 'nothing'; message: string }
|
|
444
|
+
| { kind: 'plan'; changes: Change[]; patch: (m: Manifest) => void };
|
|
445
|
+
|
|
446
|
+
/** What an install or an uninstall would change, read from the disk and written to nothing. */
|
|
447
|
+
export async function planGuard(ctx: Ctx, action: 'install' | 'uninstall', thresholds: Thresholds | null, t: CliMessages): Promise<GuardPlan> {
|
|
448
|
+
const p = pathsFor(ctx);
|
|
449
|
+
const home = resolve(ctx.home);
|
|
450
|
+
const refuse = (finding: Finding): GuardPlan => ({ kind: 'refused', message: t.proactive.reason[finding.code](finding.params) });
|
|
451
|
+
const file = shown(ctx, p.settings);
|
|
452
|
+
|
|
453
|
+
if (ctx.platform === 'win32') return { kind: 'refused', message: t.sessionGuard.windows() };
|
|
454
|
+
const manifestRead = await readJsonObject(ctx, p.manifest, home);
|
|
455
|
+
if (manifestRead.kind === 'refused') return refuse(manifestRead.finding);
|
|
456
|
+
const manifest = manifestRead.kind === 'ok' ? manifestFrom(manifestRead.value) : emptyManifest();
|
|
457
|
+
const read = await readJsonObject(ctx, p.settings, home);
|
|
458
|
+
if (read.kind === 'refused') return refuse(read.finding);
|
|
459
|
+
const value: Obj = read.kind === 'ok' ? read.value : {};
|
|
460
|
+
const view = viewGuard(value);
|
|
461
|
+
if (view.shape !== null) return { kind: 'refused', message: t.sessionGuard.settingsShape(file, view.shape) };
|
|
462
|
+
|
|
463
|
+
if (action === 'uninstall') {
|
|
464
|
+
if (Object.keys(view.found).length === 0) return { kind: 'nothing', message: t.sessionGuard.nothingToUninstall() };
|
|
465
|
+
const next = structuredClone(value);
|
|
466
|
+
withoutGuard(next, manifest.guard?.created ?? []);
|
|
467
|
+
const madeByUs = manifest.guard?.createdFile === true || manifest.statusline?.createdFile === true;
|
|
468
|
+
const gone = madeByUs && Object.keys(next).length === 0;
|
|
469
|
+
return {
|
|
470
|
+
kind: 'plan',
|
|
471
|
+
changes: [jsonChange('session-guard', p.settings, read, gone ? null : next, false)],
|
|
472
|
+
patch: (m) => {
|
|
473
|
+
delete m.guard;
|
|
474
|
+
},
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
if (thresholds === null) return { kind: 'refused', message: t.sessionGuard.refusedMissing('--warn, --stop, --on-cannot-tell') };
|
|
479
|
+
if (read.kind === 'absent' && !(await stat(join(home, '.claude')).then((info) => info.isDirectory(), () => false))) {
|
|
480
|
+
return { kind: 'refused', message: t.sessionGuard.noClaude(shown(ctx, join(home, '.claude'))) };
|
|
481
|
+
}
|
|
482
|
+
const runtime = await stableRuntime(ctx);
|
|
483
|
+
if (!runtime.ok) return refuse({ code: runtime.code === 'unstable' ? 'cli.unstable' : 'cli.unsafe', params: { path: runtime.path } });
|
|
484
|
+
const next = structuredClone(value);
|
|
485
|
+
const created = withGuard(next, guardCommand(runtime.node, runtime.entry, thresholds));
|
|
486
|
+
const backup = !(manifest.guard?.createdFile === true || manifest.statusline?.createdFile === true);
|
|
487
|
+
const change = jsonChange('session-guard', p.settings, read, next, backup, 0o600);
|
|
488
|
+
if (change.after === change.before) return { kind: 'nothing', message: t.sessionGuard.alreadyInstalled(file) };
|
|
489
|
+
return {
|
|
490
|
+
kind: 'plan',
|
|
491
|
+
changes: [change],
|
|
492
|
+
patch: (m) => {
|
|
493
|
+
m.guard = {
|
|
494
|
+
createdFile: m.guard?.createdFile === true || read.kind === 'absent',
|
|
495
|
+
created: [...new Set([...(m.guard?.created ?? []), ...created])],
|
|
496
|
+
};
|
|
497
|
+
},
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** A write that failed, as the finding `trazum proactive` would report for it. */
|
|
502
|
+
export class GuardWriteFailed extends Error {
|
|
503
|
+
constructor(readonly finding: Finding) {
|
|
504
|
+
super(finding.code);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** Writes a plan through the one door, then the record of it; puts it all back if any write fails. */
|
|
509
|
+
export async function applyGuardPlan(ctx: Ctx, plan: Extract<GuardPlan, { kind: 'plan' }>, action: 'install' | 'uninstall'): Promise<void> {
|
|
510
|
+
const p = pathsFor(ctx);
|
|
511
|
+
const manifestRead = await readJsonObject(ctx, p.manifest, resolve(ctx.home));
|
|
512
|
+
const was = manifestRead.kind === 'ok' ? manifestRead.raw : null;
|
|
513
|
+
const manifest = manifestRead.kind === 'ok' ? manifestFrom(manifestRead.value) : emptyManifest();
|
|
514
|
+
const applied: Change[] = [];
|
|
515
|
+
try {
|
|
516
|
+
for (const change of plan.changes) {
|
|
517
|
+
await applyChange(ctx, change);
|
|
518
|
+
applied.push(change);
|
|
519
|
+
}
|
|
520
|
+
plan.patch(manifest);
|
|
521
|
+
const text = manifestEmpty(manifest) ? null : `${JSON.stringify(manifest, null, 2)}\n`;
|
|
522
|
+
if (text !== was) {
|
|
523
|
+
const change: Change = { item: 'manifest', target: p.manifest, before: was, after: text, mode: 0o600, added: [], removed: [], backup: false };
|
|
524
|
+
await applyChange(ctx, change);
|
|
525
|
+
applied.push(change);
|
|
526
|
+
}
|
|
527
|
+
if (action === 'uninstall') await removeEmptyDir(ctx, p.stateDir);
|
|
528
|
+
} catch (error) {
|
|
529
|
+
const left = await undo(ctx, applied);
|
|
530
|
+
if (left.length > 0) {
|
|
531
|
+
throw new GuardWriteFailed({ code: 'write.partial', params: { files: left.map((target) => shown(ctx, target)).join(', ') } });
|
|
532
|
+
}
|
|
533
|
+
throw new GuardWriteFailed(failure(ctx, error));
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** Which of the two events carry the hook: both, one, or none. */
|
|
538
|
+
export function guardState(view: GuardView): 'on' | 'partial' | 'off' {
|
|
539
|
+
const n = Object.keys(view.found).length;
|
|
540
|
+
return n === GUARD_EVENTS.length ? 'on' : n === 0 ? 'off' : 'partial';
|
|
541
|
+
}
|
package/src/task.ts
CHANGED
|
@@ -1,30 +1,7 @@
|
|
|
1
1
|
import { analyzeTask, compareTasks, parseTaskReport, taskPolicy, MAX_INPUT_CHARS } from '@trazum/core';
|
|
2
|
+
import type { CliMessages } from './i18n/types.js';
|
|
2
3
|
import { changeTaskInstructions, readTaskText, writeTaskText } from './task-files.js';
|
|
3
4
|
|
|
4
|
-
const HELP = `Usage:
|
|
5
|
-
trazum task analyze --id <id> --type <type> --criterion <text>
|
|
6
|
-
--claude-code <file> [--codex <file>] [--claude-code <file> ...]
|
|
7
|
-
[--outcome accepted|rejected|unknown --assessor <label>]
|
|
8
|
-
[--policy baseline|repeat-review-v1] [-o <new-report.json>]
|
|
9
|
-
trazum task policy <report.json> [-o <new-policy.md>]
|
|
10
|
-
trazum task apply <report.json> --instructions <existing-file>
|
|
11
|
-
trazum task revert --instructions <existing-file>
|
|
12
|
-
trazum task compare <before.json> <after.json> [-o <new-comparison.json>]
|
|
13
|
-
|
|
14
|
-
Analyze explicit, complete task sources from Claude Code and Codex locally.
|
|
15
|
-
Repeat the source flags to include sessions from both harnesses. No home scan,
|
|
16
|
-
network access, provider call, hook installation or command execution occurs.
|
|
17
|
-
Up to 16 sources and ${MAX_INPUT_CHARS} characters combined. Do not split one
|
|
18
|
-
session across sources or import the same session more than once.
|
|
19
|
-
Reports and comparisons are JSON by default (--json is also accepted).
|
|
20
|
-
Outcome and assessor are caller declarations, never inferred from usage.
|
|
21
|
-
Policy application adds a small, optional managed block to the file you choose.
|
|
22
|
-
Review the diff and run a comparable task yourself before comparing reports.
|
|
23
|
-
Revert removes only the exact unchanged block. Close other editors while applying
|
|
24
|
-
or reverting. Existing output reports are never overwritten; new files use 0600.
|
|
25
|
-
Repeated tool results may be intentional. A paired comparison is an observation,
|
|
26
|
-
not proof of causal savings, task quality or remaining subscription allowance.
|
|
27
|
-
`;
|
|
28
5
|
|
|
29
6
|
type Parsed = { flags: Map<string, string>; paths: string[]; sources: { format: 'claude-code' | 'codex'; path: string }[] };
|
|
30
7
|
const ALLOWED: Record<string, readonly string[]> = {
|
|
@@ -72,10 +49,15 @@ async function emit(value: string | object, output?: string): Promise<void> {
|
|
|
72
49
|
else process.stdout.write(text);
|
|
73
50
|
}
|
|
74
51
|
|
|
75
|
-
|
|
52
|
+
/**
|
|
53
|
+
* `trazum task`. Its help comes from the reader's catalogue; its errors are
|
|
54
|
+
* raised in English and said in the reader's language where `main` reports
|
|
55
|
+
* them (#871).
|
|
56
|
+
*/
|
|
57
|
+
export async function runTask(args: string[], messages: CliMessages['taskFilter']): Promise<void> {
|
|
76
58
|
if (args.length === 0 || (args.length === 1 && ['--help', '-h'].includes(args[0]!)) ||
|
|
77
59
|
(args.length === 2 && Object.hasOwn(ALLOWED, args[0]!) && ['--help', '-h'].includes(args[1]!))) {
|
|
78
|
-
process.stdout.write(
|
|
60
|
+
process.stdout.write(messages.taskHelp(MAX_INPUT_CHARS));
|
|
79
61
|
return;
|
|
80
62
|
}
|
|
81
63
|
const action = args[0]!;
|
package/src/waste.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `trazum waste`: the files it reads, and nothing else.
|
|
3
|
+
*
|
|
4
|
+
* The analysis is `analyzeSessionWaste` in the core and is pure. This is the
|
|
5
|
+
* part that touches the disk, kept small so what it touches can be said in one
|
|
6
|
+
* place: the session's transcript, the transcripts of its subagents in the
|
|
7
|
+
* folder beside it (as `session-guard` and the status line read them), and the
|
|
8
|
+
* size in bytes of one CLAUDE.md. A `stat` for the size. The content of that
|
|
9
|
+
* file is never opened, and no file is written.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
13
|
+
import { join, resolve } from 'node:path';
|
|
14
|
+
import { jsonlFiles } from './session-guard.js';
|
|
15
|
+
|
|
16
|
+
export type SessionRead =
|
|
17
|
+
| { ok: true; texts: string[] }
|
|
18
|
+
| { ok: false; cause: 'not-found' | 'unreadable' };
|
|
19
|
+
|
|
20
|
+
/** The transcript first, then its subagents' transcripts in a stable order. */
|
|
21
|
+
export async function readSession(target: string): Promise<SessionRead> {
|
|
22
|
+
const info = await stat(target).catch(() => null);
|
|
23
|
+
if (info === null || !info.isFile()) return { ok: false, cause: 'not-found' };
|
|
24
|
+
const subagents = await jsonlFiles(join(target.replace(/\.jsonl$/, ''), 'subagents'));
|
|
25
|
+
if (subagents === null) return { ok: false, cause: 'unreadable' };
|
|
26
|
+
const texts: string[] = [];
|
|
27
|
+
for (const file of [target, ...subagents]) {
|
|
28
|
+
try {
|
|
29
|
+
texts.push(await readFile(file, 'utf8'));
|
|
30
|
+
} catch {
|
|
31
|
+
return { ok: false, cause: 'unreadable' };
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return { ok: true, texts };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A file's size in bytes, or null when it is not a regular file here. Never its content. */
|
|
38
|
+
export async function sizeOf(path: string): Promise<{ path: string; bytes: number } | null> {
|
|
39
|
+
const absolute = resolve(path);
|
|
40
|
+
const info = await stat(absolute).catch(() => null);
|
|
41
|
+
return info !== null && info.isFile() ? { path: absolute, bytes: info.size } : null;
|
|
42
|
+
}
|