@openclaw/tokenjuice 2026.9.5 → 2026.9.7
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/icon.png +0 -0
- package/dist/index.js +1 -1
- package/node_modules/tokenjuice/README.md +4 -0
- package/node_modules/tokenjuice/dist/cli/main.d.ts +3 -0
- package/node_modules/tokenjuice/dist/cli/main.js +58 -10
- package/node_modules/tokenjuice/dist/core/analysis.js +3 -3
- package/node_modules/tokenjuice/dist/core/artifacts.d.ts +5 -1
- package/node_modules/tokenjuice/dist/core/artifacts.js +93 -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/integrations/compact-bash-result.d.ts +1 -0
- package/node_modules/tokenjuice/dist/core/integrations/compact-bash-result.js +2 -1
- package/node_modules/tokenjuice/dist/core/reduce.js +5 -0
- package/node_modules/tokenjuice/dist/core/wrap.js +1 -1
- package/node_modules/tokenjuice/dist/hosts/claude-code/index.js +12 -61
- package/node_modules/tokenjuice/dist/hosts/codebuddy/index.js +12 -61
- package/node_modules/tokenjuice/dist/hosts/codex/index.d.ts +6 -0
- package/node_modules/tokenjuice/dist/hosts/codex/index.js +365 -147
- package/node_modules/tokenjuice/dist/hosts/droid/index.js +21 -29
- package/node_modules/tokenjuice/dist/hosts/opencode/extension/runtime.js +1489 -1193
- package/node_modules/tokenjuice/dist/hosts/pi/extension/runtime.js +1471 -1175
- package/node_modules/tokenjuice/dist/hosts/shared/settings-file.d.ts +10 -0
- package/node_modules/tokenjuice/dist/hosts/shared/settings-file.js +165 -0
- package/node_modules/tokenjuice/dist/index.d.ts +1 -1
- package/node_modules/tokenjuice/dist/index.js +1 -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 +5 -5
|
@@ -1,29 +1,30 @@
|
|
|
1
|
-
import {
|
|
2
|
-
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";
|
|
3
5
|
import { homedir } from "node:os";
|
|
4
6
|
import packageJson from "../../../package.json" with { type: "json" };
|
|
5
7
|
import { stripLeadingCdPrefix } from "../../core/command.js";
|
|
6
|
-
import { tryStoreArtifactMetadata } from "../../core/artifacts.js";
|
|
8
|
+
import { getTelemetryCommandFamily, shouldRecordStats, storeArtifact, tryStoreArtifactMetadata } from "../../core/artifacts.js";
|
|
9
|
+
import { appendBoundedJsonl } from "../../core/bounded-jsonl.js";
|
|
7
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
13
|
import { countTextChars, sliceTextChars, stripAnsi } from "../../core/text.js";
|
|
11
14
|
import { isNodeExecutablePath, parseShellWords } from "../shared/hook-command.js";
|
|
12
|
-
import { buildTokenjuiceHookCommand } from "../shared/host-command.js";
|
|
15
|
+
import { buildTokenjuiceHookCommand, isExecutableFile } from "../shared/host-command.js";
|
|
13
16
|
import { inspectTokenjuiceHookCommand } from "../shared/hook-command-doctor.js";
|
|
14
17
|
const GENERIC_FALLBACK_MIN_SAVED_CHARS = 120;
|
|
15
18
|
const GENERIC_FALLBACK_MAX_RATIO = 0.75;
|
|
16
19
|
const HOOK_REWRITE_MIN_SAVED_CHARS = 8;
|
|
17
20
|
const CODEX_HOOK_MAX_COMPACTION_BYTES = 1 * 1024 * 1024;
|
|
18
21
|
const CODEX_HOOK_LAST_LOG = "tokenjuice-hook.last.json";
|
|
19
|
-
const
|
|
20
|
-
const
|
|
21
|
-
const CODEX_HOOK_HISTORY_LOCK_STALE_MS = 30_000;
|
|
22
|
-
const CODEX_HOOK_HISTORY_LOCK_RETRY_MS = 25;
|
|
23
|
-
const CODEX_HOOK_HISTORY_LOCK_RETRIES = 8;
|
|
22
|
+
const CODEX_HOOK_HISTORY_DIRECTORY = "tokenjuice-hook.history-v1";
|
|
23
|
+
const CODEX_HOOK_HISTORY_PREFIX = "events";
|
|
24
24
|
const LOW_NON_TOKENJUICE_TIMEOUT_SECONDS = 2;
|
|
25
25
|
const RECOMMENDED_NON_TOKENJUICE_TIMEOUT_SECONDS = 6;
|
|
26
26
|
const TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS = 30;
|
|
27
|
+
const CODEX_HOOK_INTEGRATION_ID = "tokenjuice.post-tool-use";
|
|
27
28
|
function validateCodexOmissionPolicy(options) {
|
|
28
29
|
if (options.noOmit && options.allowOmit) {
|
|
29
30
|
throw new Error("Codex noOmit and allowOmit policies cannot be enabled together");
|
|
@@ -258,6 +259,16 @@ function stringifyToolResponse(value) {
|
|
|
258
259
|
return "";
|
|
259
260
|
}
|
|
260
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
|
+
}
|
|
261
272
|
return value;
|
|
262
273
|
}
|
|
263
274
|
if (Array.isArray(value)) {
|
|
@@ -267,11 +278,20 @@ function stringifyToolResponse(value) {
|
|
|
267
278
|
.join("\n");
|
|
268
279
|
}
|
|
269
280
|
if (isRecord(value)) {
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
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;
|
|
275
295
|
}
|
|
276
296
|
return JSON.stringify(value);
|
|
277
297
|
}
|
|
@@ -296,8 +316,31 @@ function isTokenjuiceCodexHookCommand(hook) {
|
|
|
296
316
|
|| command.includes("codex-post-tool-use")
|
|
297
317
|
|| command.includes("post_tool_use_tokenjuice.py");
|
|
298
318
|
}
|
|
299
|
-
function
|
|
300
|
-
|
|
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);
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
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 });
|
|
336
|
+
}
|
|
337
|
+
}
|
|
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
|
+
}
|
|
301
344
|
}
|
|
302
345
|
function collectTokenjuiceCodexHookCommands(config) {
|
|
303
346
|
const commands = [];
|
|
@@ -328,11 +371,10 @@ function collectLowTimeoutWarnings(config) {
|
|
|
328
371
|
const issues = [];
|
|
329
372
|
for (const [eventName, groups] of Object.entries(config.hooks)) {
|
|
330
373
|
groups.forEach((group, groupIndex) => {
|
|
331
|
-
const tokenjuiceGroup = eventName === "PostToolUse" && isTokenjuiceCodexHook(group);
|
|
332
|
-
if (tokenjuiceGroup) {
|
|
333
|
-
return;
|
|
334
|
-
}
|
|
335
374
|
group.hooks.forEach((hook, hookIndex) => {
|
|
375
|
+
if (eventName === "PostToolUse" && isTokenjuiceCodexHookCommand(hook)) {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
336
378
|
if (typeof hook.command !== "string") {
|
|
337
379
|
return;
|
|
338
380
|
}
|
|
@@ -403,7 +445,7 @@ async function loadHooksConfig(hooksPath) {
|
|
|
403
445
|
const config = sanitizeHooksConfig(parsed);
|
|
404
446
|
const backupPath = `${hooksPath}.bak`;
|
|
405
447
|
await writeFile(backupPath, rawText, "utf8");
|
|
406
|
-
return { config, backupPath };
|
|
448
|
+
return { config, backupPath, sourceText: rawText };
|
|
407
449
|
}
|
|
408
450
|
catch (error) {
|
|
409
451
|
if (error.code === "ENOENT") {
|
|
@@ -412,6 +454,122 @@ async function loadHooksConfig(hooksPath) {
|
|
|
412
454
|
throw new Error(`failed to load codex hooks from ${hooksPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
413
455
|
}
|
|
414
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
|
+
}
|
|
415
573
|
async function readHooksConfig(hooksPath) {
|
|
416
574
|
try {
|
|
417
575
|
const rawText = await readFile(hooksPath, "utf8");
|
|
@@ -470,7 +628,7 @@ function commandRequestsTokenjuiceRawBypass(command) {
|
|
|
470
628
|
function buildCodexFeedback(inlineText, rawRefId, compaction, exitCode, maxChars = 1200, noOmit = false) {
|
|
471
629
|
const recoveryReference = rawRefId
|
|
472
630
|
? `tokenjuice cat ${rawRefId}`
|
|
473
|
-
:
|
|
631
|
+
: undefined;
|
|
474
632
|
const serialize = (compactedOutput, authoritative) => [
|
|
475
633
|
"<tokenjuice_compacted_tool_observation>",
|
|
476
634
|
JSON.stringify({
|
|
@@ -478,7 +636,7 @@ function buildCodexFeedback(inlineText, rawRefId, compaction, exitCode, maxChars
|
|
|
478
636
|
exitCode: exitCode ?? null,
|
|
479
637
|
authority: authoritative ? "authoritative-omission" : "non-authoritative-rewrite",
|
|
480
638
|
compactedOutput,
|
|
481
|
-
...(authoritative ? { recoveryReference } : {}),
|
|
639
|
+
...(authoritative && recoveryReference ? { recoveryReference } : {}),
|
|
482
640
|
}, null, 2),
|
|
483
641
|
"</tokenjuice_compacted_tool_observation>",
|
|
484
642
|
].join("\n");
|
|
@@ -537,9 +695,18 @@ function extractCodexExitCode(payload) {
|
|
|
537
695
|
return parsed;
|
|
538
696
|
}
|
|
539
697
|
}
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
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]);
|
|
543
710
|
if (typeof parsed === "number") {
|
|
544
711
|
return parsed;
|
|
545
712
|
}
|
|
@@ -547,44 +714,124 @@ function extractCodexExitCode(payload) {
|
|
|
547
714
|
}
|
|
548
715
|
return undefined;
|
|
549
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
|
+
}
|
|
550
764
|
export async function installCodexHook(hooksPath = getDefaultHooksPath(), options = {}) {
|
|
551
|
-
const { config, backupPath } = await loadHooksConfig(hooksPath);
|
|
552
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);
|
|
553
786
|
const postToolUse = config.hooks.PostToolUse ?? [];
|
|
554
|
-
const retained = postToolUse
|
|
787
|
+
const { retained } = splitTokenjuiceCodexHooks(postToolUse);
|
|
555
788
|
retained.push(createTokenjuiceCodexHook(command));
|
|
556
789
|
config.hooks.PostToolUse = retained;
|
|
557
|
-
await
|
|
558
|
-
const tempPath = `${hooksPath}.tmp`;
|
|
559
|
-
await writeFile(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
560
|
-
await rename(tempPath, hooksPath);
|
|
790
|
+
await writeStandaloneHooksConfig(hooksPath, config, sourceText);
|
|
561
791
|
const featureFlag = await inspectCodexHooksFeatureFlag(options.featureFlagConfigPath);
|
|
562
792
|
return {
|
|
563
793
|
hooksPath,
|
|
564
794
|
...(backupPath ? { backupPath } : {}),
|
|
565
795
|
command,
|
|
566
796
|
featureFlag,
|
|
797
|
+
writer: "standalone",
|
|
798
|
+
fragmentId: CODEX_HOOK_INTEGRATION_ID,
|
|
567
799
|
};
|
|
568
800
|
}
|
|
569
801
|
export async function uninstallCodexHook(hooksPath = getDefaultHooksPath()) {
|
|
570
|
-
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);
|
|
571
820
|
const postToolUse = config.hooks.PostToolUse ?? [];
|
|
572
|
-
const retained
|
|
573
|
-
const removed = postToolUse.length - retained.length;
|
|
821
|
+
const { retained, removed } = splitTokenjuiceCodexHooks(postToolUse);
|
|
574
822
|
if (retained.length > 0) {
|
|
575
823
|
config.hooks.PostToolUse = retained;
|
|
576
824
|
}
|
|
577
825
|
else {
|
|
578
826
|
delete config.hooks.PostToolUse;
|
|
579
827
|
}
|
|
580
|
-
await
|
|
581
|
-
const tempPath = `${hooksPath}.tmp`;
|
|
582
|
-
await writeFile(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
583
|
-
await rename(tempPath, hooksPath);
|
|
828
|
+
await writeStandaloneHooksConfig(hooksPath, config, sourceText);
|
|
584
829
|
return {
|
|
585
830
|
hooksPath,
|
|
586
831
|
...(backupPath ? { backupPath } : {}),
|
|
587
832
|
removed,
|
|
833
|
+
writer: "standalone",
|
|
834
|
+
fragmentId: CODEX_HOOK_INTEGRATION_ID,
|
|
588
835
|
};
|
|
589
836
|
}
|
|
590
837
|
export async function doctorCodexHook(hooksPath = getDefaultHooksPath(), options = {}) {
|
|
@@ -723,11 +970,14 @@ function shouldStoreFromEnv() {
|
|
|
723
970
|
return value === "1" || value === "true" || value === "TRUE" || value === "yes" || value === "YES";
|
|
724
971
|
}
|
|
725
972
|
async function writeHookDebug(record) {
|
|
973
|
+
if (!shouldRecordStats()) {
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
726
976
|
try {
|
|
727
977
|
const codexHome = getCodexHome();
|
|
728
978
|
const debugPath = join(codexHome, CODEX_HOOK_LAST_LOG);
|
|
729
|
-
const historyPath = join(codexHome, CODEX_HOOK_HISTORY_LOG);
|
|
730
979
|
const enrichedRecord = {
|
|
980
|
+
eventId: randomUUID(),
|
|
731
981
|
timestamp: new Date().toISOString(),
|
|
732
982
|
tokenjuiceVersion: packageJson.version,
|
|
733
983
|
hookCommandPath: process.argv[1],
|
|
@@ -735,93 +985,19 @@ async function writeHookDebug(record) {
|
|
|
735
985
|
};
|
|
736
986
|
await mkdir(dirname(debugPath), { recursive: true });
|
|
737
987
|
await writeFile(debugPath, `${JSON.stringify(enrichedRecord, null, 2)}\n`, "utf8");
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
return text
|
|
746
|
-
.split("\n")
|
|
747
|
-
.map((line) => line.trim())
|
|
748
|
-
.filter(Boolean)
|
|
749
|
-
.filter((line) => {
|
|
750
|
-
try {
|
|
751
|
-
JSON.parse(line);
|
|
752
|
-
return true;
|
|
753
|
-
}
|
|
754
|
-
catch {
|
|
755
|
-
return false;
|
|
756
|
-
}
|
|
757
|
-
});
|
|
758
|
-
}
|
|
759
|
-
function wait(ms) {
|
|
760
|
-
return new Promise((resolvePromise) => {
|
|
761
|
-
setTimeout(resolvePromise, ms);
|
|
762
|
-
});
|
|
763
|
-
}
|
|
764
|
-
async function acquireHistoryLock(lockPath) {
|
|
765
|
-
for (let attempt = 0; attempt <= CODEX_HOOK_HISTORY_LOCK_RETRIES; attempt += 1) {
|
|
766
|
-
try {
|
|
767
|
-
await mkdir(lockPath);
|
|
768
|
-
return true;
|
|
769
|
-
}
|
|
770
|
-
catch (error) {
|
|
771
|
-
const code = error.code;
|
|
772
|
-
if (code !== "EEXIST") {
|
|
773
|
-
throw error;
|
|
774
|
-
}
|
|
775
|
-
try {
|
|
776
|
-
const details = await stat(lockPath);
|
|
777
|
-
if (Date.now() - details.mtimeMs > CODEX_HOOK_HISTORY_LOCK_STALE_MS) {
|
|
778
|
-
await rm(lockPath, { recursive: true, force: true });
|
|
779
|
-
continue;
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
catch (statError) {
|
|
783
|
-
const statCode = statError.code;
|
|
784
|
-
if (statCode !== "ENOENT") {
|
|
785
|
-
throw statError;
|
|
786
|
-
}
|
|
787
|
-
continue;
|
|
788
|
-
}
|
|
789
|
-
if (attempt < CODEX_HOOK_HISTORY_LOCK_RETRIES) {
|
|
790
|
-
await wait(CODEX_HOOK_HISTORY_LOCK_RETRY_MS);
|
|
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;
|
|
791
995
|
}
|
|
792
996
|
}
|
|
997
|
+
await appendBoundedJsonl(join(codexHome, CODEX_HOOK_HISTORY_DIRECTORY), CODEX_HOOK_HISTORY_PREFIX, enrichedRecord.eventId, historyRecord);
|
|
793
998
|
}
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
async function writeHookHistoryEntry(historyPath, line) {
|
|
797
|
-
const lockPath = `${historyPath}.lock`;
|
|
798
|
-
const tempPath = `${historyPath}.${process.pid}.tmp`;
|
|
799
|
-
const hasLock = await acquireHistoryLock(lockPath);
|
|
800
|
-
if (!hasLock) {
|
|
801
|
-
await appendFile(historyPath, `${line}\n`, "utf8");
|
|
802
|
-
return;
|
|
803
|
-
}
|
|
804
|
-
try {
|
|
805
|
-
let historyLines = [];
|
|
806
|
-
try {
|
|
807
|
-
historyLines = sanitizeHookHistoryLines(await readFile(historyPath, "utf8"));
|
|
808
|
-
}
|
|
809
|
-
catch (error) {
|
|
810
|
-
const code = error.code;
|
|
811
|
-
if (code !== "ENOENT") {
|
|
812
|
-
throw error;
|
|
813
|
-
}
|
|
814
|
-
}
|
|
815
|
-
historyLines.push(line);
|
|
816
|
-
if (historyLines.length > CODEX_HOOK_HISTORY_LIMIT) {
|
|
817
|
-
historyLines = historyLines.slice(-CODEX_HOOK_HISTORY_LIMIT);
|
|
818
|
-
}
|
|
819
|
-
await writeFile(tempPath, `${historyLines.join("\n")}\n`, "utf8");
|
|
820
|
-
await rename(tempPath, historyPath);
|
|
821
|
-
}
|
|
822
|
-
finally {
|
|
823
|
-
await rm(tempPath, { force: true }).catch(() => { });
|
|
824
|
-
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.
|
|
825
1001
|
}
|
|
826
1002
|
}
|
|
827
1003
|
function buildImmediateSkipStats(text) {
|
|
@@ -834,23 +1010,36 @@ function buildImmediateSkipStats(text) {
|
|
|
834
1010
|
};
|
|
835
1011
|
}
|
|
836
1012
|
async function recordImmediateHookStats(input, rawText, storeRaw) {
|
|
837
|
-
|
|
1013
|
+
const recordStats = shouldRecordStats();
|
|
1014
|
+
if (!storeRaw && !recordStats) {
|
|
838
1015
|
return;
|
|
839
1016
|
}
|
|
840
1017
|
const stats = buildImmediateSkipStats(rawText);
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
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
|
+
}
|
|
852
1040
|
}
|
|
853
1041
|
export async function runCodexPostToolUseHook(rawText, options = {}) {
|
|
1042
|
+
const hookStartedAt = Date.now();
|
|
854
1043
|
validateCodexOmissionPolicy(options);
|
|
855
1044
|
let payload;
|
|
856
1045
|
try {
|
|
@@ -867,29 +1056,40 @@ export async function runCodexPostToolUseHook(rawText, options = {}) {
|
|
|
867
1056
|
command,
|
|
868
1057
|
noOmit,
|
|
869
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
|
+
});
|
|
870
1070
|
};
|
|
871
1071
|
if (payload.hook_event_name !== "PostToolUse") {
|
|
872
|
-
await
|
|
1072
|
+
await writeDebug({ ...debug, skipped: "non-post-tool-use" });
|
|
873
1073
|
return 0;
|
|
874
1074
|
}
|
|
875
1075
|
if (payload.tool_name !== "Bash") {
|
|
876
|
-
await
|
|
1076
|
+
await writeDebug({ ...debug, skipped: "non-bash" });
|
|
877
1077
|
return 0;
|
|
878
1078
|
}
|
|
879
1079
|
if (typeof command !== "string" || !command.trim()) {
|
|
880
|
-
await
|
|
1080
|
+
await writeDebug({ ...debug, skipped: "missing-command" });
|
|
881
1081
|
return 0;
|
|
882
1082
|
}
|
|
883
1083
|
const combinedText = stringifyToolResponse(payload.tool_response);
|
|
884
1084
|
if (!combinedText.trim()) {
|
|
885
|
-
await
|
|
1085
|
+
await writeDebug({ ...debug, skipped: "empty-tool-response" });
|
|
886
1086
|
return 0;
|
|
887
1087
|
}
|
|
888
1088
|
const rawBytes = Buffer.byteLength(combinedText, "utf8");
|
|
889
1089
|
if (rawBytes > CODEX_HOOK_MAX_COMPACTION_BYTES) {
|
|
890
1090
|
const plainText = stripAnsi(combinedText);
|
|
891
1091
|
const rawChars = countTextChars(plainText);
|
|
892
|
-
await
|
|
1092
|
+
await writeDebug({
|
|
893
1093
|
...debug,
|
|
894
1094
|
rawChars,
|
|
895
1095
|
rawBytes,
|
|
@@ -912,10 +1112,24 @@ export async function runCodexPostToolUseHook(rawText, options = {}) {
|
|
|
912
1112
|
},
|
|
913
1113
|
};
|
|
914
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
|
+
}
|
|
915
1129
|
if (commandRequestsTokenjuiceRawBypass(command)) {
|
|
916
1130
|
await recordImmediateHookStats(executionInput, combinedText, storeRaw);
|
|
917
1131
|
const stats = buildImmediateSkipStats(combinedText);
|
|
918
|
-
await
|
|
1132
|
+
await writeDebug({
|
|
919
1133
|
...debug,
|
|
920
1134
|
...stats,
|
|
921
1135
|
skipped: "explicit-raw-bypass",
|
|
@@ -926,7 +1140,7 @@ export async function runCodexPostToolUseHook(rawText, options = {}) {
|
|
|
926
1140
|
if (inspectionSkipReason) {
|
|
927
1141
|
await recordImmediateHookStats(executionInput, combinedText, storeRaw);
|
|
928
1142
|
const stats = buildImmediateSkipStats(combinedText);
|
|
929
|
-
await
|
|
1143
|
+
await writeDebug({
|
|
930
1144
|
...debug,
|
|
931
1145
|
...stats,
|
|
932
1146
|
skipped: inspectionSkipReason,
|
|
@@ -945,6 +1159,7 @@ export async function runCodexPostToolUseHook(rawText, options = {}) {
|
|
|
945
1159
|
...(typeof maxInlineChars === "number" ? { maxInlineChars } : {}),
|
|
946
1160
|
...(noOmit ? { noOmit: true } : {}),
|
|
947
1161
|
storeRaw,
|
|
1162
|
+
recordStats: shouldRecordStats(),
|
|
948
1163
|
metadata: {
|
|
949
1164
|
source: "codex-post-tool-use",
|
|
950
1165
|
},
|
|
@@ -966,25 +1181,28 @@ export async function runCodexPostToolUseHook(rawText, options = {}) {
|
|
|
966
1181
|
debug.compaction = result.compaction;
|
|
967
1182
|
}
|
|
968
1183
|
if (outcome.action === "keep") {
|
|
969
|
-
await
|
|
1184
|
+
await writeDebug({ ...debug, deliveryMode: "original-only", skipped: outcome.reason });
|
|
970
1185
|
return 0;
|
|
971
1186
|
}
|
|
972
1187
|
const replacement = buildCodexReplacementOutput(outcome.result.inlineText, outcome.result.rawRef?.id, outcome.result.compaction, exitCode, maxInlineChars, noOmit);
|
|
973
1188
|
if (!replacement) {
|
|
974
|
-
await
|
|
1189
|
+
await writeDebug({ ...debug, deliveryMode: "original-only", skipped: "observation-inline-limit" });
|
|
975
1190
|
return 0;
|
|
976
1191
|
}
|
|
977
1192
|
process.stdout.write(`${JSON.stringify(replacement.payload)}\n`);
|
|
978
|
-
await
|
|
1193
|
+
await writeDebug({
|
|
979
1194
|
...debug,
|
|
980
1195
|
rewrote: true,
|
|
1196
|
+
deliveryMode: "original-plus-additional-context",
|
|
1197
|
+
measurement: "pre-delivery-summary-characters",
|
|
981
1198
|
feedbackTruncated: replacement.truncated,
|
|
982
1199
|
});
|
|
983
1200
|
return 0;
|
|
984
1201
|
}
|
|
985
1202
|
catch (error) {
|
|
986
|
-
await
|
|
1203
|
+
await writeDebug({
|
|
987
1204
|
...debug,
|
|
1205
|
+
deliveryMode: "original-only",
|
|
988
1206
|
skipped: "hook-error",
|
|
989
1207
|
error: error instanceof Error ? error.message : String(error),
|
|
990
1208
|
});
|