Jev-powered verbatim compaction: once context reaches 60%, prunes stale tool calls with zero generation. Skips (never falls back to the LLM summarizer) when…

<img src="docs/repo-hero.png" alt="VexJoy Agent" width="100%">
Essays and writing behind this toolkit live at vexjoy.com.
VexJoy Agent connects plain-English requests to specialist agents, skills, and workflows. /do selects the knowledge and tools needed for your task. Hooks enforce specific checks, and scripts handle repeatable work.
The aim is to give capable models useful domain knowledge without making you learn the toolkit's catalog.
<!-- Counts here must match the Four Layers table (~line 143). Verify both: python3 scripts/validate-doc-counts.py --> 44 agents, 63 skills, 79 hooks, 157 scripts. Agents carry domain knowledge, skills provide reusable methods, hooks enforce selected checks, and scripts handle repeatable plumbing.
Works across Claude Code (/do), Codex ($do), Factory (/do), Reasonix (/do).
$ claude
> /do debug this Go test
Routing: go-engineer + systematic-debugging
Phase 1/4: Reproduce: running test, capturing failure...
Phase 2/4: Hypothesize: 3 candidates from stack trace...
Phase 3/4: Verify: isolated root cause in connection pool timeout
Phase 4/4: Fix: patch applied, test passing, PR opened
✓ Delivered: PR #847, fix connection pool timeout in health check
The router pairs a Go agent with a debugging skill, then follows the task through verification and delivery.
ROUTE PLAN EXECUTE VERIFY DELIVER RECORD
┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐
│ /do │───▶│ Task │───▶│Agent │───▶│Tests │───▶│ PR │───▶│Route │
│Router│ │ Plan │ │+Skill│ │Gates │ │Branch│ │Result│
└──────┘ └──────┘ └──────┘ └──────┘ └──────┘ └──────┘
/d requires TypeSafe's Jev. Jev classifies the request, checks that the selected route preserves the requested outcome, and then dispatches the agent, skill, and pipeline.
Intent preservation is production behavior: /d restates the requested outcome and gates dispatch on a Jev receipt for that exact proposed intent, preventing an agent from quietly expanding an apple into an orchard.
Choose either transport:
# Preferred: Jev through Vercel AI Gateway
export JEV_TRANSPORT=vercel
export AI_GATEWAY_API_KEY=...
# Alternative: Jev's direct API
export JEV_TRANSPORT=direct
export TYPESAFE_API_KEY=...
JEV_TRANSPORT=auto is the default. It prefers Vercel when AI_GATEWAY_API_KEY is set, then uses the direct API when only TYPESAFE_API_KEY is set. An explicit transport never silently switches to the other one. The TypeSafe MCP plugin is not required for /d.
Intent-alignment judgments are recorded in learning.db without raw request text. Receipts keep the Jev judge model separate from the executing agent's configured model and effort level. View proposed-intent difference rates by agent profile, judge model, and transport:
python3 scripts/jev-intent-stats.py --days 30
Example:
> /d fix the flaky test in the payments module
Intent alignment (/d):
-> Restated outcome: Fix the flaky payments test without changing unrelated behavior.
-> Jev: aligned
ROUTING (/d): testing-automation-engineer + testing-preferred-patterns
Source: jev (confidence: medium)
Invoking...
Checks require evidence rather than confidence.
| Agent Says | What Happens |
|---|---|
| "Code looks correct, skip tests" | Exit gate requires test output. Blocked. |
| "Trivial change, no verification" | Hook blocks completion without evidence. |
| "Similar to before" | Skill demands case-specific proof. |
| "User is in a hurry" | Protocol overrides time pressure. |
| "I'm confident" | Gate demands exit code, not assertion. |
Hooks run at configured events. Skills state what to verify; blocking hooks enforce the checks they cover. Coverage depends on the runtime and tool path.
The content engine researches, drafts in a calibrated voice, checks 397 writing patterns, and adapts finished pieces for each platform. /html produces a self-contained report, deck, prototype, chart, or diagram.
Toolkit changes use direct review and relevant checks. Model comparisons can settle specific uncertainties; they are not required for every edit. PHILOSOPHY.md explains the validation policy.
The automated nightly evolution loop (/evolve, writes to evolution-reports/) ran regularly through mid-May 2026. It is currently dormant; recent evidence has come from manual PRs instead.
git clone https://github.com/notque/vexjoy-agent.git ~/vexjoy-agent
cd ~/vexjoy-agent
./install.sh
Installs into ~/.claude/ and into ~/.codex/, ~/.factory/, ~/.hermes/, and ~/.reasonix/ when the runtime command is on PATH or its home directory exists. install.sh wraps the vexinstall engine (scripts/vexinstall/). Each SessionStart in the repo re-syncs through the same engine. Symlinks (default in a git checkout) follow git pull; --copy gives a stable snapshot.
| Flag | Effect |
|---|---|
--dry-run | Print the plan; write nothing |
--target <t> | Only claude, codex, factory, hermes, reasonix, or all |
--no-takeover | Leave old unowned copies in place (default: move them to trash and replace) |
--uninstall / --rollback | Remove owned entries / restore the newest trash and settings backup |
Layout and safety rules: docs/installer-layout.md.
Want only part of the toolkit? Run ./install.sh --configure, or copy .local.example/profile.yaml to .local/profile.yaml and edit it. Without a profile, the full toolkit installs. Details: .local.example/README.md.
| CLI | Entry Point |
|---|---|
| Claude Code | /do |
| Codex | $do |
| Factory | /do |
| Reasonix | /do |
Jev Auto-Compact plugin (optional, requires TYPESAFE_API_KEY):
claude plugin marketplace add ./plugins/jev-auto-compact
claude plugin install jev-auto-compact@jev-auto-compact -y
Replaces generated compaction summaries with Jev-judged verbatim pruning after context reaches 60%. Inspect recorded before/after tokens and duration with python3 scripts/jev-compact-evidence.py.
Full setup: docs/start-here.md
Mirrors agents, skills, and supported hooks into ~/.codex/. Codex v0.144.1+ supports 60 of the 71 unique Claude hook registrations: 30 native, 30 adapter-backed, and 11 unsupported. These are registrations, not unique hook files.
The adapter converts apply_patch operations into the Write/Edit payload expected by existing guards. It cannot intercept writes through unified_exec, unmatched MCP tools, WebSearch, or other unsupported paths. PreCompact and Stop receive less telemetry than in Claude Code. This is expanded compatibility, not full parity.
After install or any hook-definition change, run /hooks in Codex and review the new definitions before trusting them. Codex hash-trusts hook commands and skips changed, unreviewed definitions.
Mirrors agents (as "droids"), skills, and hooks into ~/.factory/. Hook config merges into ~/.factory/settings.json with paths rewritten.
Mirrors skills, 157 scripts, and 10 allowlisted hook registrations into ~/.reasonix/. Reasonix has no agent or custom-command surface; /do arrives as a skill. It exposes four events: PreToolUse, PostToolUse, UserPromptSubmit, and Stop. MCP, model, and permissions in ~/.reasonix/config.json remain user-owned.
The toolkit supplies its own routing, domain knowledge, methodology, and enforcement. The default system prompt duplicates most of that.
claude --system-prompt "."
Strips built-in tool-use instructions. The toolkit's agents, skills, hooks, and CLAUDE.md provide the project-specific guidance.
<!-- Counts here must match the intro line (~line 13). Verify both: python3 scripts/validate-doc-counts.py -->
| Layer | Count | Does |
|---|---|---|
| Agents | 44 | Domain knowledge: idiom tables, failure mode catalogs, error-to-fix mappings |
| Skills | 63 | Reusable guidance and methodology for recurring work. |
| Hooks | 79 | Lifecycle checks, context injection, and telemetry. |
| Scripts | 157 | Repeatable validation, orchestration, and plumbing. |
Full skill catalog: docs/skills.md.
┌─────────────────────────────────────────────────┐
│ SKILL.md │
│ ┌─ Frontmatter ─────────────────────────────┐ │
│ │ triggers, pairs_with, success-criteria │ │
│ └────────────────────────────────────────────┘ │
│ Reference Loading Table (conditional imports) │
│ Phased Instructions (numbered, with gates) │
│ Verification (evidence requirements) │
└─────────────────────────────────────────────────┘
A game built entirely by Claude Code using these agents, skills, and pipelines:
<video src="https://github.com/user-attachments/assets/0e74abeb-dc7e-42ba-8239-a7a98cb1ab09" width="100%" autoplay loop muted playsinline></video>
I just want to use it Install, learn /do, done.
I do knowledge work Writing, research, data analysis, moderation, HTML artifacts. No code.
I'm a developer Architecture, extension points, adding agents and skills.
I'm an AI power user Routing tables, pipelines, hooks, telemetry DB.
I'm an AI agent Machine-dense inventory. Tables, paths, schemas.
Full design philosophy: PHILOSOPHY.md
One report-only script surfaces upkeep work; it prints a digest and never edits, deletes, or blocks.
python3 scripts/stale-skill-scan.py --top 20 ranks stale skills and agents as pruning candidates. Run it quarterly; see docs/deprecation-template.md.Scheduled work follows the same boundary as everything else: judgment uses models; repeatable plumbing uses 157 scripts.
| Need | Use |
|---|---|
| Run a deterministic command on a schedule | scripts/agent-scheduler.py with runner: "command" |
| Run an agent judgment on a schedule, webhook, or file change | scripts/agent-scheduler.py with the default runner: "claude" |
| Install or remove a user crontab entry safely | scripts/crontab-manager.py |
| Audit shell cron reliability | cron-automation |
| Keep one interactive objective moving until criteria verify | objective-loop |
See CONTRIBUTING.md.
MIT. See LICENSE.
hooks/jev-auto-compact.mjs 882 lines1/**
2 * Jev Auto-Compact: constant verbatim compaction via function hooks.
3 *
4 * Two hooks:
5 * turn.complete — triggers $.session.compact() once context >= 60%
6 * session.compact — Jev-judges each tool call, returns pruned {messages}
7 *
8 * Three tiers (programs -> Jev -> no LLM):
9 * Tier 1: pair tool calls with results, pin recent, pre-filter obvious drops
10 * Tier 2: Jev judges ambiguous calls (3 criteria-rich Nouls per call)
11 * Tier 3: not needed -- zero generation, verbatim pruning only
12 *
13 * Zero dependencies. Uses $.http.fetch for Jev API, nothing else external.
14 *
15 * Nothing leaves the host with a secret in it: every message text and tool
16 * input is passed through ./redact.mjs before it enters the Jev state.
17 */
18
19import { redactText, redactToolInput } from './redact.mjs';
20
21// ---------------------------------------------------------------------------
22// Constants
23// ---------------------------------------------------------------------------
24
25const MIN_REDUCTION_RATIO = 0.15;
26/** Context-window percent at which turn.complete triggers a compaction. */
27const COMPACT_AT_PERCENT = 60;
28const PRESERVE_RECENT = 6;
29const KEEP_THRESHOLD = 0.5;
30const TRUNCATE_HEAD_CHARS = 300;
31const MAX_STATE_TOKENS = 12000;
32/**
33 * Jev accepts 64k tokens per request, and `state` plus the longest question
34 * must stay under 32k. The two limits below leave margin for the rough token
35 * estimate. State is billed once per request, so every request should carry
36 * as many questions as fit.
37 */
38const MAX_REQUEST_TOKENS = 56000;
39const STATE_HARD_LIMIT_TOKENS = 28000;
40/** A compaction that needs more requests than this goes to the fallback path. */
41const MAX_REQUESTS_PER_COMPACTION = 4;
42/** Auth and billing failures never succeed on retry; stop sending after one. */
43const STOP_ON_STATUS = new Set([401, 402]);
44const MAX_GOAL_CHARS = 500;
45const ABRIDGE_TEXT_THRESHOLD = 550;
46const ABRIDGE_HEAD = 400;
47const ABRIDGE_TAIL = 150;
48const JEV_URL = 'https://api.typesafe.ai/v1/systemone';
49/** A Jev request that has not answered by now counts as failed, so a hung request cannot hang the session. */
50const JEV_TIMEOUT_MS = 20000;
51const JEV_MODEL = 'jev-1.14.0';
52/**
53 * After a `{skip}` (Jev found nothing to prune) the transcript is unchanged,
54 * so asking again next turn only repeats the same cold-cache Jev pass. Retry
55 * once the conversation has grown by this many messages ...
56 */
57const SKIP_RETRY_MIN_NEW_MESSAGES = 8;
58/** ... or context has risen by this many percentage points. */
59const SKIP_RETRY_MIN_PERCENT = 5;
60
61/** Per-tool threshold overrides (lower = keep more aggressively). */
62const TOOL_THRESHOLDS = { Edit: 0.35, Write: 0.35, NotebookEdit: 0.35 };
63
64// ---------------------------------------------------------------------------
65// Token estimation
66// ---------------------------------------------------------------------------
67
68function estimateTokens(text) {
69 if (!text) return 0;
70 let tokens = 0;
71 for (const ch of text) {
72 if (/[a-zA-Z]/.test(ch)) tokens += 1 / 6;
73 else if (/[0-9]/.test(ch)) tokens += 0.5;
74 else tokens += 0.9;
75 }
76 return Math.floor(tokens) + 1;
77}
78
79// ---------------------------------------------------------------------------
80// Tool call collection from SessionMessage[]
81// ---------------------------------------------------------------------------
82
83function collectCalls(messages) {
84 const uses = new Map();
85 const results = new Map();
86
87 for (let i = 0; i < messages.length; i++) {
88 const msg = messages[i];
89 for (const tu of msg.toolUses || []) {
90 uses.set(tu.tool_use_id, { use: tu, msgIdx: i });
91 }
92 for (const tr of msg.toolResults || []) {
93 results.set(tr.tool_use_id, { result: tr, msgIdx: i });
94 }
95 }
96
97 const total = messages.length;
98 const calls = [];
99 let seq = 0;
100
101 for (const [uid, { use, msgIdx: useIdx }] of uses) {
102 const res = results.get(uid);
103 if (!res) continue;
104 const { result, msgIdx: resIdx } = res;
105
106 seq++;
107 const pinned =
108 useIdx === 0 ||
109 resIdx === 0 ||
110 useIdx >= total - PRESERVE_RECENT ||
111 resIdx >= total - PRESERVE_RECENT;
112
113 const resultText = result.text || '';
114 const inputStr =
115 typeof use.input === 'string' ? use.input : JSON.stringify(use.input || {});
116
117 calls.push({
118 uid,
119 seqId: `t${seq}`,
120 tool: use.tool || 'unknown',
121 input: inputStr,
122 resultText,
123 resultChars: resultText.length,
124 useIdx,
125 resIdx,
126 pinned,
127 isError: result.isError || false,
128 useRef: use,
129 resRef: result,
130 });
131 }
132 return calls;
133}
134
135// ---------------------------------------------------------------------------
136// Tier 1: programmatic pre-filters
137// ---------------------------------------------------------------------------
138
139function prefilter(call) {
140 const { tool, resultChars, isError, input } = call;
141
142 // Obvious keeps: long error results (diagnostic info)
143 if (isError && resultChars > 200) return false;
144
145 // Obvious drops
146 if (tool === 'Glob' || tool === 'ListDirectory') return true;
147
148 if (tool === 'Bash') {
149 let cmd = input;
150 try {
151 const parsed = JSON.parse(input);
152 cmd = parsed.command || input;
153 } catch { /* not JSON, use raw */ }
154 const stripped = cmd.trim();
155 if (['ls', 'pwd', 'ls -la', 'ls -l', 'ls -a'].includes(stripped)) return true;
156 if (stripped.startsWith('git status')) return true;
157 }
158
159 return null; // Jev decides
160}
161
162function prefilterCalls(calls) {
163 const candidates = [];
164 const decisions = {};
165
166 for (const call of calls) {
167 if (call.pinned) {
168 decisions[call.seqId] = { action: 'keep', reason: 'pinned' };
169 continue;
170 }
171 const verdict = prefilter(call);
172 if (verdict === true) {
173 decisions[call.seqId] = { action: 'drop_call', reason: 'prefilter_drop' };
174 } else if (verdict === false) {
175 decisions[call.seqId] = { action: 'keep', reason: 'prefilter_keep' };
176 } else {
177 candidates.push(call);
178 }
179 }
180 return { candidates, decisions };
181}
182
183// ---------------------------------------------------------------------------
184// Multi-stage state fitting (ported from Python jev-compact.py)
185// ---------------------------------------------------------------------------
186
187/** Last three user prompts, redacted. Returns { goal, redactions }. */
188function extractGoal(messages) {
189 const texts = [];
190 let redactions = 0;
191 for (let i = messages.length - 1; i >= 0 && texts.length < 3; i--) {
192 if (messages[i].role === 'user' && messages[i].text) {
193 const r = redactText(messages[i].text);
194 redactions += r.count;
195 texts.unshift(r.text.substring(0, MAX_GOAL_CHARS));
196 }
197 }
198 return { goal: texts.join('\n---\n'), redactions };
199}
200
201// `msg.text` and each call's `input` arrive here already redacted (fitState
202// does that once, before the fitting stages, so a redaction counts once).
203function buildHistoryEntry(msg, idx, callsByMsg, inputLimit, abridge, collapse, pinnedIndices) {
204 const role = msg.role || 'unknown';
205 const text = msg.text || '';
206
207 // Collapse non-pinned messages without tool calls
208 if (collapse && !pinnedIndices.has(idx) && !callsByMsg.has(idx)) {
209 if (!text.trim()) return null;
210 return { i: idx, role, text: `[... ${text.length} chars omitted ...]` };
211 }
212
213 // Abridge long non-pinned text
214 let displayText = text;
215 if (abridge && !pinnedIndices.has(idx) && text.length > ABRIDGE_TEXT_THRESHOLD) {
216 displayText =
217 text.substring(0, ABRIDGE_HEAD) +
218 `\n[... ${text.length - ABRIDGE_HEAD - ABRIDGE_TAIL} chars omitted ...]\n` +
219 text.substring(text.length - ABRIDGE_TAIL);
220 }
221
222 const entry = { i: idx, role, text: displayText };
223
224 const mc = callsByMsg.get(idx);
225 if (mc) {
226 entry.tool_calls = mc.map((c) => ({
227 id: c.seqId,
228 tool: c.tool,
229 input: c.input.substring(0, inputLimit),
230 result: `${c.isError ? 'error' : 'ok'}, ${c.resultChars} chars (omitted)`,
231 }));
232 }
233
234 return entry;
235}
236
237/**
238 * Build the Jev state, shrinking it stage by stage until it fits.
239 * Redacts every message text and tool input first. Returns { state, redactions }.
240 */
241function fitState(rawMessages, rawCalls, goal) {
242 let redactions = 0;
243 const messages = rawMessages.map((m) => {
244 if (!m.text) return m;
245 const r = redactText(m.text);
246 redactions += r.count;
247 return r.count ? { ...m, text: r.text } : m;
248 });
249 const calls = rawCalls.map((c) => {
250 const r = redactToolInput(c.input);
251 redactions += r.count;
252 return r.count ? { ...c, input: r.text } : c;
253 });
254
255 const callsByMsg = new Map();
256 const pinnedIndices = new Set();
257
258 for (const c of calls) {
259 if (!callsByMsg.has(c.useIdx)) callsByMsg.set(c.useIdx, []);
260 callsByMsg.get(c.useIdx).push(c);
261 if (c.pinned) {
262 pinnedIndices.add(c.useIdx);
263 pinnedIndices.add(c.resIdx);
264 }
265 }
266
267 // Pin recent messages and first message
268 const total = messages.length;
269 for (let i = Math.max(0, total - PRESERVE_RECENT); i < total; i++) {
270 pinnedIndices.add(i);
271 }
272 pinnedIndices.add(0);
273
274 const contextText =
275 'A coding assistant conversation is being compacted to free context. ' +
276 '`history` is the whole conversation; tool outputs are replaced by notes. ' +
277 'Each question asks whether one tool call or result still needs to stay verbatim. ' +
278 'Whatever is not kept is deleted permanently, but the assistant can re-run any tool.';
279
280 // Progressive stages: [inputLimit, abridge, collapse, dropTextOnly]
281 const stages = [
282 [1000, false, false, false],
283 [200, false, false, false],
284 [60, false, false, false],
285 [60, true, false, false],
286 [60, true, true, false],
287 [60, true, true, true],
288 ];
289
290 let state;
291 for (const [inputLimit, abridge, collapse, dropTextOnly] of stages) {
292 const history = [];
293 for (let i = 0; i < messages.length; i++) {
294 const entry = buildHistoryEntry(
295 messages[i], i, callsByMsg, inputLimit, abridge, collapse, pinnedIndices
296 );
297 if (entry === null) continue;
298 if (dropTextOnly && !pinnedIndices.has(i) && !callsByMsg.has(i)) continue;
299 history.push(entry);
300 }
301
302 state = { context: contextText, goal, history };
303 const stateStr = JSON.stringify(state);
304 if (estimateTokens(stateStr) <= MAX_STATE_TOKENS) return { state, redactions };
305 }
306
307 return { state, redactions }; // smallest version
308}
309
310// ---------------------------------------------------------------------------
311// Build Jev questions
312// ---------------------------------------------------------------------------
313
314function questionsFor(call) {
315 const { seqId, tool, resultChars } = call;
316 return {
317 [`call_${seqId}`]: {
318 type: 'noul',
319 instructions: {
320 question: `Tool call ${seqId} (${tool}) should stay in the history: knowing this call was made, with its input, still matters for what the assistant does next.`,
321 criteria: {
322 true: 'The call\'s input or the fact it was made is referenced, constrains, or informs later actions.',
323 false: 'The call was exploratory, superseded by a later call to the same tool on the same target, or its input is fully captured in later context.',
324 },
325 },
326 },
327 [`result_${seqId}`]: {
328 type: 'noul',
329 instructions: {
330 question: `The full output of tool call ${seqId} (${tool}, ${resultChars} chars) should stay verbatim: the assistant still needs its contents and re-running the tool would not reproduce it.`,
331 criteria: {
332 true: 'The result contains information not available elsewhere: error details, file contents being modified, test output. Re-running would not reproduce it.',
333 false: 'The result is a simple acknowledgment, a file listing available from later reads, or output reproducible by re-running.',
334 },
335 },
336 },
337 [`referenced_${seqId}`]: {
338 type: 'noul',
339 instructions: {
340 question: `The result of tool call ${seqId} (${tool}) was referenced or used in a later assistant message or tool call input.`,
341 },
342 },
343 };
344}
345
346// ---------------------------------------------------------------------------
347// Batching
348// ---------------------------------------------------------------------------
349
350function batchCalls(candidates, stateTokens) {
351 if (!candidates.length) return [];
352 // State over the hard limit cannot be judged in any request.
353 if (stateTokens > STATE_HARD_LIMIT_TOKENS) return null;
354
355 const available = MAX_REQUEST_TOKENS - stateTokens;
356 const batches = [];
357 let current = [];
358 let used = 0;
359 for (const c of candidates) {
360 const cost = estimateTokens(JSON.stringify(questionsFor(c)));
361 if (current.length > 0 && used + cost > available) {
362 batches.push(current);
363 current = [];
364 used = 0;
365 }
366 current.push(c);
367 used += cost;
368 }
369 if (current.length > 0) batches.push(current);
370
371 // Each request re-sends the whole state. Past the cap the run costs more
372 // than it saves, so the caller takes its fallback path.
373 if (batches.length > MAX_REQUESTS_PER_COMPACTION) return null;
374 return batches;
375}
376
377// ---------------------------------------------------------------------------
378// Jev API call
379// ---------------------------------------------------------------------------
380
381async function callJev(fetchFn, apiKey, state, questions, timeoutMs = JEV_TIMEOUT_MS) {
382 const payload = { model: JEV_MODEL, state, questions };
383 let timer;
384 const timeout = new Promise((_, reject) => {
385 timer = setTimeout(() => reject(new Error('Jev request timed out')), timeoutMs);
386 });
387 let response;
388 try {
389 response = await Promise.race([
390 fetchFn(JEV_URL, {
391 method: 'POST',
392 headers: {
393 Authorization: `Bearer ${apiKey}`,
394 'Content-Type': 'application/json',
395 },
396 body: JSON.stringify(payload),
397 }),
398 timeout,
399 ]);
400 } finally {
401 clearTimeout(timer);
402 }
403
404 if (!response.ok) {
405 const err = new Error(`Jev HTTP ${response.status}`);
406 err.status = response.status; // status only: the body is never logged
407 throw err;
408 }
409
410 const data = JSON.parse(response.text);
411 if (!data.answers) throw new Error('Jev response missing answers');
412 return data;
413}
414
415// ---------------------------------------------------------------------------
416// Decision logic
417// ---------------------------------------------------------------------------
418
419// A Noul is a probability. Anything else (a string, NaN, a value outside
420// [0, 1]) counts as no answer, and no answer keeps the call.
421function noulValue(answers, key) {
422 const a = answers[key];
423 if (!a || typeof a.noul !== 'number' || !Number.isFinite(a.noul)) return null;
424 if (a.noul < 0 || a.noul > 1) return null;
425 return a.noul;
426}
427
428function decideCall(call, keepCall, keepResult, referenced) {
429 const threshold = TOOL_THRESHOLDS[call.tool] || KEEP_THRESHOLD;
430
431 let effectiveResult = keepResult;
432 if (referenced >= 0.6) {
433 effectiveResult = Math.max(keepResult, 0.5 + (referenced - 0.6) * 0.5);
434 }
435
436 if (effectiveResult >= threshold) {
437 return { action: 'keep', reason: 'kept', keepCall, keepResult, referenced };
438 } else if (keepCall >= threshold) {
439 return { action: 'drop_result', reason: 'result_dropped', keepCall, keepResult, referenced };
440 } else {
441 return { action: 'drop_call', reason: 'call_dropped', keepCall, keepResult, referenced };
442 }
443}
444
445// ---------------------------------------------------------------------------
446// Apply decisions to SessionMessage[]
447// ---------------------------------------------------------------------------
448
449function applyDecisions(messages, decisions, calls) {
450 const uidDecision = new Map();
451 for (const call of calls) {
452 const d = decisions[call.seqId];
453 if (d) uidDecision.set(call.uid, d);
454 }
455
456 const result = [];
457 for (const msg of messages) {
458 let changed = false;
459 let newToolUses = msg.toolUses || [];
460 let newToolResults = msg.toolResults || [];
461
462 if (newToolUses.length > 0) {
463 const filtered = newToolUses.filter((tu) => {
464 const d = uidDecision.get(tu.tool_use_id);
465 if (d && d.action === 'drop_call') { changed = true; return false; }
466 return true;
467 });
468 if (filtered.length !== newToolUses.length) {
469 newToolUses = filtered;
470 changed = true;
471 }
472 }
473
474 if (newToolResults.length > 0) {
475 const filtered = [];
476 for (const tr of newToolResults) {
477 const d = uidDecision.get(tr.tool_use_id);
478 if (d && d.action === 'drop_call') { changed = true; continue; }
479 if (d && d.action === 'drop_result') {
480 const text = tr.text || '';
481 if (text.length > TRUNCATE_HEAD_CHARS) {
482 const truncated = text.length - TRUNCATE_HEAD_CHARS;
483 filtered.push({
484 ...tr,
485 text: text.substring(0, TRUNCATE_HEAD_CHARS) +
486 `\n[jev-compact truncated ${truncated} chars; re-run the tool if needed]`,
487 });
488 changed = true;
489 } else {
490 filtered.push(tr);
491 }
492 } else {
493 filtered.push(tr);
494 }
495 }
496 if (changed || filtered.length !== newToolResults.length) {
497 newToolResults = filtered;
498 changed = true;
499 }
500 }
501
502 if (!msg.text && newToolUses.length === 0 && newToolResults.length === 0) continue;
503
504 if (!changed) {
505 result.push(msg);
506 } else {
507 const rebuilt = { ...msg, text: msg.text || '', toolUses: newToolUses };
508 if (newToolResults.length > 0) rebuilt.toolResults = newToolResults;
509 else delete rebuilt.toolResults;
510 result.push(rebuilt);
511 }
512 }
513 return result;
514}
515
516// ---------------------------------------------------------------------------
517// Full compaction pipeline
518// ---------------------------------------------------------------------------
519
520/**
521 * @param {(url, init) => Promise<{status, ok, text}>} fetchFn
522 * @param {string} apiKey
523 * @param {SessionMessage[]} messages
524 * @param {(line: string) => void} [log] status-only diagnostics (never a payload)
525 * @param {{timeoutMs?: number}} [options] per-request timeout in ms
526 */
527export async function compact(fetchFn, apiKey, messages, log = () => {}, { timeoutMs = JEV_TIMEOUT_MS } = {}) {
528 const calls = collectCalls(messages);
529 if (calls.length === 0) return { messages, stats: { totalCalls: 0, ratio: 0, errorBatches: 0, redactions: 0 } };
530
531 // Tier 1: pre-filter
532 const { candidates, decisions } = prefilterCalls(calls);
533 const pinned = Object.values(decisions).filter((d) => d.reason === 'pinned').length;
534 const prefiltered = Object.values(decisions).filter((d) => d.reason === 'prefilter_drop').length;
535
536 if (candidates.length === 0) {
537 const result = applyDecisions(messages, decisions, calls);
538 return {
539 messages: result,
540 decisions,
541 stats: { totalCalls: calls.length, pinned, prefiltered, jevJudged: 0, ratio: 0, errorBatches: 0, redactions: 0 },
542 };
543 }
544
545 // Build state with multi-stage fitting. Nothing below this line may read
546 // `messages` text or `calls[].input` for the Jev payload: only `state`.
547 const { goal, redactions: goalRedactions } = extractGoal(messages);
548 const { state, redactions: stateRedactions } = fitState(messages, calls, goal);
549 const redactions = goalRedactions + stateRedactions;
550 const stateTokens = estimateTokens(JSON.stringify(state));
551
552 // Batch questions to fit Jev limits
553 const batches = batchCalls(candidates, stateTokens);
554 if (batches === null) {
555 log(`[jev-auto-compact] ${candidates.length} tool calls with a ${stateTokens}-token state do not fit in ${MAX_REQUESTS_PER_COMPACTION} Jev requests`);
556 return {
557 messages,
558 decisions,
559 stats: { totalCalls: calls.length, pinned, prefiltered, jevJudged: 0, jevCalls: 0, ratio: 0, errorBatches: 0, redactions, overBudget: true, callLog: [] },
560 };
561 }
562
563 const start = Date.now();
564 const answers = {};
565 let jevCalls = 0;
566 let errorBatches = 0;
567 const callLog = []; // one entry per Jev request, for the call log
568
569 // Process batches sequentially ($.http.fetch may not support concurrent)
570 for (const batch of batches) {
571 const batchQuestions = {};
572 for (const c of batch) {
573 Object.assign(batchQuestions, questionsFor(c));
574 }
575
576 const callStart = Date.now();
577 const callEntry = {
578 ts: new Date(callStart).toISOString(),
579 n_questions: Object.keys(batchQuestions).length,
580 };
581 try {
582 const jevData = await callJev(fetchFn, apiKey, state, batchQuestions, timeoutMs);
583 // Keep only answers to questions this batch asked: a reply must not
584 // overwrite the answer to another batch's call.
585 for (const [id, answer] of Object.entries(jevData.answers || {})) {
586 if (Object.hasOwn(batchQuestions, id)) answers[id] = answer;
587 }
588 jevCalls++;
589 const u = jevData.usage || {};
590 callLog.push({
591 ...callEntry,
592 ok: true,
593 latency_ms: Date.now() - callStart,
594 input_tokens: typeof u.input_tokens === 'number' ? u.input_tokens : null,
595 output_tokens: typeof u.output_tokens === 'number' ? u.output_tokens : null,
596 });
597 } catch (err) {
598 callLog.push({
599 ...callEntry,
600 ok: false,
601 latency_ms: Date.now() - callStart,
602 error: typeof err?.status === 'number' ? `HTTP ${err.status}` : err?.name || 'error',
603 });
604 // On batch failure, keep all calls in this batch (fail-safe). Say so
605 // once per compaction, status only: never the request or response body.
606 errorBatches++;
607 if (errorBatches === 1) {
608 const status = typeof err?.status === 'number' ? `HTTP ${err.status}` : (err?.name || 'error');
609 log(`[jev-auto-compact] Jev batch failed (${status}); keeping its ${batch.length} calls`);
610 }
611 for (const c of batch) {
612 decisions[c.seqId] = { action: 'keep', reason: 'jev_error' };
613 }
614 if (STOP_ON_STATUS.has(err?.status)) {
615 // Keep everything not yet judged and send nothing more.
616 for (const c of candidates) {
617 if (!decisions[c.seqId]) decisions[c.seqId] = { action: 'keep', reason: 'jev_error' };
618 }
619 break;
620 }
621 }
622 }
623
624 const latencyMs = Date.now() - start;
625
626 // Decide per candidate
627 for (const call of candidates) {
628 if (decisions[call.seqId]) continue; // already decided (error fallback)
629 const kc = noulValue(answers, `call_${call.seqId}`);
630 const kr = noulValue(answers, `result_${call.seqId}`);
631 const ref = noulValue(answers, `referenced_${call.seqId}`);
632
633 if (kc === null) {
634 decisions[call.seqId] = { action: 'keep', reason: 'missing_answer' };
635 } else {
636 decisions[call.seqId] = decideCall(call, kc, kr ?? 0.5, ref ?? 0.5);
637 }
638 }
639
640 // Apply
641 const result = applyDecisions(messages, decisions, calls);
642 const kept = Object.values(decisions).filter((d) => d.action === 'keep').length;
643 const droppedResult = Object.values(decisions).filter((d) => d.action === 'drop_result').length;
644 const droppedCall = Object.values(decisions).filter((d) => d.action === 'drop_call').length;
645
646 const origLen = JSON.stringify(messages).length;
647 const resultLen = JSON.stringify(result).length;
648 const ratio = origLen > 0 ? 1 - resultLen / origLen : 0;
649
650 return {
651 messages: result,
652 decisions,
653 stats: {
654 totalCalls: calls.length,
655 pinned,
656 prefiltered,
657 jevJudged: candidates.length,
658 kept,
659 droppedResult,
660 droppedCall,
661 ratio: Math.round(ratio * 10000) / 10000,
662 latencyMs,
663 jevCalls,
664 errorBatches,
665 redactions,
666 callLog,
667 },
668 };
669}
670
671// ---------------------------------------------------------------------------
672// Evidence: bounded ring buffer in the plugin's own $.store (a JSON file the
673// engine keeps under the user's Claude Code config dir). $.fs.write to a
674// home-dir path is refused by the plugin sandbox, so the store is the one
675// durable place. scripts/jev-compact-evidence.py ingests it into learning.db.
676// ---------------------------------------------------------------------------
677
678const EVIDENCE_KEY = 'events';
679const EVIDENCE_MAX = 500;
680
681async function appendEvidence($, record) {
682 try {
683 const prior = await $.store.get(EVIDENCE_KEY);
684 let events = Array.isArray(prior) ? prior : [];
685 events.push(...(Array.isArray(record) ? record : [record]));
686 if (events.length > EVIDENCE_MAX) events = events.slice(-EVIDENCE_MAX);
687 await $.store.set(EVIDENCE_KEY, events);
688 } catch (error) {
689 // Evidence is best-effort; never let it break compaction. Say why once.
690 $.ui.log(`[jev-auto-compact] evidence not recorded (${error instanceof Error ? error.message : String(error)})`);
691 }
692}
693
694async function safeUsage($) {
695 try {
696 const u = await $.session.usage();
697 return {
698 tokens: u?.context?.tokens ?? null,
699 window: u?.context?.window ?? null,
700 percent: u?.context?.percent ?? null,
701 cost_usd: u?.cost?.usd ?? null,
702 };
703 } catch {
704 return { tokens: null, window: null, percent: null, cost_usd: null };
705 }
706}
707
708async function safeSessionId($) {
709 try {
710 return await $.session.id();
711 } catch {
712 return null;
713 }
714}
715
716function pct(ratio) {
717 return `${(ratio * 100).toFixed(0)}%`;
718}
719
720// ---------------------------------------------------------------------------
721// Plugin registration
722// ---------------------------------------------------------------------------
723
724/** @type {import('claude-code').Register} */
725export const register = (on, options) => {
726 let compacting = false;
727 /** Set when a plugin-triggered compaction answered {skip}: the transcript
728 * size it saw. turn.complete does not re-trigger until it has grown. */
729 let skippedAt = null; // { messages: number, percent: number|null }
730
731 on('session.compact', async ($, event, next) => {
732 const trigger = event.trigger || 'unknown';
733
734 // precompute installs nothing; a subagent's own transcript is covered by
735 // the PreCompact Python hook (function hooks only see the main loop).
736 if (trigger === 'precompute' || event.agentId) return next(event);
737
738 const startedAt = Date.now();
739 const ts = new Date(startedAt).toISOString();
740 const sessionId = await safeSessionId($);
741 const usage = await safeUsage($);
742 const base = {
743 kind: 'compaction',
744 session_id: sessionId,
745 ts,
746 source: 'plugin',
747 trigger,
748 messages_before: event.messages.length,
749 tokens_before: usage.tokens,
750 };
751
752 try {
753 const apiKey =
754 (await $.env.get('TYPESAFE_API_KEY')) ||
755 ((await $.settings.read())?.env || {})['TYPESAFE_API_KEY'];
756
757 if (!apiKey) {
758 $.ui.log('[jev-auto-compact] no TYPESAFE_API_KEY, falling back to built-in');
759 await appendEvidence($, { ...base, engine: 'builtin', note: 'no api key' });
760 return next(event);
761 }
762
763 const fetchFn = async (url, init) => {
764 const resp = await $.http.fetch(url, init);
765 return { status: resp.status, ok: resp.ok, text: resp.text };
766 };
767
768 const result = await compact(fetchFn, apiKey, event.messages, (line) => $.ui.log(line));
769 const { stats } = result;
770 if (Array.isArray(stats.callLog) && stats.callLog.length > 0) {
771 await appendEvidence(
772 $,
773 stats.callLog.map((c) => ({ kind: 'jev_call', session_id: sessionId, ...c }))
774 );
775 }
776 const statsRecord = {
777 messages_after: result.messages.length,
778 reduction_ratio: stats.ratio,
779 dropped_calls: stats.droppedCall ?? 0,
780 truncated_results: stats.droppedResult ?? 0,
781 pinned: stats.pinned ?? 0,
782 prefiltered: stats.prefiltered ?? 0,
783 jev_judged: stats.jevJudged ?? 0,
784 jev_api_calls: stats.jevCalls ?? 0,
785 jev_error_batches: stats.errorBatches ?? 0,
786 redactions: stats.redactions ?? 0,
787 latency_ms: stats.latencyMs ?? 0,
788 duration_ms: Date.now() - startedAt,
789 };
790
791 if (stats.ratio < MIN_REDUCTION_RATIO) {
792 if (trigger === 'plugin') {
793 // We asked for this compaction and Jev found nothing worth pruning.
794 // Leave the conversation as it is: never hand a self-triggered
795 // compaction to the built-in summarizer (minutes of LLM time).
796 const reason = stats.overBudget
797 ? 'too large for one Jev pass'
798 : `nothing to prune (${pct(stats.ratio)} < ${pct(MIN_REDUCTION_RATIO)} min)`;
799 $.ui.log(`[jev-auto-compact] skipped: ${reason}`);
800 await appendEvidence($, { ...base, ...statsRecord, engine: 'skipped', note: reason });
801 skippedAt = { messages: event.messages.length, percent: usage.percent };
802 return { skip: `jev-auto-compact: ${reason}` };
803 }
804 // The engine or the user needs this compaction; Jev alone is not
805 // enough, so the built-in summarizer runs.
806 const reason = stats.overBudget
807 ? 'too large for one Jev pass'
808 : `${pct(stats.ratio)} < ${pct(MIN_REDUCTION_RATIO)} min`;
809 $.ui.log(`[jev-auto-compact] fallback to built-in (${reason})`);
810 await appendEvidence($, { ...base, ...statsRecord, engine: 'builtin', note: reason });
811 return next(event);
812 }
813
814 $.ui.log(
815 `[jev-auto-compact] ${result.messages.length}/${event.messages.length} msgs, ` +
816 `${pct(stats.ratio)} reduction, ` +
817 `${stats.droppedCall} dropped, ${stats.droppedResult} truncated, ` +
818 `${stats.pinned} pinned, ${stats.prefiltered} prefiltered ` +
819 `(${stats.latencyMs}ms, ${stats.jevJudged} Jev-judged, ${stats.jevCalls} API calls` +
820 (stats.errorBatches ? `, ${stats.errorBatches} failed` : '') +
821 `, redactions: ${stats.redactions ?? 0}` +
822 (usage.tokens ? `, ctx ${usage.tokens} tokens before)` : ')')
823 );
824 await appendEvidence($, { ...base, ...statsRecord, engine: 'jev' });
825 skippedAt = null;
826
827 const compacted = { messages: result.messages };
828 if (typeof usage.tokens === 'number') compacted.tokensBefore = usage.tokens;
829 return compacted;
830 } catch (error) {
831 const message = error instanceof Error ? error.message : String(error);
832 $.ui.log(`[jev-auto-compact] fallback to built-in (${message})`);
833 await appendEvidence($, { ...base, engine: 'error', note: message.substring(0, 200) });
834 return next(event);
835 }
836 });
837
838 on('turn.complete', async ($, event, next) => {
839 // Main-loop turns only; a subagent's turn.complete carries agentId.
840 if (event.agentId || compacting) return next(event);
841 try {
842 compacting = true;
843 const usage = await safeUsage($);
844 const sessionId = await safeSessionId($);
845 await appendEvidence($, {
846 kind: 'usage',
847 session_id: sessionId,
848 ts: new Date().toISOString(),
849 phase: 'turn_complete',
850 context_tokens: usage.tokens,
851 context_window: usage.window,
852 context_percent: usage.percent,
853 cost_usd: usage.cost_usd,
854 });
855 // Threshold-gated. Every compaction is a cold KV-cache rewrite of the
856 // whole prefix (measured: ~$2 vs ~$0.44 for a normal turn), so firing
857 // every turn multiplies cost with no benefit. Fire only when context is
858 // genuinely filling; if usage is unavailable, do nothing.
859 if (typeof usage.percent !== 'number' || usage.percent < COMPACT_AT_PERCENT) {
860 return next(event);
861 }
862 if (skippedAt) {
863 // The last self-triggered compaction found nothing to prune. Re-ask
864 // only once the conversation has moved on enough for a new answer.
865 const messageCount = (await $.session.messages()).length;
866 const grewBy = messageCount - skippedAt.messages;
867 const roseBy = typeof skippedAt.percent === 'number' ? usage.percent - skippedAt.percent : Infinity;
868 if (grewBy < SKIP_RETRY_MIN_NEW_MESSAGES && roseBy < SKIP_RETRY_MIN_PERCENT) return next(event);
869 }
870 $.ui.log(`[jev-auto-compact] context at ${usage.percent.toFixed(0)}% >= ${COMPACT_AT_PERCENT}%, compacting`);
871 await $.session.compact();
872 } catch (error) {
873 $.ui.log(
874 `[jev-auto-compact] auto-compact skipped (${error instanceof Error ? error.message : String(error)})`
875 );
876 } finally {
877 compacting = false;
878 }
879 return next(event);
880 });
881};
882hooks/redact.mjs 129 lines1/**
2 * Secret redaction for text that leaves the host to the Jev API.
3 *
4 * Owner rule: nothing leaves the host to Jev with a secret in it. Every tool
5 * input and message text passes through `redactText` before it enters the
6 * compaction state; tool inputs that name a protected path are withheld whole.
7 *
8 * TYPE names are shared with the Python twin (`scripts/jev_redact.py`):
9 * bearer, cookie, jwt, aws_key, aws_secret, github, openai, slack, google,
10 * gitlab, npm, huggingface, vercel, docker, pem, url_credentials, kv_secret, entropy
11 *
12 * Replacement: `<redacted:TYPE:last4>` when the value is >= 12 chars,
13 * `<redacted:TYPE>` otherwise. Zero dependencies.
14 */
15
16const MIN_LAST4_LEN = 12;
17const MARK = '<redacted:';
18
19export function mark(type, value) {
20 const v = String(value ?? '');
21 return v.length >= MIN_LAST4_LEN ? `${MARK}${type}:${v.slice(-4)}>` : `${MARK}${type}>`;
22}
23
24// PEM armor, assembled from pieces so a secret scanner never sees a
25// key-shaped literal in this source file.
26const ARMOR = '-'.repeat(5);
27const PEM_BLOCK = new RegExp(
28 `${ARMOR}BEGIN [A-Z ]*PRIVATE KEY${ARMOR}[\\s\\S]*?${ARMOR}END [A-Z ]*PRIVATE KEY${ARMOR}`,
29 'g'
30);
31
32// Each rule: [type, regex, replacer(match, ...groups) -> string]. Order matters:
33// multi-line and structured forms first, the generic KEY=VALUE rule last, and
34// a value already marked `<redacted:` is never redacted twice.
35const RULES = [
36 ['pem', PEM_BLOCK, (m) => mark('pem', m)],
37 ['url_credentials', /\b([a-z][a-z0-9+.-]*:\/\/)(?!<redacted:)([^\s/:@<]+):([^\s/@<]+)@/gi,
38 (m, scheme, user, pass) => `${scheme}${mark('url_credentials', `${user}:${pass}`)}@`],
39 // JWT before bearer: `Bearer eyJ...` is reported as a jwt, the more specific type.
40 ['jwt', /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\b/g,
41 (m) => mark('jwt', m)],
42 // Header with a scheme (Bearer/Basic/Token) or a bare `Bearer x`/`Basic x`.
43 ['bearer', /\b(authorization\s*[:=]\s*["']?)(bearer|basic|token)(\s+)(?!<redacted:)([A-Za-z0-9\-._~+/]+=*)/gi,
44 (m, hdr, scheme, sp, tok) => `${hdr}${scheme}${sp}${mark('bearer', tok)}`],
45 ['bearer', /(?<!redacted:)\b(bearer|basic)(\s+)(?!<redacted:)([A-Za-z0-9\-._~+/]{8,}=*)/gi,
46 (m, scheme, sp, tok) => `${scheme}${sp}${mark('bearer', tok)}`],
47 // Header with no scheme: the whole value is the credential.
48 ['bearer', /\b(authorization\s*[:=]\s*["']?)(?!<redacted:)(?!bearer\b|basic\b|token\b)([^\s"',;<>]{8,})/gi,
49 (m, hdr, tok) => `${hdr}${mark('bearer', tok)}`],
50 // Not preceded by `:` or a word char: the `cookie:xxxx>` inside a mark is not a header.
51 ['cookie', /(?<![:\w])((?:set-)?cookie\s*[:=]\s*["']?)([^\s"'<][^\r\n"']*)/gi,
52 (m, hdr, val) => `${hdr}${mark('cookie', val)}`],
53 ['aws_secret', /\b(aws_secret_access_key|aws[_-]?secret(?:[_-]?key)?)(\s*[:=]\s*["']?)(?!<redacted:)([A-Za-z0-9/+=]{40})\b/gi,
54 (m, key, sep, val) => `${key}${sep}${mark('aws_secret', val)}`],
55 ['aws_key', /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g, (m) => mark('aws_key', m)],
56 ['github', /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g, (m) => mark('github', m)],
57 ['openai', /\bsk-(?:proj-|live-|test-)?[A-Za-z0-9_-]{16,}\b|\bsk_(?:live|test)_[A-Za-z0-9]{8,}\b/g,
58 (m) => mark('openai', m)],
59 ['slack', /\bxox[abp]-[A-Za-z0-9-]{10,}\b/g, (m) => mark('slack', m)],
60 ['google', /\bAIza[0-9A-Za-z_-]{35}\b/g, (m) => mark('google', m)],
61 ['gitlab', /\bglpat-[A-Za-z0-9_-]{20,}/g, (m) => mark('gitlab', m)],
62 ['npm', /\bnpm_[A-Za-z0-9]{30,}\b/g, (m) => mark('npm', m)],
63 ['huggingface', /\bhf_[A-Za-z0-9]{30,}\b/g, (m) => mark('huggingface', m)],
64 ['vercel', /\bvck_[A-Za-z0-9_-]{20,}/g, (m) => mark('vercel', m)],
65 ['docker', /\bdckr_pat_[A-Za-z0-9_-]{20,}/g, (m) => mark('docker', m)],
66 // A key inside an existing mark (`<redacted:kv_secret:…`) is never a key,
67 // and a value never spans into a mark's `<`/`>`.
68 ['kv_secret',
69 /(?<!redacted:)\b([A-Za-z0-9_.-]*(?:secret|token|passw|api[_-]?key|private|credential|auth)[A-Za-z0-9_.-]*)("?\s*[:=]\s*["']?)(?!<redacted:)([^\s"',;<>]{8,})/gi,
70 (m, key, sep, val) => `${key}${sep}${mark('kv_secret', val)}`],
71 // A bare long token next to a key name with no `=`/`:` between them
72 // (`token <32+ chars>`). Twin of the `entropy` rule in scripts/jev_redact.py.
73 ['entropy',
74 /(?<!redacted:)\b([A-Za-z0-9_.-]*(?:secret|token|passw|api[_-]?key|private|credential|auth)[A-Za-z0-9_.-]*\W{1,6})((?:[A-Za-z0-9+/=_-]{32,}|[0-9a-f]{32,}))/gi,
75 (m, head, val) => `${head}${mark('entropy', val)}`],
76];
77
78/**
79 * Redact secrets in `text`.
80 * @param {string} text
81 * @returns {{ text: string, count: number }}
82 */
83export function redactText(text) {
84 let out = String(text ?? '');
85 if (!out) return { text: out, count: 0 };
86 let count = 0;
87 for (const [, re, fn] of RULES) {
88 out = out.replace(re, (...args) => {
89 count++;
90 return fn(...args);
91 });
92 }
93 return { text: out, count };
94}
95
96// A tool input that names one of these is withheld whole: its content is a
97// credential file by construction, and a path alone says enough to Jev.
98const PROTECTED_PATH = new RegExp(
99 [
100 String.raw`(?:^|[\s"'=/\\])\.env(?:\.[A-Za-z0-9_-]+)?\b`,
101 String.raw`\.pem\b`,
102 String.raw`\.key\b`,
103 String.raw`(?:^|[\s"'=/\\])id_[A-Za-z0-9]+\b`,
104 String.raw`\.ssh[/\\]`,
105 String.raw`\.aws[/\\]`,
106 String.raw`\.gnupg[/\\]`,
107 String.raw`\btoken\.json\b`,
108 String.raw`\bcredentials[^/\\\s"']*`,
109 ].join('|'),
110 'i'
111);
112
113export const WITHHELD_INPUT = '[input withheld: protected path]';
114
115/** True when a tool input string names a protected path. */
116export function namesProtectedPath(input) {
117 return PROTECTED_PATH.test(String(input ?? ''));
118}
119
120/**
121 * Redact a tool input: withheld whole for a protected path, else redactText.
122 * A withheld input counts as one redaction.
123 * @returns {{ text: string, count: number }}
124 */
125export function redactToolInput(input) {
126 if (namesProtectedPath(input)) return { text: WITHHELD_INPUT, count: 1 };
127 return redactText(input);
128}
129