@openclaw/tokenjuice 2026.9.4 → 2026.9.6
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/assets/activity.svg +3 -0
- package/assets/icon.png +0 -0
- package/node_modules/tokenjuice/README.md +10 -1
- package/node_modules/tokenjuice/dist/cli/install-output.d.ts +7 -0
- package/node_modules/tokenjuice/dist/cli/install-output.js +19 -0
- package/node_modules/tokenjuice/dist/cli/main.d.ts +7 -0
- package/node_modules/tokenjuice/dist/cli/main.js +201 -36
- package/node_modules/tokenjuice/dist/core/analysis.js +3 -3
- package/node_modules/tokenjuice/dist/core/artifacts.d.ts +6 -1
- package/node_modules/tokenjuice/dist/core/artifacts.js +122 -45
- package/node_modules/tokenjuice/dist/core/bounded-jsonl.d.ts +26 -0
- package/node_modules/tokenjuice/dist/core/bounded-jsonl.js +407 -0
- package/node_modules/tokenjuice/dist/core/compaction-metadata.d.ts +1 -1
- package/node_modules/tokenjuice/dist/core/integrations/compact-bash-result.d.ts +2 -0
- package/node_modules/tokenjuice/dist/core/integrations/compact-bash-result.js +3 -2
- package/node_modules/tokenjuice/dist/core/reduce.js +23 -10
- package/node_modules/tokenjuice/dist/core/text.d.ts +4 -0
- package/node_modules/tokenjuice/dist/core/text.js +32 -0
- package/node_modules/tokenjuice/dist/core/wrap.js +1 -1
- package/node_modules/tokenjuice/dist/hosts/codex/index.d.ts +31 -1
- package/node_modules/tokenjuice/dist/hosts/codex/index.js +554 -288
- package/node_modules/tokenjuice/dist/hosts/droid/index.js +12 -3
- package/node_modules/tokenjuice/dist/hosts/grok-bot/index.d.ts +25 -0
- package/node_modules/tokenjuice/dist/hosts/grok-bot/index.js +644 -0
- package/node_modules/tokenjuice/dist/hosts/opencode/extension/runtime.js +644 -279
- package/node_modules/tokenjuice/dist/hosts/pi/extension/runtime.js +647 -282
- package/node_modules/tokenjuice/dist/hosts/shared/hook-command-doctor.d.ts +24 -0
- package/node_modules/tokenjuice/dist/hosts/shared/hook-command-doctor.js +80 -1
- package/node_modules/tokenjuice/dist/hosts/shared/hook-command.d.ts +19 -0
- package/node_modules/tokenjuice/dist/hosts/shared/hook-command.js +61 -6
- package/node_modules/tokenjuice/dist/hosts/shared/hook-doctor.d.ts +3 -1
- package/node_modules/tokenjuice/dist/hosts/shared/hook-doctor.js +2 -0
- package/node_modules/tokenjuice/dist/hosts/shared/host-command.d.ts +10 -1
- package/node_modules/tokenjuice/dist/hosts/shared/host-command.js +43 -4
- package/node_modules/tokenjuice/dist/hosts/shared/pre-tool-wrap.js +9 -7
- package/node_modules/tokenjuice/dist/index.d.ts +3 -1
- package/node_modules/tokenjuice/dist/index.js +2 -1
- package/node_modules/tokenjuice/dist/types.d.ts +15 -0
- package/node_modules/tokenjuice/package.json +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +8 -6
|
@@ -1,27 +1,35 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { mkdir, lstat, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { delimiter, dirname, join } from "node:path";
|
|
4
5
|
import { homedir } from "node:os";
|
|
5
6
|
import packageJson from "../../../package.json" with { type: "json" };
|
|
6
7
|
import { stripLeadingCdPrefix } from "../../core/command.js";
|
|
7
|
-
import {
|
|
8
|
+
import { getTelemetryCommandFamily, shouldRecordStats, storeArtifact, tryStoreArtifactMetadata } from "../../core/artifacts.js";
|
|
9
|
+
import { appendBoundedJsonl } from "../../core/bounded-jsonl.js";
|
|
10
|
+
import { readNoOmissionFromEnv } from "../../core/env.js";
|
|
8
11
|
import { compactBashResult, getOutputAwareInspectionSkipReason } from "../../core/integrations/compact-bash-result.js";
|
|
9
12
|
import { classifyOnly } from "../../core/reduce.js";
|
|
10
|
-
import { countTextChars, stripAnsi } from "../../core/text.js";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
+
import { countTextChars, sliceTextChars, stripAnsi } from "../../core/text.js";
|
|
14
|
+
import { isNodeExecutablePath, parseShellWords } from "../shared/hook-command.js";
|
|
15
|
+
import { buildTokenjuiceHookCommand, isExecutableFile } from "../shared/host-command.js";
|
|
16
|
+
import { inspectTokenjuiceHookCommand } from "../shared/hook-command-doctor.js";
|
|
13
17
|
const GENERIC_FALLBACK_MIN_SAVED_CHARS = 120;
|
|
14
18
|
const GENERIC_FALLBACK_MAX_RATIO = 0.75;
|
|
15
19
|
const HOOK_REWRITE_MIN_SAVED_CHARS = 8;
|
|
20
|
+
const CODEX_HOOK_MAX_COMPACTION_BYTES = 1 * 1024 * 1024;
|
|
16
21
|
const CODEX_HOOK_LAST_LOG = "tokenjuice-hook.last.json";
|
|
17
|
-
const
|
|
18
|
-
const
|
|
19
|
-
const CODEX_HOOK_HISTORY_LOCK_STALE_MS = 30_000;
|
|
20
|
-
const CODEX_HOOK_HISTORY_LOCK_RETRY_MS = 25;
|
|
21
|
-
const CODEX_HOOK_HISTORY_LOCK_RETRIES = 8;
|
|
22
|
+
const CODEX_HOOK_HISTORY_DIRECTORY = "tokenjuice-hook.history-v1";
|
|
23
|
+
const CODEX_HOOK_HISTORY_PREFIX = "events";
|
|
22
24
|
const LOW_NON_TOKENJUICE_TIMEOUT_SECONDS = 2;
|
|
23
25
|
const RECOMMENDED_NON_TOKENJUICE_TIMEOUT_SECONDS = 6;
|
|
24
|
-
const TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS =
|
|
26
|
+
const TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS = 30;
|
|
27
|
+
const CODEX_HOOK_INTEGRATION_ID = "tokenjuice.post-tool-use";
|
|
28
|
+
function validateCodexOmissionPolicy(options) {
|
|
29
|
+
if (options.noOmit && options.allowOmit) {
|
|
30
|
+
throw new Error("Codex noOmit and allowOmit policies cannot be enabled together");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
25
33
|
const TOKENJUICE_CODEX_STATUS = "compacting bash output with tokenjuice";
|
|
26
34
|
const TOKENJUICE_CODEX_FIX_COMMAND = "tokenjuice install codex";
|
|
27
35
|
function getCodexHome() {
|
|
@@ -196,65 +204,18 @@ function parseCodexRuntimeConfig(source) {
|
|
|
196
204
|
}
|
|
197
205
|
return values;
|
|
198
206
|
}
|
|
199
|
-
async function isExecutableFile(path) {
|
|
200
|
-
try {
|
|
201
|
-
await access(path, fsConstants.X_OK);
|
|
202
|
-
return true;
|
|
203
|
-
}
|
|
204
|
-
catch {
|
|
205
|
-
return false;
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
async function resolveInstalledTokenjuicePath() {
|
|
209
|
-
const pathValue = process.env.PATH;
|
|
210
|
-
if (!pathValue) {
|
|
211
|
-
return undefined;
|
|
212
|
-
}
|
|
213
|
-
const candidateNames = process.platform === "win32"
|
|
214
|
-
? ["tokenjuice.exe", "tokenjuice.cmd", "tokenjuice.bat", "tokenjuice"]
|
|
215
|
-
: ["tokenjuice"];
|
|
216
|
-
for (const segment of pathValue.split(delimiter)) {
|
|
217
|
-
if (!segment) {
|
|
218
|
-
continue;
|
|
219
|
-
}
|
|
220
|
-
for (const candidateName of candidateNames) {
|
|
221
|
-
const candidatePath = join(segment, candidateName);
|
|
222
|
-
if (await isExecutableFile(candidatePath)) {
|
|
223
|
-
return candidatePath;
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
return undefined;
|
|
228
|
-
}
|
|
229
207
|
async function buildCodexHookCommand(options = {}) {
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
}
|
|
236
|
-
if (!options.local) {
|
|
237
|
-
const installedBinaryPath = await resolveInstalledTokenjuicePath();
|
|
238
|
-
if (installedBinaryPath) {
|
|
239
|
-
return `${shellQuote(installedBinaryPath)} codex-post-tool-use`;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
if (binaryPath.endsWith(".js")) {
|
|
243
|
-
return `${shellQuote(nodePath)} ${shellQuote(binaryPath)} codex-post-tool-use`;
|
|
244
|
-
}
|
|
245
|
-
return `${shellQuote(binaryPath)} codex-post-tool-use`;
|
|
208
|
+
const command = await buildTokenjuiceHookCommand("codex-post-tool-use", "codex", {
|
|
209
|
+
...options,
|
|
210
|
+
pinNodeForJavaScriptLauncher: true,
|
|
211
|
+
});
|
|
212
|
+
return options.noOmit ? `${command} --no-omit` : command;
|
|
246
213
|
}
|
|
247
|
-
function getCodexFixCommand(local = false) {
|
|
248
|
-
return
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
await access(path);
|
|
253
|
-
return true;
|
|
254
|
-
}
|
|
255
|
-
catch {
|
|
256
|
-
return false;
|
|
257
|
-
}
|
|
214
|
+
function getCodexFixCommand(local = false, noOmit = false) {
|
|
215
|
+
return [
|
|
216
|
+
local ? "tokenjuice install codex --local" : TOKENJUICE_CODEX_FIX_COMMAND,
|
|
217
|
+
...(noOmit ? ["--no-omit"] : []),
|
|
218
|
+
].join(" ");
|
|
258
219
|
}
|
|
259
220
|
async function newestMtimeMs(path) {
|
|
260
221
|
try {
|
|
@@ -298,6 +259,16 @@ function stringifyToolResponse(value) {
|
|
|
298
259
|
return "";
|
|
299
260
|
}
|
|
300
261
|
if (typeof value === "string") {
|
|
262
|
+
try {
|
|
263
|
+
const parsed = JSON.parse(value);
|
|
264
|
+
if (isRecord(parsed)
|
|
265
|
+
&& ["output", "text", "stdout", "stderr", "combinedText"].some((key) => key in parsed)) {
|
|
266
|
+
return stringifyToolResponse(parsed);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
// Plain output is expected to be much more common than a JSON-string envelope.
|
|
271
|
+
}
|
|
301
272
|
return value;
|
|
302
273
|
}
|
|
303
274
|
if (Array.isArray(value)) {
|
|
@@ -307,11 +278,20 @@ function stringifyToolResponse(value) {
|
|
|
307
278
|
.join("\n");
|
|
308
279
|
}
|
|
309
280
|
if (isRecord(value)) {
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
281
|
+
const combinedText = value.combinedText;
|
|
282
|
+
if (typeof combinedText === "string" && combinedText) {
|
|
283
|
+
return combinedText;
|
|
284
|
+
}
|
|
285
|
+
const stdout = typeof value.stdout === "string" ? value.stdout : "";
|
|
286
|
+
const stderr = typeof value.stderr === "string" ? value.stderr : "";
|
|
287
|
+
const output = typeof value.output === "string" ? value.output : "";
|
|
288
|
+
const text = typeof value.text === "string" ? value.text : "";
|
|
289
|
+
const primary = stdout || output || text;
|
|
290
|
+
if (primary && stderr) {
|
|
291
|
+
return [`[stdout]`, primary, `[stderr]`, stderr].join("\n");
|
|
292
|
+
}
|
|
293
|
+
if (primary || stderr) {
|
|
294
|
+
return primary || stderr;
|
|
315
295
|
}
|
|
316
296
|
return JSON.stringify(value);
|
|
317
297
|
}
|
|
@@ -330,33 +310,55 @@ function createTokenjuiceCodexHook(command) {
|
|
|
330
310
|
],
|
|
331
311
|
};
|
|
332
312
|
}
|
|
333
|
-
function
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|| command.includes("post_tool_use_tokenjuice.py");
|
|
339
|
-
});
|
|
313
|
+
function isTokenjuiceCodexHookCommand(hook) {
|
|
314
|
+
const command = typeof hook.command === "string" ? hook.command : "";
|
|
315
|
+
return hook.statusMessage === TOKENJUICE_CODEX_STATUS
|
|
316
|
+
|| command.includes("codex-post-tool-use")
|
|
317
|
+
|| command.includes("post_tool_use_tokenjuice.py");
|
|
340
318
|
}
|
|
341
|
-
function
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
319
|
+
function splitTokenjuiceCodexHooks(groups) {
|
|
320
|
+
const retained = [];
|
|
321
|
+
const owned = [];
|
|
322
|
+
let removed = 0;
|
|
323
|
+
let hasMixedGroup = false;
|
|
324
|
+
for (const group of groups) {
|
|
325
|
+
const tokenjuiceHooks = group.hooks.filter(isTokenjuiceCodexHookCommand);
|
|
326
|
+
if (tokenjuiceHooks.length === 0) {
|
|
327
|
+
retained.push(group);
|
|
347
328
|
continue;
|
|
348
329
|
}
|
|
349
|
-
const
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
if (hook) {
|
|
356
|
-
return hook;
|
|
330
|
+
const otherHooks = group.hooks.filter((hook) => !isTokenjuiceCodexHookCommand(hook));
|
|
331
|
+
removed += tokenjuiceHooks.length;
|
|
332
|
+
owned.push({ ...group, hooks: tokenjuiceHooks });
|
|
333
|
+
if (otherHooks.length > 0) {
|
|
334
|
+
hasMixedGroup = true;
|
|
335
|
+
retained.push({ ...group, hooks: otherHooks });
|
|
357
336
|
}
|
|
358
337
|
}
|
|
359
|
-
return
|
|
338
|
+
return { retained, owned, removed, hasMixedGroup };
|
|
339
|
+
}
|
|
340
|
+
function assertRendererCanOwnTokenjuiceGroups(hooksPath, split) {
|
|
341
|
+
if (split.hasMixedGroup) {
|
|
342
|
+
throw new Error(`cannot safely migrate a mixed Tokenjuice/custom matcher group at ${hooksPath}; separate the commands into distinct groups before retrying with the codex-hooks renderer`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
function collectTokenjuiceCodexHookCommands(config) {
|
|
346
|
+
const commands = [];
|
|
347
|
+
for (const [eventName, groups] of Object.entries(config.hooks)) {
|
|
348
|
+
groups.forEach((group, groupIndex) => {
|
|
349
|
+
group.hooks.forEach((hook, hookIndex) => {
|
|
350
|
+
if (!isTokenjuiceCodexHookCommand(hook) || typeof hook.command !== "string") {
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
commands.push({
|
|
354
|
+
location: `${eventName}[${groupIndex}].hooks[${hookIndex}]`,
|
|
355
|
+
hook,
|
|
356
|
+
command: hook.command,
|
|
357
|
+
});
|
|
358
|
+
});
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
return commands;
|
|
360
362
|
}
|
|
361
363
|
function truncateHookCommand(command, maxLength = 80) {
|
|
362
364
|
const trimmed = command.trim();
|
|
@@ -365,44 +367,14 @@ function truncateHookCommand(command, maxLength = 80) {
|
|
|
365
367
|
}
|
|
366
368
|
return `${trimmed.slice(0, maxLength - 3)}...`;
|
|
367
369
|
}
|
|
368
|
-
function extractHomebrewCellarVersion(path) {
|
|
369
|
-
const normalized = path.replace(/\\/gu, "/");
|
|
370
|
-
const match = normalized.match(/\/Cellar\/tokenjuice\/([^/]+)\//u);
|
|
371
|
-
return match?.[1];
|
|
372
|
-
}
|
|
373
|
-
async function detectResolvedHomebrewVersionMismatch(commandPaths) {
|
|
374
|
-
for (const path of commandPaths) {
|
|
375
|
-
if (!path.endsWith("/tokenjuice") && !path.endsWith("\\tokenjuice") && !path.endsWith("\\tokenjuice.exe")) {
|
|
376
|
-
continue;
|
|
377
|
-
}
|
|
378
|
-
let resolvedPath;
|
|
379
|
-
try {
|
|
380
|
-
resolvedPath = await realpath(path);
|
|
381
|
-
}
|
|
382
|
-
catch {
|
|
383
|
-
continue;
|
|
384
|
-
}
|
|
385
|
-
const resolvedVersion = extractHomebrewCellarVersion(resolvedPath);
|
|
386
|
-
if (!resolvedVersion || resolvedVersion === packageJson.version) {
|
|
387
|
-
continue;
|
|
388
|
-
}
|
|
389
|
-
return {
|
|
390
|
-
launcherPath: path,
|
|
391
|
-
resolvedPath,
|
|
392
|
-
resolvedVersion,
|
|
393
|
-
};
|
|
394
|
-
}
|
|
395
|
-
return undefined;
|
|
396
|
-
}
|
|
397
370
|
function collectLowTimeoutWarnings(config) {
|
|
398
371
|
const issues = [];
|
|
399
372
|
for (const [eventName, groups] of Object.entries(config.hooks)) {
|
|
400
373
|
groups.forEach((group, groupIndex) => {
|
|
401
|
-
const tokenjuiceGroup = eventName === "PostToolUse" && isTokenjuiceCodexHook(group);
|
|
402
|
-
if (tokenjuiceGroup) {
|
|
403
|
-
return;
|
|
404
|
-
}
|
|
405
374
|
group.hooks.forEach((hook, hookIndex) => {
|
|
375
|
+
if (eventName === "PostToolUse" && isTokenjuiceCodexHookCommand(hook)) {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
406
378
|
if (typeof hook.command !== "string") {
|
|
407
379
|
return;
|
|
408
380
|
}
|
|
@@ -420,16 +392,14 @@ function collectLowTimeoutWarnings(config) {
|
|
|
420
392
|
return issues;
|
|
421
393
|
}
|
|
422
394
|
function collectTokenjuiceHookTimeoutWarnings(config, fixCommand) {
|
|
423
|
-
const
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
}
|
|
427
|
-
if (hook.timeout !== TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS) {
|
|
395
|
+
const staleCommands = collectTokenjuiceCodexHookCommands(config)
|
|
396
|
+
.filter(({ hook }) => hook.timeout !== TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS);
|
|
397
|
+
if (staleCommands.length === 1) {
|
|
428
398
|
return [
|
|
429
399
|
`configured Codex tokenjuice hook timeout is missing or stale; run ${fixCommand} to add the ${TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS}s safety cap`,
|
|
430
400
|
];
|
|
431
401
|
}
|
|
432
|
-
return
|
|
402
|
+
return staleCommands.map(({ location }) => `configured Codex tokenjuice hook ${location} timeout is missing or stale; run ${fixCommand} to add the ${TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS}s safety cap`);
|
|
433
403
|
}
|
|
434
404
|
function sanitizeHooksConfig(raw) {
|
|
435
405
|
if (!isRecord(raw) || !isRecord(raw.hooks)) {
|
|
@@ -475,7 +445,7 @@ async function loadHooksConfig(hooksPath) {
|
|
|
475
445
|
const config = sanitizeHooksConfig(parsed);
|
|
476
446
|
const backupPath = `${hooksPath}.bak`;
|
|
477
447
|
await writeFile(backupPath, rawText, "utf8");
|
|
478
|
-
return { config, backupPath };
|
|
448
|
+
return { config, backupPath, sourceText: rawText };
|
|
479
449
|
}
|
|
480
450
|
catch (error) {
|
|
481
451
|
if (error.code === "ENOENT") {
|
|
@@ -484,6 +454,122 @@ async function loadHooksConfig(hooksPath) {
|
|
|
484
454
|
throw new Error(`failed to load codex hooks from ${hooksPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
485
455
|
}
|
|
486
456
|
}
|
|
457
|
+
async function resolveCodexHooksRenderer() {
|
|
458
|
+
const pathValue = process.env.PATH;
|
|
459
|
+
if (!pathValue) {
|
|
460
|
+
return undefined;
|
|
461
|
+
}
|
|
462
|
+
const names = process.platform === "win32"
|
|
463
|
+
? ["codex-hooks.exe", "codex-hooks.cmd", "codex-hooks.bat", "codex-hooks"]
|
|
464
|
+
: ["codex-hooks"];
|
|
465
|
+
for (const segment of pathValue.split(delimiter)) {
|
|
466
|
+
if (!segment) {
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
for (const name of names) {
|
|
470
|
+
const candidate = join(segment, name);
|
|
471
|
+
if (await isExecutableFile(candidate)) {
|
|
472
|
+
return candidate;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return undefined;
|
|
477
|
+
}
|
|
478
|
+
const UNSAFE_WINDOWS_BATCH_ARGUMENT = /["&|<>()^%!\u0000-\u001F\u007F]/u;
|
|
479
|
+
function assertSafeWindowsBatchArguments(args) {
|
|
480
|
+
if (args.some((arg) => !arg || arg.trim() !== arg || UNSAFE_WINDOWS_BATCH_ARGUMENT.test(arg))) {
|
|
481
|
+
throw new Error("unsafe Windows batch renderer argument");
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
async function runCodexHooksRenderer(rendererPath, action, hooksPath, fragment, ownedSource) {
|
|
485
|
+
const nonce = `${process.pid}-${randomUUID()}`;
|
|
486
|
+
const fragmentPath = join(dirname(hooksPath), `.tokenjuice-hooks-fragment-${nonce}.json`);
|
|
487
|
+
const ownedSourcePath = join(dirname(hooksPath), `.tokenjuice-hooks-owned-${nonce}.json`);
|
|
488
|
+
const args = [
|
|
489
|
+
action,
|
|
490
|
+
"--integration-id",
|
|
491
|
+
CODEX_HOOK_INTEGRATION_ID,
|
|
492
|
+
"--target",
|
|
493
|
+
hooksPath,
|
|
494
|
+
];
|
|
495
|
+
if (action === "register" && fragment) {
|
|
496
|
+
args.push("--fragment", fragmentPath);
|
|
497
|
+
}
|
|
498
|
+
if (ownedSource && Object.keys(ownedSource.hooks).length > 0) {
|
|
499
|
+
args.push("--owned-source", ownedSourcePath);
|
|
500
|
+
}
|
|
501
|
+
const isWindowsBatch = process.platform === "win32" && /\.(?:cmd|bat)$/iu.test(rendererPath);
|
|
502
|
+
const executable = isWindowsBatch ? process.env.ComSpec?.trim() || "cmd.exe" : rendererPath;
|
|
503
|
+
const executableArgs = isWindowsBatch
|
|
504
|
+
? ["/d", "/s", "/c", "call", rendererPath, ...args]
|
|
505
|
+
: args;
|
|
506
|
+
if (isWindowsBatch) {
|
|
507
|
+
assertSafeWindowsBatchArguments([...executableArgs, fragmentPath, ownedSourcePath]);
|
|
508
|
+
}
|
|
509
|
+
await mkdir(dirname(hooksPath), { recursive: true, mode: 0o700 });
|
|
510
|
+
try {
|
|
511
|
+
if (action === "register" && fragment) {
|
|
512
|
+
await writeFile(fragmentPath, `${JSON.stringify(fragment, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
513
|
+
}
|
|
514
|
+
if (ownedSource && Object.keys(ownedSource.hooks).length > 0) {
|
|
515
|
+
await writeFile(ownedSourcePath, `${JSON.stringify(ownedSource, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
516
|
+
}
|
|
517
|
+
await new Promise((resolvePromise, rejectPromise) => {
|
|
518
|
+
execFile(executable, executableArgs, { encoding: "utf8" }, (error, _stdout, stderr) => {
|
|
519
|
+
if (!error) {
|
|
520
|
+
resolvePromise();
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
const detail = stderr.trim() || error.message;
|
|
524
|
+
rejectPromise(new Error(`codex-hooks renderer failed: ${detail}`));
|
|
525
|
+
});
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
finally {
|
|
529
|
+
await Promise.all([
|
|
530
|
+
rm(fragmentPath, { force: true }),
|
|
531
|
+
rm(ownedSourcePath, { force: true }),
|
|
532
|
+
]);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
async function assertStandaloneHooksTarget(hooksPath) {
|
|
536
|
+
try {
|
|
537
|
+
if ((await lstat(hooksPath)).isSymbolicLink()) {
|
|
538
|
+
throw new Error(`cannot directly replace externally owned hooks symlink at ${hooksPath}; install codex-hooks or update its owner`);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
catch (error) {
|
|
542
|
+
if (error.code !== "ENOENT") {
|
|
543
|
+
throw error;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
async function assertHooksSourceUnchanged(hooksPath, sourceText) {
|
|
548
|
+
try {
|
|
549
|
+
const current = await readFile(hooksPath, "utf8");
|
|
550
|
+
if (current !== sourceText) {
|
|
551
|
+
throw new Error(`codex hooks changed during update at ${hooksPath}; no replacement`);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
catch (error) {
|
|
555
|
+
if (error.code === "ENOENT" && sourceText === undefined) {
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
throw error;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
async function writeStandaloneHooksConfig(hooksPath, config, sourceText) {
|
|
562
|
+
await mkdir(dirname(hooksPath), { recursive: true });
|
|
563
|
+
const tempPath = `${hooksPath}.tmp.${process.pid}-${randomUUID()}`;
|
|
564
|
+
try {
|
|
565
|
+
await writeFile(tempPath, `${JSON.stringify(config, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
566
|
+
await assertHooksSourceUnchanged(hooksPath, sourceText);
|
|
567
|
+
await rename(tempPath, hooksPath);
|
|
568
|
+
}
|
|
569
|
+
finally {
|
|
570
|
+
await rm(tempPath, { force: true });
|
|
571
|
+
}
|
|
572
|
+
}
|
|
487
573
|
async function readHooksConfig(hooksPath) {
|
|
488
574
|
try {
|
|
489
575
|
const rawText = await readFile(hooksPath, "utf8");
|
|
@@ -539,16 +625,58 @@ function commandRequestsTokenjuiceRawBypass(command) {
|
|
|
539
625
|
const optionArgs = argv.slice(wrapIndex + 1, optionEndIndex === -1 ? undefined : optionEndIndex);
|
|
540
626
|
return optionArgs.includes("--raw") || optionArgs.includes("--full");
|
|
541
627
|
}
|
|
542
|
-
function buildCodexFeedback(inlineText, rawRefId) {
|
|
543
|
-
|
|
628
|
+
function buildCodexFeedback(inlineText, rawRefId, compaction, exitCode, maxChars = 1200, noOmit = false) {
|
|
629
|
+
const recoveryReference = rawRefId
|
|
630
|
+
? `tokenjuice cat ${rawRefId}`
|
|
631
|
+
: undefined;
|
|
632
|
+
const serialize = (compactedOutput, authoritative) => [
|
|
633
|
+
"<tokenjuice_compacted_tool_observation>",
|
|
634
|
+
JSON.stringify({
|
|
635
|
+
source: "codex-post-tool-use",
|
|
636
|
+
exitCode: exitCode ?? null,
|
|
637
|
+
authority: authoritative ? "authoritative-omission" : "non-authoritative-rewrite",
|
|
638
|
+
compactedOutput,
|
|
639
|
+
...(authoritative && recoveryReference ? { recoveryReference } : {}),
|
|
640
|
+
}, null, 2),
|
|
641
|
+
"</tokenjuice_compacted_tool_observation>",
|
|
642
|
+
].join("\n");
|
|
643
|
+
const feedback = serialize(inlineText, compaction?.authoritative === true);
|
|
644
|
+
if (countTextChars(feedback) <= maxChars) {
|
|
645
|
+
return { text: feedback, truncated: false };
|
|
646
|
+
}
|
|
647
|
+
if (noOmit) {
|
|
648
|
+
return undefined;
|
|
649
|
+
}
|
|
650
|
+
const truncationMarker = "\n... compacted observation truncated ...";
|
|
651
|
+
let low = 0;
|
|
652
|
+
let high = countTextChars(inlineText);
|
|
653
|
+
let best;
|
|
654
|
+
while (low <= high) {
|
|
655
|
+
const midpoint = Math.floor((low + high) / 2);
|
|
656
|
+
const candidate = serialize(`${sliceTextChars(inlineText, 0, midpoint)}${truncationMarker}`, true);
|
|
657
|
+
if (countTextChars(candidate) <= maxChars) {
|
|
658
|
+
best = candidate;
|
|
659
|
+
low = midpoint + 1;
|
|
660
|
+
}
|
|
661
|
+
else {
|
|
662
|
+
high = midpoint - 1;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
return best ? { text: best, truncated: true } : undefined;
|
|
544
666
|
}
|
|
545
|
-
function buildCodexReplacementOutput(inlineText, rawRefId) {
|
|
546
|
-
const feedback = buildCodexFeedback(inlineText, rawRefId);
|
|
667
|
+
function buildCodexReplacementOutput(inlineText, rawRefId, compaction, exitCode, maxChars, noOmit) {
|
|
668
|
+
const feedback = buildCodexFeedback(inlineText, rawRefId, compaction, exitCode, maxChars, noOmit);
|
|
669
|
+
if (!feedback) {
|
|
670
|
+
return undefined;
|
|
671
|
+
}
|
|
547
672
|
return {
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
673
|
+
payload: {
|
|
674
|
+
hookSpecificOutput: {
|
|
675
|
+
hookEventName: "PostToolUse",
|
|
676
|
+
additionalContext: feedback.text,
|
|
677
|
+
},
|
|
551
678
|
},
|
|
679
|
+
truncated: feedback.truncated,
|
|
552
680
|
};
|
|
553
681
|
}
|
|
554
682
|
function parseExitCodeValue(value) {
|
|
@@ -567,9 +695,18 @@ function extractCodexExitCode(payload) {
|
|
|
567
695
|
return parsed;
|
|
568
696
|
}
|
|
569
697
|
}
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
698
|
+
let response = payload.tool_response;
|
|
699
|
+
if (typeof response === "string") {
|
|
700
|
+
try {
|
|
701
|
+
response = JSON.parse(response);
|
|
702
|
+
}
|
|
703
|
+
catch {
|
|
704
|
+
response = undefined;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
if (isRecord(response)) {
|
|
708
|
+
for (const key of ["exitCode", "exit_code", "status"]) {
|
|
709
|
+
const parsed = parseExitCodeValue(response[key]);
|
|
573
710
|
if (typeof parsed === "number") {
|
|
574
711
|
return parsed;
|
|
575
712
|
}
|
|
@@ -577,52 +714,152 @@ function extractCodexExitCode(payload) {
|
|
|
577
714
|
}
|
|
578
715
|
return undefined;
|
|
579
716
|
}
|
|
717
|
+
function isJsonDocument(text) {
|
|
718
|
+
try {
|
|
719
|
+
JSON.parse(text);
|
|
720
|
+
return true;
|
|
721
|
+
}
|
|
722
|
+
catch {
|
|
723
|
+
return false;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
function hasStructuredJsonOutput(value) {
|
|
727
|
+
if (typeof value === "string") {
|
|
728
|
+
try {
|
|
729
|
+
const parsed = JSON.parse(value);
|
|
730
|
+
if (isRecord(parsed)
|
|
731
|
+
&& ["output", "text", "stdout", "stderr", "combinedText"].some((key) => key in parsed)) {
|
|
732
|
+
return hasStructuredJsonOutput(parsed);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
catch {
|
|
736
|
+
return false;
|
|
737
|
+
}
|
|
738
|
+
return false;
|
|
739
|
+
}
|
|
740
|
+
if (Array.isArray(value)) {
|
|
741
|
+
return value.some((entry) => hasStructuredJsonOutput(entry));
|
|
742
|
+
}
|
|
743
|
+
if (!isRecord(value)) {
|
|
744
|
+
return false;
|
|
745
|
+
}
|
|
746
|
+
return ["combinedText", "stdout", "output", "text"].some((key) => typeof value[key] === "string" && isJsonDocument(value[key]));
|
|
747
|
+
}
|
|
748
|
+
function getCriticalCodexEvidenceReason(command, text, exitCode) {
|
|
749
|
+
if (typeof exitCode === "number" && exitCode !== 0) {
|
|
750
|
+
return "nonzero-exit-evidence";
|
|
751
|
+
}
|
|
752
|
+
if (isJsonDocument(text)) {
|
|
753
|
+
return "machine-readable-output";
|
|
754
|
+
}
|
|
755
|
+
if (/(?:^|[/\\\s'"])(?:AGENTS|SOUL|SKILL)\.md(?:$|[/\\\s'"])/iu.test(command)) {
|
|
756
|
+
return "instruction-file-output";
|
|
757
|
+
}
|
|
758
|
+
if (/(?:^|\s)['"]?(?:\.schema|\\d[+a-z]*)['"]?(?:\s|$)/iu.test(command)
|
|
759
|
+
|| /\b(?:schema-only|show\s+create|describe|pragma)\b/iu.test(command)) {
|
|
760
|
+
return "schema-output";
|
|
761
|
+
}
|
|
762
|
+
return undefined;
|
|
763
|
+
}
|
|
580
764
|
export async function installCodexHook(hooksPath = getDefaultHooksPath(), options = {}) {
|
|
581
|
-
const { config, backupPath } = await loadHooksConfig(hooksPath);
|
|
582
765
|
const command = await buildCodexHookCommand(options);
|
|
766
|
+
const rendererPath = await resolveCodexHooksRenderer();
|
|
767
|
+
if (rendererPath) {
|
|
768
|
+
const { config } = await readHooksConfig(hooksPath);
|
|
769
|
+
const split = splitTokenjuiceCodexHooks(config.hooks.PostToolUse ?? []);
|
|
770
|
+
assertRendererCanOwnTokenjuiceGroups(hooksPath, split);
|
|
771
|
+
const ownedSource = {
|
|
772
|
+
hooks: split.owned.length > 0 ? { PostToolUse: split.owned } : {},
|
|
773
|
+
};
|
|
774
|
+
await runCodexHooksRenderer(rendererPath, "register", hooksPath, { hooks: { PostToolUse: [createTokenjuiceCodexHook(command)] } }, ownedSource);
|
|
775
|
+
const featureFlag = await inspectCodexHooksFeatureFlag(options.featureFlagConfigPath);
|
|
776
|
+
return {
|
|
777
|
+
hooksPath,
|
|
778
|
+
command,
|
|
779
|
+
featureFlag,
|
|
780
|
+
writer: "codex-hooks",
|
|
781
|
+
fragmentId: CODEX_HOOK_INTEGRATION_ID,
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
await assertStandaloneHooksTarget(hooksPath);
|
|
785
|
+
const { config, backupPath, sourceText } = await loadHooksConfig(hooksPath);
|
|
583
786
|
const postToolUse = config.hooks.PostToolUse ?? [];
|
|
584
|
-
const retained = postToolUse
|
|
787
|
+
const { retained } = splitTokenjuiceCodexHooks(postToolUse);
|
|
585
788
|
retained.push(createTokenjuiceCodexHook(command));
|
|
586
789
|
config.hooks.PostToolUse = retained;
|
|
587
|
-
await
|
|
588
|
-
const tempPath = `${hooksPath}.tmp`;
|
|
589
|
-
await writeFile(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
590
|
-
await rename(tempPath, hooksPath);
|
|
790
|
+
await writeStandaloneHooksConfig(hooksPath, config, sourceText);
|
|
591
791
|
const featureFlag = await inspectCodexHooksFeatureFlag(options.featureFlagConfigPath);
|
|
592
792
|
return {
|
|
593
793
|
hooksPath,
|
|
594
794
|
...(backupPath ? { backupPath } : {}),
|
|
595
795
|
command,
|
|
596
796
|
featureFlag,
|
|
797
|
+
writer: "standalone",
|
|
798
|
+
fragmentId: CODEX_HOOK_INTEGRATION_ID,
|
|
597
799
|
};
|
|
598
800
|
}
|
|
599
801
|
export async function uninstallCodexHook(hooksPath = getDefaultHooksPath()) {
|
|
600
|
-
const
|
|
802
|
+
const rendererPath = await resolveCodexHooksRenderer();
|
|
803
|
+
if (rendererPath) {
|
|
804
|
+
const { config } = await readHooksConfig(hooksPath);
|
|
805
|
+
const split = splitTokenjuiceCodexHooks(config.hooks.PostToolUse ?? []);
|
|
806
|
+
assertRendererCanOwnTokenjuiceGroups(hooksPath, split);
|
|
807
|
+
const ownedSource = {
|
|
808
|
+
hooks: split.owned.length > 0 ? { PostToolUse: split.owned } : {},
|
|
809
|
+
};
|
|
810
|
+
await runCodexHooksRenderer(rendererPath, "unregister", hooksPath, undefined, ownedSource);
|
|
811
|
+
return {
|
|
812
|
+
hooksPath,
|
|
813
|
+
removed: split.removed,
|
|
814
|
+
writer: "codex-hooks",
|
|
815
|
+
fragmentId: CODEX_HOOK_INTEGRATION_ID,
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
await assertStandaloneHooksTarget(hooksPath);
|
|
819
|
+
const { config, backupPath, sourceText } = await loadHooksConfig(hooksPath);
|
|
601
820
|
const postToolUse = config.hooks.PostToolUse ?? [];
|
|
602
|
-
const retained
|
|
603
|
-
const removed = postToolUse.length - retained.length;
|
|
821
|
+
const { retained, removed } = splitTokenjuiceCodexHooks(postToolUse);
|
|
604
822
|
if (retained.length > 0) {
|
|
605
823
|
config.hooks.PostToolUse = retained;
|
|
606
824
|
}
|
|
607
825
|
else {
|
|
608
826
|
delete config.hooks.PostToolUse;
|
|
609
827
|
}
|
|
610
|
-
await
|
|
611
|
-
const tempPath = `${hooksPath}.tmp`;
|
|
612
|
-
await writeFile(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
613
|
-
await rename(tempPath, hooksPath);
|
|
828
|
+
await writeStandaloneHooksConfig(hooksPath, config, sourceText);
|
|
614
829
|
return {
|
|
615
830
|
hooksPath,
|
|
616
831
|
...(backupPath ? { backupPath } : {}),
|
|
617
832
|
removed,
|
|
833
|
+
writer: "standalone",
|
|
834
|
+
fragmentId: CODEX_HOOK_INTEGRATION_ID,
|
|
618
835
|
};
|
|
619
836
|
}
|
|
620
837
|
export async function doctorCodexHook(hooksPath = getDefaultHooksPath(), options = {}) {
|
|
838
|
+
const noOmit = options.noOmit === true;
|
|
621
839
|
const expectedCommand = await buildCodexHookCommand(options);
|
|
622
|
-
const
|
|
840
|
+
const expectedNodePath = options.nodePath ?? process.execPath;
|
|
841
|
+
const installFixCommand = getCodexFixCommand(options.local, noOmit);
|
|
623
842
|
let fixCommand = installFixCommand;
|
|
624
843
|
const { config, exists } = await readHooksConfig(hooksPath);
|
|
625
|
-
const
|
|
844
|
+
const locatedCommands = collectTokenjuiceCodexHookCommands(config);
|
|
845
|
+
const detectedCommands = await Promise.all(locatedCommands.map(async ({ location, command }) => ({
|
|
846
|
+
location,
|
|
847
|
+
command,
|
|
848
|
+
...(await inspectTokenjuiceHookCommand({
|
|
849
|
+
command,
|
|
850
|
+
expectedNodePath,
|
|
851
|
+
expectedPackageVersion: packageJson.version,
|
|
852
|
+
})),
|
|
853
|
+
})));
|
|
854
|
+
const detectedCommand = detectedCommands[0]?.command;
|
|
855
|
+
const duplicateHookCount = Math.max(0, detectedCommands.length - 1);
|
|
856
|
+
const checkedPaths = [...new Set(detectedCommands.flatMap((entry) => entry.checkedPaths))];
|
|
857
|
+
const missingPaths = [...new Set(detectedCommands.flatMap((entry) => entry.missingPaths))];
|
|
858
|
+
const nonExecutablePaths = [...new Set(detectedCommands.flatMap((entry) => entry.nonExecutablePaths))];
|
|
859
|
+
const runtimeMismatches = detectedCommands.flatMap((entry) => entry.runtimeMismatch ? [{ location: entry.location, ...entry.runtimeMismatch }] : []);
|
|
860
|
+
const packageVersionMismatches = detectedCommands.flatMap((entry) => entry.packageVersionMismatch
|
|
861
|
+
? [{ location: entry.location, ...entry.packageVersionMismatch }]
|
|
862
|
+
: []);
|
|
626
863
|
const featureFlag = await inspectCodexHooksFeatureFlag(options.featureFlagConfigPath);
|
|
627
864
|
const runtimeConfig = await inspectCodexRuntimeConfig(options.featureFlagConfigPath);
|
|
628
865
|
if (!exists) {
|
|
@@ -632,8 +869,13 @@ export async function doctorCodexHook(hooksPath = getDefaultHooksPath(), options
|
|
|
632
869
|
issues: [],
|
|
633
870
|
fixCommand,
|
|
634
871
|
expectedCommand,
|
|
872
|
+
detectedCommands,
|
|
873
|
+
duplicateHookCount,
|
|
635
874
|
checkedPaths: [],
|
|
636
875
|
missingPaths: [],
|
|
876
|
+
nonExecutablePaths: [],
|
|
877
|
+
runtimeMismatches: [],
|
|
878
|
+
packageVersionMismatches: [],
|
|
637
879
|
featureFlag,
|
|
638
880
|
runtimeConfig,
|
|
639
881
|
};
|
|
@@ -645,22 +887,24 @@ export async function doctorCodexHook(hooksPath = getDefaultHooksPath(), options
|
|
|
645
887
|
issues: [],
|
|
646
888
|
fixCommand,
|
|
647
889
|
expectedCommand,
|
|
890
|
+
detectedCommands,
|
|
891
|
+
duplicateHookCount,
|
|
648
892
|
checkedPaths: [],
|
|
649
893
|
missingPaths: [],
|
|
894
|
+
nonExecutablePaths: [],
|
|
895
|
+
runtimeMismatches: [],
|
|
896
|
+
packageVersionMismatches: [],
|
|
650
897
|
featureFlag,
|
|
651
898
|
runtimeConfig,
|
|
652
899
|
};
|
|
653
900
|
}
|
|
654
|
-
const checkedPaths = extractHookCommandPaths(detectedCommand);
|
|
655
|
-
const missingPaths = [];
|
|
656
|
-
for (const path of checkedPaths) {
|
|
657
|
-
if (!(await isExecutableFile(path)) && !(path.endsWith(".js") && await pathExists(path))) {
|
|
658
|
-
missingPaths.push(path);
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
901
|
const issues = [];
|
|
662
|
-
|
|
663
|
-
|
|
902
|
+
const commandMismatch = detectedCommands.some((entry) => entry.command !== expectedCommand);
|
|
903
|
+
if (duplicateHookCount > 0) {
|
|
904
|
+
issues.push(`configured Codex hooks contain ${detectedCommands.length} tokenjuice commands; expected exactly one managed hook`);
|
|
905
|
+
}
|
|
906
|
+
if (commandMismatch) {
|
|
907
|
+
if (detectedCommands.some((entry) => entry.command.includes("/Cellar/"))) {
|
|
664
908
|
issues.push("configured Codex hook is pinned to a versioned Homebrew Cellar path");
|
|
665
909
|
}
|
|
666
910
|
else {
|
|
@@ -670,14 +914,21 @@ export async function doctorCodexHook(hooksPath = getDefaultHooksPath(), options
|
|
|
670
914
|
if (missingPaths.length > 0) {
|
|
671
915
|
issues.push(`configured Codex hook points at missing path${missingPaths.length === 1 ? "" : "s"}`);
|
|
672
916
|
}
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
917
|
+
if (nonExecutablePaths.length > 0) {
|
|
918
|
+
issues.push(`configured Codex hook points at non-executable path${nonExecutablePaths.length === 1 ? "" : "s"}`);
|
|
919
|
+
}
|
|
920
|
+
for (const mismatch of runtimeMismatches) {
|
|
921
|
+
issues.push(`configured Codex hook ${mismatch.location} uses Node runtime ${mismatch.configuredPath}, but this tokenjuice uses ${mismatch.expectedPath}`);
|
|
922
|
+
}
|
|
923
|
+
for (const mismatch of packageVersionMismatches) {
|
|
924
|
+
issues.push(`configured Codex hook launcher resolves to Homebrew tokenjuice ${mismatch.resolvedVersion}, but this tokenjuice is ${mismatch.expectedVersion}`);
|
|
925
|
+
fixCommand = commandMismatch
|
|
926
|
+
? `brew upgrade tokenjuice && ${installFixCommand}`
|
|
927
|
+
: "brew upgrade tokenjuice";
|
|
677
928
|
}
|
|
678
929
|
if (options.local && await detectStaleLocalBuild(checkedPaths)) {
|
|
679
930
|
issues.push("local Codex hook target is older than the source tree");
|
|
680
|
-
fixCommand =
|
|
931
|
+
fixCommand = `pnpm build && ${getCodexFixCommand(true, noOmit)}`;
|
|
681
932
|
}
|
|
682
933
|
if (!featureFlag.enabled) {
|
|
683
934
|
issues.push("Codex feature flag `hooks` is disabled — the configured hook will not fire");
|
|
@@ -686,13 +937,22 @@ export async function doctorCodexHook(hooksPath = getDefaultHooksPath(), options
|
|
|
686
937
|
issues.push(...collectLowTimeoutWarnings(config));
|
|
687
938
|
return {
|
|
688
939
|
hooksPath,
|
|
689
|
-
status: missingPaths.length > 0
|
|
940
|
+
status: missingPaths.length > 0 || nonExecutablePaths.length > 0
|
|
941
|
+
? "broken"
|
|
942
|
+
: issues.length > 0
|
|
943
|
+
? "warn"
|
|
944
|
+
: "ok",
|
|
690
945
|
issues,
|
|
691
946
|
fixCommand,
|
|
692
947
|
expectedCommand,
|
|
693
948
|
detectedCommand,
|
|
949
|
+
detectedCommands,
|
|
950
|
+
duplicateHookCount,
|
|
694
951
|
checkedPaths,
|
|
695
952
|
missingPaths,
|
|
953
|
+
nonExecutablePaths,
|
|
954
|
+
runtimeMismatches,
|
|
955
|
+
packageVersionMismatches,
|
|
696
956
|
featureFlag,
|
|
697
957
|
runtimeConfig,
|
|
698
958
|
};
|
|
@@ -710,100 +970,34 @@ function shouldStoreFromEnv() {
|
|
|
710
970
|
return value === "1" || value === "true" || value === "TRUE" || value === "yes" || value === "YES";
|
|
711
971
|
}
|
|
712
972
|
async function writeHookDebug(record) {
|
|
713
|
-
|
|
714
|
-
const debugPath = join(codexHome, CODEX_HOOK_LAST_LOG);
|
|
715
|
-
const historyPath = join(codexHome, CODEX_HOOK_HISTORY_LOG);
|
|
716
|
-
const enrichedRecord = {
|
|
717
|
-
timestamp: new Date().toISOString(),
|
|
718
|
-
tokenjuiceVersion: packageJson.version,
|
|
719
|
-
hookCommandPath: process.argv[1],
|
|
720
|
-
...record,
|
|
721
|
-
};
|
|
722
|
-
await mkdir(dirname(debugPath), { recursive: true });
|
|
723
|
-
await writeFile(debugPath, `${JSON.stringify(enrichedRecord, null, 2)}\n`, "utf8");
|
|
724
|
-
await writeHookHistoryEntry(historyPath, JSON.stringify(enrichedRecord));
|
|
725
|
-
}
|
|
726
|
-
function sanitizeHookHistoryLines(text) {
|
|
727
|
-
return text
|
|
728
|
-
.split("\n")
|
|
729
|
-
.map((line) => line.trim())
|
|
730
|
-
.filter(Boolean)
|
|
731
|
-
.filter((line) => {
|
|
732
|
-
try {
|
|
733
|
-
JSON.parse(line);
|
|
734
|
-
return true;
|
|
735
|
-
}
|
|
736
|
-
catch {
|
|
737
|
-
return false;
|
|
738
|
-
}
|
|
739
|
-
});
|
|
740
|
-
}
|
|
741
|
-
function wait(ms) {
|
|
742
|
-
return new Promise((resolvePromise) => {
|
|
743
|
-
setTimeout(resolvePromise, ms);
|
|
744
|
-
});
|
|
745
|
-
}
|
|
746
|
-
async function acquireHistoryLock(lockPath) {
|
|
747
|
-
for (let attempt = 0; attempt <= CODEX_HOOK_HISTORY_LOCK_RETRIES; attempt += 1) {
|
|
748
|
-
try {
|
|
749
|
-
await mkdir(lockPath);
|
|
750
|
-
return true;
|
|
751
|
-
}
|
|
752
|
-
catch (error) {
|
|
753
|
-
const code = error.code;
|
|
754
|
-
if (code !== "EEXIST") {
|
|
755
|
-
throw error;
|
|
756
|
-
}
|
|
757
|
-
try {
|
|
758
|
-
const details = await stat(lockPath);
|
|
759
|
-
if (Date.now() - details.mtimeMs > CODEX_HOOK_HISTORY_LOCK_STALE_MS) {
|
|
760
|
-
await rm(lockPath, { recursive: true, force: true });
|
|
761
|
-
continue;
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
catch (statError) {
|
|
765
|
-
const statCode = statError.code;
|
|
766
|
-
if (statCode !== "ENOENT") {
|
|
767
|
-
throw statError;
|
|
768
|
-
}
|
|
769
|
-
continue;
|
|
770
|
-
}
|
|
771
|
-
if (attempt < CODEX_HOOK_HISTORY_LOCK_RETRIES) {
|
|
772
|
-
await wait(CODEX_HOOK_HISTORY_LOCK_RETRY_MS);
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
}
|
|
776
|
-
return false;
|
|
777
|
-
}
|
|
778
|
-
async function writeHookHistoryEntry(historyPath, line) {
|
|
779
|
-
const lockPath = `${historyPath}.lock`;
|
|
780
|
-
const tempPath = `${historyPath}.${process.pid}.tmp`;
|
|
781
|
-
const hasLock = await acquireHistoryLock(lockPath);
|
|
782
|
-
if (!hasLock) {
|
|
783
|
-
await appendFile(historyPath, `${line}\n`, "utf8");
|
|
973
|
+
if (!shouldRecordStats()) {
|
|
784
974
|
return;
|
|
785
975
|
}
|
|
786
976
|
try {
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
977
|
+
const codexHome = getCodexHome();
|
|
978
|
+
const debugPath = join(codexHome, CODEX_HOOK_LAST_LOG);
|
|
979
|
+
const enrichedRecord = {
|
|
980
|
+
eventId: randomUUID(),
|
|
981
|
+
timestamp: new Date().toISOString(),
|
|
982
|
+
tokenjuiceVersion: packageJson.version,
|
|
983
|
+
hookCommandPath: process.argv[1],
|
|
984
|
+
...record,
|
|
985
|
+
};
|
|
986
|
+
await mkdir(dirname(debugPath), { recursive: true });
|
|
987
|
+
await writeFile(debugPath, `${JSON.stringify(enrichedRecord, null, 2)}\n`, "utf8");
|
|
988
|
+
const historyRecord = { ...enrichedRecord };
|
|
989
|
+
if (typeof historyRecord.command === "string") {
|
|
990
|
+
const command = historyRecord.command;
|
|
991
|
+
delete historyRecord.command;
|
|
992
|
+
const commandFamily = getTelemetryCommandFamily({ command });
|
|
993
|
+
if (commandFamily) {
|
|
994
|
+
historyRecord.commandFamily = commandFamily;
|
|
795
995
|
}
|
|
796
996
|
}
|
|
797
|
-
|
|
798
|
-
if (historyLines.length > CODEX_HOOK_HISTORY_LIMIT) {
|
|
799
|
-
historyLines = historyLines.slice(-CODEX_HOOK_HISTORY_LIMIT);
|
|
800
|
-
}
|
|
801
|
-
await writeFile(tempPath, `${historyLines.join("\n")}\n`, "utf8");
|
|
802
|
-
await rename(tempPath, historyPath);
|
|
997
|
+
await appendBoundedJsonl(join(codexHome, CODEX_HOOK_HISTORY_DIRECTORY), CODEX_HOOK_HISTORY_PREFIX, enrichedRecord.eventId, historyRecord);
|
|
803
998
|
}
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
await rm(lockPath, { recursive: true, force: true }).catch(() => { });
|
|
999
|
+
catch {
|
|
1000
|
+
// A diagnostic side effect must never turn an otherwise optional hook into a failed tool call.
|
|
807
1001
|
}
|
|
808
1002
|
}
|
|
809
1003
|
function buildImmediateSkipStats(text) {
|
|
@@ -816,23 +1010,37 @@ function buildImmediateSkipStats(text) {
|
|
|
816
1010
|
};
|
|
817
1011
|
}
|
|
818
1012
|
async function recordImmediateHookStats(input, rawText, storeRaw) {
|
|
819
|
-
|
|
1013
|
+
const recordStats = shouldRecordStats();
|
|
1014
|
+
if (!storeRaw && !recordStats) {
|
|
820
1015
|
return;
|
|
821
1016
|
}
|
|
822
1017
|
const stats = buildImmediateSkipStats(rawText);
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
1018
|
+
try {
|
|
1019
|
+
const classification = await classifyOnly(input);
|
|
1020
|
+
const artifact = {
|
|
1021
|
+
input,
|
|
1022
|
+
rawText,
|
|
1023
|
+
classification,
|
|
1024
|
+
stats: {
|
|
1025
|
+
rawChars: stats.rawChars,
|
|
1026
|
+
reducedChars: stats.reducedChars,
|
|
1027
|
+
ratio: stats.ratio,
|
|
1028
|
+
},
|
|
1029
|
+
};
|
|
1030
|
+
if (storeRaw) {
|
|
1031
|
+
await storeArtifact({ ...artifact, recordStats });
|
|
1032
|
+
}
|
|
1033
|
+
else {
|
|
1034
|
+
await tryStoreArtifactMetadata(artifact);
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
catch {
|
|
1038
|
+
// Optional retention and telemetry must not fail the host tool call.
|
|
1039
|
+
}
|
|
834
1040
|
}
|
|
835
|
-
export async function runCodexPostToolUseHook(rawText) {
|
|
1041
|
+
export async function runCodexPostToolUseHook(rawText, options = {}) {
|
|
1042
|
+
const hookStartedAt = Date.now();
|
|
1043
|
+
validateCodexOmissionPolicy(options);
|
|
836
1044
|
let payload;
|
|
837
1045
|
try {
|
|
838
1046
|
payload = JSON.parse(rawText);
|
|
@@ -841,27 +1049,55 @@ export async function runCodexPostToolUseHook(rawText) {
|
|
|
841
1049
|
return 0;
|
|
842
1050
|
}
|
|
843
1051
|
const command = payload.tool_input?.command;
|
|
1052
|
+
const noOmit = !options.allowOmit && (options.noOmit || readNoOmissionFromEnv());
|
|
844
1053
|
const debug = {
|
|
845
1054
|
hookEvent: payload.hook_event_name,
|
|
846
1055
|
toolName: payload.tool_name,
|
|
847
1056
|
command,
|
|
1057
|
+
noOmit,
|
|
848
1058
|
rewrote: false,
|
|
1059
|
+
...(typeof payload.session_id === "string" ? { threadId: payload.session_id } : {}),
|
|
1060
|
+
...(typeof payload.thread_id === "string" ? { threadId: payload.thread_id } : {}),
|
|
1061
|
+
...(typeof payload.turn_id === "string" ? { turnId: payload.turn_id } : {}),
|
|
1062
|
+
...(typeof payload.tool_call_id === "string" ? { callId: payload.tool_call_id } : {}),
|
|
1063
|
+
...(typeof payload.tool_use_id === "string" ? { callId: payload.tool_use_id } : {}),
|
|
1064
|
+
};
|
|
1065
|
+
const writeDebug = async (record) => {
|
|
1066
|
+
await writeHookDebug({
|
|
1067
|
+
...record,
|
|
1068
|
+
hookLatencyMs: Date.now() - hookStartedAt,
|
|
1069
|
+
});
|
|
849
1070
|
};
|
|
850
1071
|
if (payload.hook_event_name !== "PostToolUse") {
|
|
851
|
-
await
|
|
1072
|
+
await writeDebug({ ...debug, skipped: "non-post-tool-use" });
|
|
852
1073
|
return 0;
|
|
853
1074
|
}
|
|
854
1075
|
if (payload.tool_name !== "Bash") {
|
|
855
|
-
await
|
|
1076
|
+
await writeDebug({ ...debug, skipped: "non-bash" });
|
|
856
1077
|
return 0;
|
|
857
1078
|
}
|
|
858
1079
|
if (typeof command !== "string" || !command.trim()) {
|
|
859
|
-
await
|
|
1080
|
+
await writeDebug({ ...debug, skipped: "missing-command" });
|
|
860
1081
|
return 0;
|
|
861
1082
|
}
|
|
862
1083
|
const combinedText = stringifyToolResponse(payload.tool_response);
|
|
863
1084
|
if (!combinedText.trim()) {
|
|
864
|
-
await
|
|
1085
|
+
await writeDebug({ ...debug, skipped: "empty-tool-response" });
|
|
1086
|
+
return 0;
|
|
1087
|
+
}
|
|
1088
|
+
const rawBytes = Buffer.byteLength(combinedText, "utf8");
|
|
1089
|
+
if (rawBytes > CODEX_HOOK_MAX_COMPACTION_BYTES) {
|
|
1090
|
+
const plainText = stripAnsi(combinedText);
|
|
1091
|
+
const rawChars = countTextChars(plainText);
|
|
1092
|
+
await writeDebug({
|
|
1093
|
+
...debug,
|
|
1094
|
+
rawChars,
|
|
1095
|
+
rawBytes,
|
|
1096
|
+
reducedChars: rawChars,
|
|
1097
|
+
savedChars: 0,
|
|
1098
|
+
ratio: 1,
|
|
1099
|
+
skipped: "response-too-large",
|
|
1100
|
+
});
|
|
865
1101
|
return 0;
|
|
866
1102
|
}
|
|
867
1103
|
const exitCode = extractCodexExitCode(payload);
|
|
@@ -876,10 +1112,24 @@ export async function runCodexPostToolUseHook(rawText) {
|
|
|
876
1112
|
},
|
|
877
1113
|
};
|
|
878
1114
|
const storeRaw = shouldStoreFromEnv();
|
|
1115
|
+
const criticalEvidenceReason = hasStructuredJsonOutput(payload.tool_response)
|
|
1116
|
+
? "machine-readable-output"
|
|
1117
|
+
: getCriticalCodexEvidenceReason(command, combinedText, exitCode);
|
|
1118
|
+
if (criticalEvidenceReason) {
|
|
1119
|
+
await recordImmediateHookStats(executionInput, combinedText, storeRaw);
|
|
1120
|
+
await writeDebug({
|
|
1121
|
+
...debug,
|
|
1122
|
+
...buildImmediateSkipStats(combinedText),
|
|
1123
|
+
exitCode,
|
|
1124
|
+
deliveryMode: "original-only",
|
|
1125
|
+
skipped: criticalEvidenceReason,
|
|
1126
|
+
});
|
|
1127
|
+
return 0;
|
|
1128
|
+
}
|
|
879
1129
|
if (commandRequestsTokenjuiceRawBypass(command)) {
|
|
880
1130
|
await recordImmediateHookStats(executionInput, combinedText, storeRaw);
|
|
881
1131
|
const stats = buildImmediateSkipStats(combinedText);
|
|
882
|
-
await
|
|
1132
|
+
await writeDebug({
|
|
883
1133
|
...debug,
|
|
884
1134
|
...stats,
|
|
885
1135
|
skipped: "explicit-raw-bypass",
|
|
@@ -890,7 +1140,7 @@ export async function runCodexPostToolUseHook(rawText) {
|
|
|
890
1140
|
if (inspectionSkipReason) {
|
|
891
1141
|
await recordImmediateHookStats(executionInput, combinedText, storeRaw);
|
|
892
1142
|
const stats = buildImmediateSkipStats(combinedText);
|
|
893
|
-
await
|
|
1143
|
+
await writeDebug({
|
|
894
1144
|
...debug,
|
|
895
1145
|
...stats,
|
|
896
1146
|
skipped: inspectionSkipReason,
|
|
@@ -905,8 +1155,11 @@ export async function runCodexPostToolUseHook(rawText) {
|
|
|
905
1155
|
visibleText: combinedText,
|
|
906
1156
|
...(typeof payload.cwd === "string" && payload.cwd.trim() ? { cwd: payload.cwd } : {}),
|
|
907
1157
|
...(typeof exitCode === "number" ? { exitCode } : {}),
|
|
1158
|
+
...(options.allowOmit ? { allowOmit: true } : {}),
|
|
908
1159
|
...(typeof maxInlineChars === "number" ? { maxInlineChars } : {}),
|
|
1160
|
+
...(noOmit ? { noOmit: true } : {}),
|
|
909
1161
|
storeRaw,
|
|
1162
|
+
recordStats: shouldRecordStats(),
|
|
910
1163
|
metadata: {
|
|
911
1164
|
source: "codex-post-tool-use",
|
|
912
1165
|
},
|
|
@@ -925,18 +1178,31 @@ export async function runCodexPostToolUseHook(rawText) {
|
|
|
925
1178
|
debug.savedChars = savedChars;
|
|
926
1179
|
debug.ratio = result.stats.ratio;
|
|
927
1180
|
debug.matchedReducer = result.classification.matchedReducer;
|
|
1181
|
+
debug.compaction = result.compaction;
|
|
928
1182
|
}
|
|
929
1183
|
if (outcome.action === "keep") {
|
|
930
|
-
await
|
|
1184
|
+
await writeDebug({ ...debug, deliveryMode: "original-only", skipped: outcome.reason });
|
|
1185
|
+
return 0;
|
|
1186
|
+
}
|
|
1187
|
+
const replacement = buildCodexReplacementOutput(outcome.result.inlineText, outcome.result.rawRef?.id, outcome.result.compaction, exitCode, maxInlineChars, noOmit);
|
|
1188
|
+
if (!replacement) {
|
|
1189
|
+
await writeDebug({ ...debug, deliveryMode: "original-only", skipped: "observation-inline-limit" });
|
|
931
1190
|
return 0;
|
|
932
1191
|
}
|
|
933
|
-
process.stdout.write(`${JSON.stringify(
|
|
934
|
-
await
|
|
1192
|
+
process.stdout.write(`${JSON.stringify(replacement.payload)}\n`);
|
|
1193
|
+
await writeDebug({
|
|
1194
|
+
...debug,
|
|
1195
|
+
rewrote: true,
|
|
1196
|
+
deliveryMode: "original-plus-additional-context",
|
|
1197
|
+
measurement: "pre-delivery-summary-characters",
|
|
1198
|
+
feedbackTruncated: replacement.truncated,
|
|
1199
|
+
});
|
|
935
1200
|
return 0;
|
|
936
1201
|
}
|
|
937
1202
|
catch (error) {
|
|
938
|
-
await
|
|
1203
|
+
await writeDebug({
|
|
939
1204
|
...debug,
|
|
1205
|
+
deliveryMode: "original-only",
|
|
940
1206
|
skipped: "hook-error",
|
|
941
1207
|
error: error instanceof Error ? error.message : String(error),
|
|
942
1208
|
});
|