token-goat 2.9.29 → 2.9.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -40
- package/SECURITY.md +28 -10
- package/THIRD_PARTY_NOTICES.md +40 -3
- package/dist/native/linux-arm64/tg-hook +0 -0
- package/dist/native/linux-x64/tg-hook +0 -0
- package/dist/ort-wasm-simd-threaded.mjs +59 -0
- package/dist/token-goat-chunk-3CHUNJ2O.mjs +53 -0
- package/dist/token-goat-chunk-3Z5S4KGM.mjs +918 -0
- package/dist/token-goat-chunk-4FVIAHSI.mjs +211 -0
- package/dist/{token-goat-chunk-PGTH2U4C.mjs → token-goat-chunk-4JJS54TR.mjs} +4 -3
- package/dist/token-goat-chunk-4LCCNRTG.mjs +313 -0
- package/dist/{token-goat-chunk-L7H3U27L.mjs → token-goat-chunk-54K3EUV3.mjs} +1 -1
- package/dist/token-goat-chunk-56EIMS3E.mjs +159 -0
- package/dist/token-goat-chunk-5BCIJXMO.mjs +609 -0
- package/dist/token-goat-chunk-5KDMCMF2.mjs +362 -0
- package/dist/token-goat-chunk-5RG5SBL6.mjs +221 -0
- package/dist/{token-goat-chunk-RRNZMM3A.mjs → token-goat-chunk-5Y6ZYL6U.mjs} +21 -2
- package/dist/{token-goat-chunk-GLXRTTLE.mjs → token-goat-chunk-64FBPDTK.mjs} +12 -8
- package/dist/{token-goat-chunk-G23DWHV4.mjs → token-goat-chunk-664RTTUV.mjs} +28 -15
- package/dist/token-goat-chunk-67TQJ76B.mjs +57 -0
- package/dist/token-goat-chunk-6QMAS7AB.mjs +42 -0
- package/dist/token-goat-chunk-7BXSNBY5.mjs +253 -0
- package/dist/{token-goat-chunk-IVWI2OCK.mjs → token-goat-chunk-7F2UBPD3.mjs} +40 -11
- package/dist/{token-goat-chunk-TGOXNAHW.mjs → token-goat-chunk-7IN2MKDS.mjs} +682 -501
- package/dist/token-goat-chunk-7NADEDKJ.mjs +124 -0
- package/dist/{token-goat-chunk-KOPIR3KZ.mjs → token-goat-chunk-A3CK6N5Z.mjs} +618 -72
- package/dist/{token-goat-chunk-O6I2XU4P.mjs → token-goat-chunk-AFLYLHDH.mjs} +44 -31
- package/dist/{token-goat-chunk-TCQANXYC.mjs → token-goat-chunk-AM5V6GSX.mjs} +18 -2
- package/dist/{token-goat-chunk-E4ZOJIZK.mjs → token-goat-chunk-APGZXSPS.mjs} +39 -146
- package/dist/{token-goat-chunk-D4ETHJD6.mjs → token-goat-chunk-ARDNEC2U.mjs} +9 -7
- package/dist/token-goat-chunk-ATCPY7EQ.mjs +134 -0
- package/dist/token-goat-chunk-B2RZZCSS.mjs +354 -0
- package/dist/{token-goat-chunk-BGYOZ6DO.mjs → token-goat-chunk-B45VMIIH.mjs} +6 -7
- package/dist/token-goat-chunk-BPGCUMR7.mjs +30 -0
- package/dist/{token-goat-chunk-TDUT2CL6.mjs → token-goat-chunk-C63JQV5K.mjs} +45 -6
- package/dist/{token-goat-chunk-ZER6EAXZ.mjs → token-goat-chunk-COBQGL5S.mjs} +2661 -2440
- package/dist/token-goat-chunk-COTXZHTS.mjs +39 -0
- package/dist/{token-goat-chunk-RQGGMPCR.mjs → token-goat-chunk-CYCEYAEO.mjs} +76 -16
- package/dist/token-goat-chunk-CZ3LUXYZ.mjs +4115 -0
- package/dist/{token-goat-chunk-ASLWOQ3I.mjs → token-goat-chunk-DZX2YDPT.mjs} +2 -1
- package/dist/token-goat-chunk-E3OQX2XT.mjs +824 -0
- package/dist/token-goat-chunk-EFHMMIGP.mjs +68 -0
- package/dist/token-goat-chunk-ETBHVDB6.mjs +328 -0
- package/dist/token-goat-chunk-EVMZJ27Z.mjs +147 -0
- package/dist/token-goat-chunk-EXKGNHEG.mjs +2096 -0
- package/dist/{token-goat-chunk-RTMVLHWX.mjs → token-goat-chunk-FBNQNSJK.mjs} +2555 -5127
- package/dist/{token-goat-chunk-NMTKNYGF.mjs → token-goat-chunk-FNFBKLRD.mjs} +74 -9
- package/dist/{token-goat-chunk-RLP6J7WR.mjs → token-goat-chunk-FZ3NEW5O.mjs} +33 -19
- package/dist/token-goat-chunk-G5PJ7AGM.mjs +36 -0
- package/dist/{token-goat-chunk-DNRPXHYH.mjs → token-goat-chunk-GFBSN7BD.mjs} +29 -401
- package/dist/{token-goat-chunk-XYWPOSCN.mjs → token-goat-chunk-GOLEOXZP.mjs} +763 -211
- package/dist/token-goat-chunk-H2K3QP6H.mjs +24 -0
- package/dist/token-goat-chunk-H2PHHGM5.mjs +188 -0
- package/dist/token-goat-chunk-HAVAOB3S.mjs +87 -0
- package/dist/token-goat-chunk-HG45AF2B.mjs +2228 -0
- package/dist/{token-goat-chunk-HUYUHODZ.mjs → token-goat-chunk-HOJLCGDP.mjs} +12965 -11748
- package/dist/{token-goat-chunk-435UQTKD.mjs → token-goat-chunk-HYBFA5X3.mjs} +118 -19
- package/dist/token-goat-chunk-IVALLT3S.mjs +48 -0
- package/dist/{token-goat-chunk-UXSXQQIY.mjs → token-goat-chunk-IVKIZWAB.mjs} +3 -3
- package/dist/{token-goat-chunk-52NSDWYY.mjs → token-goat-chunk-JB6QN6VF.mjs} +6 -4
- package/dist/{token-goat-chunk-HNFZZHFW.mjs → token-goat-chunk-JDHE26RP.mjs} +10 -3
- package/dist/{token-goat-chunk-FTP4U4QA.mjs → token-goat-chunk-JDU3EXSU.mjs} +12 -11
- package/dist/token-goat-chunk-JDWCRD6M.mjs +253 -0
- package/dist/{token-goat-chunk-6AK46ZT7.mjs → token-goat-chunk-JN4XMLSD.mjs} +5 -1
- package/dist/token-goat-chunk-JTQQGXZH.mjs +733 -0
- package/dist/token-goat-chunk-KKUFXAPD.mjs +25 -0
- package/dist/token-goat-chunk-KQNZDCBD.mjs +47 -0
- package/dist/{token-goat-chunk-2WOUYWLM.mjs → token-goat-chunk-KWPNJBDH.mjs} +27 -3
- package/dist/{token-goat-chunk-DPNLUJWB.mjs → token-goat-chunk-LOBGHXPB.mjs} +30 -8
- package/dist/token-goat-chunk-MKPF4CL5.mjs +37 -0
- package/dist/token-goat-chunk-MNWKPRAL.mjs +13 -0
- package/dist/{token-goat-chunk-DNSPXQXQ.mjs → token-goat-chunk-N2NMER56.mjs} +25 -15
- package/dist/token-goat-chunk-NYKZLXMK.mjs +218 -0
- package/dist/token-goat-chunk-OJBNYTJP.mjs +3087 -0
- package/dist/token-goat-chunk-P4QMM4WK.mjs +295 -0
- package/dist/token-goat-chunk-PD5VKH46.mjs +184 -0
- package/dist/token-goat-chunk-PEPTHRFF.mjs +129 -0
- package/dist/{token-goat-chunk-NMBWLRHW.mjs → token-goat-chunk-PU7V3FD6.mjs} +8721 -11104
- package/dist/token-goat-chunk-PY533T7F.mjs +46 -0
- package/dist/token-goat-chunk-Q5VTGRH7.mjs +761 -0
- package/dist/{token-goat-chunk-67BNIKKO.mjs → token-goat-chunk-QCLDAQTS.mjs} +31 -20
- package/dist/{token-goat-chunk-SE6E4BKJ.mjs → token-goat-chunk-QSBRTGM2.mjs} +9 -2
- package/dist/{token-goat-chunk-VZQEWRVH.mjs → token-goat-chunk-RC35RBUL.mjs} +4 -4
- package/dist/{token-goat-chunk-VMFWNHGR.mjs → token-goat-chunk-RHXKCZX3.mjs} +873 -504
- package/dist/{token-goat-chunk-PYSUADX4.mjs → token-goat-chunk-RZRTDST7.mjs} +17 -7
- package/dist/{token-goat-chunk-ONXH6NZ5.mjs → token-goat-chunk-SJHWVNDQ.mjs} +15 -21
- package/dist/token-goat-chunk-SMVRN2HU.mjs +188 -0
- package/dist/{token-goat-chunk-QO3LXVVR.mjs → token-goat-chunk-SQSSNQPE.mjs} +2295 -1718
- package/dist/{token-goat-chunk-2AWQ2R5X.mjs → token-goat-chunk-T4FK7VOV.mjs} +2 -2
- package/dist/token-goat-chunk-U4N3BN2W.mjs +92 -0
- package/dist/token-goat-chunk-UA5V6P3P.mjs +122 -0
- package/dist/{token-goat-chunk-UA5BKWWQ.mjs → token-goat-chunk-UQ5UK2T7.mjs} +15 -4
- package/dist/token-goat-chunk-USILZ3T3.mjs +53 -0
- package/dist/{token-goat-chunk-MELOKFDJ.mjs → token-goat-chunk-VES7EL7O.mjs} +7 -1
- package/dist/{token-goat-chunk-7CPMDFGB.mjs → token-goat-chunk-VL3YIFHZ.mjs} +389 -14
- package/dist/{token-goat-chunk-E5TK5DNO.mjs → token-goat-chunk-VPBBTSJR.mjs} +356 -129
- package/dist/{token-goat-chunk-YOOVFPTP.mjs → token-goat-chunk-W3QCJS6G.mjs} +10 -2
- package/dist/{token-goat-chunk-LZNBQTDK.mjs → token-goat-chunk-WY3L4DVT.mjs} +11 -7
- package/dist/token-goat-chunk-XKI4SEMX.mjs +66 -0
- package/dist/token-goat-chunk-XU4P6Z24.mjs +133 -0
- package/dist/{token-goat-chunk-H5J3C56Q.mjs → token-goat-chunk-Y776AENC.mjs} +112 -26
- package/dist/token-goat-chunk-YARZFCZS.mjs +359 -0
- package/dist/{token-goat-chunk-S4VSXURL.mjs → token-goat-chunk-Z44YO3QZ.mjs} +4 -0
- package/dist/token-goat-chunk-Z57YODA2.mjs +35 -0
- package/dist/{token-goat-chunk-PQ53BSCF.mjs → token-goat-chunk-ZCDTCVIS.mjs} +48 -29
- package/dist/token-goat-chunk-ZEJVMUQH.mjs +48 -0
- package/dist/{token-goat-chunk-BGHSSJUA.mjs → token-goat-chunk-ZFOBKUWH.mjs} +1 -1
- package/dist/token-goat-chunk-ZMBL6UVV.mjs +110 -0
- package/dist/{token-goat-chunk-PKRWMHVP.mjs → token-goat-chunk-ZQSJMO2R.mjs} +338 -170
- package/dist/token-goat-hook-client.cjs +87 -23
- package/dist/token-goat-hook-client.mjs +3 -3
- package/dist/token-goat-hook.mjs +46 -30
- package/dist/token-goat.core.mjs +6 -6
- package/docs/C4_RUNTIME_ARCHITECTURE.md +1 -1
- package/docs/cli.md +80 -46
- package/docs/install.md +47 -14
- package/docs/security.md +7 -7
- package/package.json +17 -7
- package/scripts/verify-native-dist.mjs +386 -0
- package/dist/token-goat-chunk-2NNUA2LR.mjs +0 -143
- package/dist/token-goat-chunk-44BM7DDQ.mjs +0 -294
- package/dist/token-goat-chunk-C5YPNZKQ.mjs +0 -318
- package/dist/token-goat-chunk-CIQ2FTY3.mjs +0 -1990
- package/dist/token-goat-chunk-EUSDXRXU.mjs +0 -1429
- package/dist/token-goat-chunk-G7IWXCFF.mjs +0 -456
- package/dist/token-goat-chunk-JTKCQMQA.mjs +0 -418
- package/dist/token-goat-chunk-ORNFMIER.mjs +0 -295
- package/dist/token-goat-chunk-VQ6F6T7X.mjs +0 -36
- package/dist/token-goat-chunk-YAGLESS3.mjs +0 -23
- package/dist/token-goat-chunk-YKSRAWUU.mjs +0 -33
- package/dist/token-goat-chunk-Z6KBMOBI.mjs +0 -53
|
@@ -0,0 +1,3087 @@
|
|
|
1
|
+
import { createRequire as __cjsRequire } from 'node:module';
|
|
2
|
+
const require = __cjsRequire(import.meta.url);
|
|
3
|
+
import {
|
|
4
|
+
compareSemver
|
|
5
|
+
} from "./token-goat-chunk-B2RZZCSS.mjs";
|
|
6
|
+
import {
|
|
7
|
+
jsonc,
|
|
8
|
+
stripBom
|
|
9
|
+
} from "./token-goat-chunk-XKI4SEMX.mjs";
|
|
10
|
+
import {
|
|
11
|
+
HOOKS_CONFIG_FILE,
|
|
12
|
+
copilotHooksOwnersPath,
|
|
13
|
+
readCopilotHooksOwners
|
|
14
|
+
} from "./token-goat-chunk-G5PJ7AGM.mjs";
|
|
15
|
+
import {
|
|
16
|
+
toolMatcherFor
|
|
17
|
+
} from "./token-goat-chunk-P4QMM4WK.mjs";
|
|
18
|
+
import {
|
|
19
|
+
COPILOT_CLI_TOOL_NAME_MAP,
|
|
20
|
+
copilotCliUserRoot,
|
|
21
|
+
foldToolName
|
|
22
|
+
} from "./token-goat-chunk-VPBBTSJR.mjs";
|
|
23
|
+
import {
|
|
24
|
+
claudeConfigDir
|
|
25
|
+
} from "./token-goat-chunk-BPGCUMR7.mjs";
|
|
26
|
+
import {
|
|
27
|
+
loadConfig,
|
|
28
|
+
nativeHooksEnabled,
|
|
29
|
+
parse,
|
|
30
|
+
stringify
|
|
31
|
+
} from "./token-goat-chunk-7IN2MKDS.mjs";
|
|
32
|
+
import {
|
|
33
|
+
registerReset
|
|
34
|
+
} from "./token-goat-chunk-YZAAZU2S.mjs";
|
|
35
|
+
import {
|
|
36
|
+
assertWriteInScope,
|
|
37
|
+
atomicWriteText,
|
|
38
|
+
backupFile,
|
|
39
|
+
commandHookFields,
|
|
40
|
+
ensureDirRecordingCreation,
|
|
41
|
+
ensureDirSync,
|
|
42
|
+
escapeRegExp,
|
|
43
|
+
extractErrorMessage,
|
|
44
|
+
hasCreatedConfig,
|
|
45
|
+
hookCommandFor,
|
|
46
|
+
hookExecPartsFor,
|
|
47
|
+
hookPowershellCommand,
|
|
48
|
+
isOwnHookEntry,
|
|
49
|
+
projectScopeRoot,
|
|
50
|
+
recordCreatedBy,
|
|
51
|
+
recordCreatedConfig,
|
|
52
|
+
recordCreatedRootKey,
|
|
53
|
+
removeCreatedBackups,
|
|
54
|
+
removeCreatedIfEmpty,
|
|
55
|
+
removeCreatedTree,
|
|
56
|
+
removeFileInScope,
|
|
57
|
+
stripDelimitedBlock,
|
|
58
|
+
stripOwnHooksFromMap,
|
|
59
|
+
stripStaleGroupHooks,
|
|
60
|
+
takeCreatedConfig,
|
|
61
|
+
takeCreatedRootKey,
|
|
62
|
+
upsertDelimitedBlock,
|
|
63
|
+
withInstallScope,
|
|
64
|
+
withRetryOnLock,
|
|
65
|
+
writeConfigText,
|
|
66
|
+
writeIfDifferent,
|
|
67
|
+
writeJsonSettings
|
|
68
|
+
} from "./token-goat-chunk-GOLEOXZP.mjs";
|
|
69
|
+
import {
|
|
70
|
+
powershellHookLine,
|
|
71
|
+
quotePosixShellWord,
|
|
72
|
+
quotePowershellPath,
|
|
73
|
+
resolveOnPath,
|
|
74
|
+
spawnResolvedSync
|
|
75
|
+
} from "./token-goat-chunk-AM5V6GSX.mjs";
|
|
76
|
+
import {
|
|
77
|
+
normalizeDarwinSystemAlias
|
|
78
|
+
} from "./token-goat-chunk-FNFBKLRD.mjs";
|
|
79
|
+
import {
|
|
80
|
+
dataDir
|
|
81
|
+
} from "./token-goat-chunk-VES7EL7O.mjs";
|
|
82
|
+
import {
|
|
83
|
+
init_define_import_meta_env
|
|
84
|
+
} from "./token-goat-chunk-A37V4PBF.mjs";
|
|
85
|
+
|
|
86
|
+
// src/bridges/claudecode.ts
|
|
87
|
+
init_define_import_meta_env();
|
|
88
|
+
|
|
89
|
+
// src/bridges/shim_common.ts
|
|
90
|
+
init_define_import_meta_env();
|
|
91
|
+
|
|
92
|
+
// src/bridges/shim_try_server.ts
|
|
93
|
+
init_define_import_meta_env();
|
|
94
|
+
var SHIM_TRY_SERVER = `// Attempts the resident hook server (src/hook_server.ts): the sibling hook client sends this
|
|
95
|
+
// call to an already-running token-goat process, so neither Node's module loading nor the hook
|
|
96
|
+
// graph is paid for again. The CommonJS client comes first: this shim is CommonJS, and loading
|
|
97
|
+
// the ES module one starts Node's ESM loader, about 5ms of a call the server answers. The ES
|
|
98
|
+
// module one is for an install built before the CommonJS file existed. It returns undefined
|
|
99
|
+
// whenever nothing was dispatched -- no server yet (it starts one in the background), all busy,
|
|
100
|
+
// replaced by a newer build, turned off, or an install predating the client -- and the caller
|
|
101
|
+
// then runs the call itself.
|
|
102
|
+
async function tryServer(entryPath, eventName, input, harnessWaitMs) {
|
|
103
|
+
if (!entryPath) return undefined
|
|
104
|
+
try {
|
|
105
|
+
const fs = require('node:fs')
|
|
106
|
+
const cjsPath = path.join(path.dirname(entryPath), 'token-goat-hook-client.cjs')
|
|
107
|
+
const mjsPath = path.join(path.dirname(entryPath), 'token-goat-hook-client.mjs')
|
|
108
|
+
const client = fs.existsSync(cjsPath) ? require(cjsPath) : fs.existsSync(mjsPath) ? await import(pathToFileURL(mjsPath).href) : undefined
|
|
109
|
+
if (client === undefined) return undefined
|
|
110
|
+
return await client.relayViaServer(eventName, input, harnessWaitMs)
|
|
111
|
+
} catch {
|
|
112
|
+
return undefined
|
|
113
|
+
}
|
|
114
|
+
}`;
|
|
115
|
+
|
|
116
|
+
// src/bridges/shim_common.ts
|
|
117
|
+
var SHIM_FILE = "token-goat-shim.cjs";
|
|
118
|
+
var LEGACY_SHIM_FILE = "token-goat-shim.js";
|
|
119
|
+
function legacyShimForwarder(noOp) {
|
|
120
|
+
const answer = noOp === "" ? "" : `
|
|
121
|
+
try { process.stdout.write('${noOp}') } catch {}`;
|
|
122
|
+
return `#!/usr/bin/env node
|
|
123
|
+
// Forwards to token-goat-shim.cjs for hook commands wired before the shim was renamed.
|
|
124
|
+
import('./token-goat-shim.cjs').catch(() => {${answer}
|
|
125
|
+
process.exitCode = 0
|
|
126
|
+
});
|
|
127
|
+
`;
|
|
128
|
+
}
|
|
129
|
+
var SHIM_REQUIRES = `const { spawnSync } = require('node:child_process')
|
|
130
|
+
const path = require('node:path')
|
|
131
|
+
const { pathToFileURL } = require('node:url')`;
|
|
132
|
+
var SHIM_VALID_HOOK_EVENTS = `// Keep in sync with HOOK_EVENTS in src/types.ts. eventName is validated against this closed
|
|
133
|
+
// set before being concatenated into a shell command string, so a hostile argv (e.g.
|
|
134
|
+
// 'pre_tool_use & calc.exe') can never reach the shell parser.
|
|
135
|
+
const VALID_HOOK_EVENTS = new Set([
|
|
136
|
+
'pre_tool_use',
|
|
137
|
+
'post_tool_use',
|
|
138
|
+
'notification',
|
|
139
|
+
'stop',
|
|
140
|
+
'pre_compact',
|
|
141
|
+
'post_compact',
|
|
142
|
+
'user_prompt_submit',
|
|
143
|
+
'subagent_stop',
|
|
144
|
+
'subagent_start',
|
|
145
|
+
'session_start',
|
|
146
|
+
'post_tool_use_failure',
|
|
147
|
+
])`;
|
|
148
|
+
var SHIM_TRY_IN_PROCESS = `// Attempts the in-process hook call: import()s dist/token-goat-hook.mjs (a sibling of
|
|
149
|
+
// the baked token-goat entry path, built with zero load-time side effects -- unlike
|
|
150
|
+
// the CLI entry, which runs the full argv-parsing CLI as a side effect of being
|
|
151
|
+
// loaded) and calls its exported relayInProcess() directly, avoiding a second node
|
|
152
|
+
// process spawn entirely. Returns undefined (triggering the spawnSync fallback below)
|
|
153
|
+
// when entryPath is absent, the sibling file doesn't exist (an older install predating
|
|
154
|
+
// this file), or anything else goes wrong -- this must never throw. harnessWaitMs, when
|
|
155
|
+
// the caller has one (Claude Code's async-detach marker time -- see SHIM_ASYNC_DETACH),
|
|
156
|
+
// is forwarded straight through: this runs in the same process as the caller, so its
|
|
157
|
+
// performance.now() reading shares the same origin and needs no conversion.
|
|
158
|
+
async function tryInProcess(entryPath, eventName, input, harnessWaitMs) {
|
|
159
|
+
if (!entryPath) return undefined
|
|
160
|
+
try {
|
|
161
|
+
const payload = JSON.parse(input)
|
|
162
|
+
const served = await tryServer(entryPath, eventName, input, harnessWaitMs)
|
|
163
|
+
if (served !== undefined) return served
|
|
164
|
+
const hookLibPath = path.join(path.dirname(entryPath), 'token-goat-hook.mjs')
|
|
165
|
+
if (!require('node:fs').existsSync(hookLibPath)) return undefined
|
|
166
|
+
const mod = await import(pathToFileURL(hookLibPath).href)
|
|
167
|
+
return await mod.relayInProcess(eventName, payload, harnessWaitMs)
|
|
168
|
+
} catch {
|
|
169
|
+
return undefined
|
|
170
|
+
}
|
|
171
|
+
}`;
|
|
172
|
+
var SHIM_SPAWN_LADDER = ` const res = entryPath
|
|
173
|
+
? spawnSync(process.execPath, [entryPath, 'hook', eventName], {
|
|
174
|
+
input,
|
|
175
|
+
encoding: 'utf8',
|
|
176
|
+
timeout: 3000,
|
|
177
|
+
killSignal: 'SIGKILL',
|
|
178
|
+
maxBuffer: SHIM_MAX_BUFFER_BYTES,
|
|
179
|
+
})`;
|
|
180
|
+
var SHIM_MAX_BUFFER_CONST = `const SHIM_MAX_BUFFER_BYTES = 32 * 1024 * 1024`;
|
|
181
|
+
var SHIM_ASYNC_DETACH = `const ASYNC_DETACH_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
|
|
182
|
+
const ASYNC_DETACH_SKIP_EXT_RE = /\\.(md|mdx|markdown|rst)$/i
|
|
183
|
+
const ASYNC_DETACH_BASH_MAX_BYTES = 200
|
|
184
|
+
// Same key order as OUTPUT_FIRST_TOOL_RESPONSE_KEYS in hooks_common.ts.
|
|
185
|
+
const ASYNC_DETACH_BASH_TEXT_KEYS = ['output', 'content', 'text', 'body', 'stdout', 'stderr']
|
|
186
|
+
function bashResultByteLength(resp) {
|
|
187
|
+
if (typeof resp === 'string') return Buffer.byteLength(resp, 'utf8')
|
|
188
|
+
if (resp && typeof resp === 'object') {
|
|
189
|
+
if (typeof resp['persistedOutputSize'] === 'number') return resp['persistedOutputSize']
|
|
190
|
+
for (const key of ASYNC_DETACH_BASH_TEXT_KEYS) {
|
|
191
|
+
if (typeof resp[key] === 'string' && resp[key] !== '') return Buffer.byteLength(resp[key], 'utf8')
|
|
192
|
+
}
|
|
193
|
+
return Buffer.byteLength(JSON.stringify(resp), 'utf8')
|
|
194
|
+
}
|
|
195
|
+
return 0
|
|
196
|
+
}
|
|
197
|
+
function isAsyncDetachEligible(eventName, input) {
|
|
198
|
+
if (eventName === 'subagent_stop') return true
|
|
199
|
+
if (eventName !== 'post_tool_use') return false
|
|
200
|
+
try {
|
|
201
|
+
const payload = JSON.parse(input)
|
|
202
|
+
const toolName = payload['tool_name']
|
|
203
|
+
if (ASYNC_DETACH_TOOLS.has(toolName)) {
|
|
204
|
+
const toolInput = payload['tool_input'] || {}
|
|
205
|
+
const filePath =
|
|
206
|
+
typeof toolInput['file_path'] === 'string'
|
|
207
|
+
? toolInput['file_path']
|
|
208
|
+
: typeof toolInput['notebook_path'] === 'string'
|
|
209
|
+
? toolInput['notebook_path']
|
|
210
|
+
: ''
|
|
211
|
+
return !ASYNC_DETACH_SKIP_EXT_RE.test(filePath)
|
|
212
|
+
}
|
|
213
|
+
if (toolName === 'Bash') return bashResultByteLength(payload['tool_response']) < ASYNC_DETACH_BASH_MAX_BYTES
|
|
214
|
+
return false
|
|
215
|
+
} catch {
|
|
216
|
+
return false
|
|
217
|
+
}
|
|
218
|
+
}`;
|
|
219
|
+
var SHIM_OWN_COMMAND_BYPASS = `const TG_CD_PREFIX_RE = /^(?:cd\\s+(?:"[^"]*"|'[^']*'|\\S+)[ \\t]*(?:&&|;|\\r?\\n)\\s*)+/
|
|
220
|
+
const TG_OWN_COMMAND_RE = /^(?:[A-Za-z_][A-Za-z0-9_]*=\\S+\\s+)*(?:token-goat\\b|node(?:\\.exe)?\\s+["']?(?:\\S*[\\\\/])?token-goat(?:\\.mjs)?["']?\\b)/i
|
|
221
|
+
function isOwnTokenGoatCommand(cmd) {
|
|
222
|
+
if (typeof cmd !== 'string' || cmd.trim() === '') return false
|
|
223
|
+
const body = (cmd.replace(TG_CD_PREFIX_RE, '') || cmd).trim()
|
|
224
|
+
if (/[;&|\`]|\\$\\(/.test(body)) return false
|
|
225
|
+
return TG_OWN_COMMAND_RE.test(body)
|
|
226
|
+
}`;
|
|
227
|
+
|
|
228
|
+
// src/bridges/claudecode.ts
|
|
229
|
+
var CLAUDECODE_HOOK_SCRIPT = `#!/usr/bin/env node
|
|
230
|
+
// token-goat Claude Code hook shim. Reads the hook payload on stdin, forwards it to \`token-goat hook <event>\`, and relays the response on stdout.
|
|
231
|
+
'use strict'
|
|
232
|
+
// Cache V8's compiled bytecode for the 3.4 MB hook bundle this shim import()s below. Without it
|
|
233
|
+
// every hook invocation recompiles that bundle from source, which profiled at ~40ms of the ~148ms
|
|
234
|
+
// a single hook takes -- and a hook fires on every tool call. Worth ~23ms per invocation, measured
|
|
235
|
+
// twice on the installed shim by interleaving both variants: 148ms to 125ms, and later 186ms to
|
|
236
|
+
// 163ms on a busier machine. The floor moves with load; the 23ms it removes does not.
|
|
237
|
+
//
|
|
238
|
+
// It has to be here rather than inside the bundle: a module is compiled before any of its own code
|
|
239
|
+
// runs, so a bundle cannot enable the cache for itself. This shim is small enough to compile in
|
|
240
|
+
// well under a millisecond, and the dynamic import() happens after this line, so the bundle is
|
|
241
|
+
// compiled with the cache already active. Same reason the MCP SDK could not be deferred from
|
|
242
|
+
// inside mcp_server.ts -- what a module can affect starts after it is already compiled.
|
|
243
|
+
//
|
|
244
|
+
// enableCompileCache landed in Node 22.1 and package.json allows >=22.0.0, so a miss is possible;
|
|
245
|
+
// it is also best-effort by nature (read-only cache dir, full disk). Swallow everything: this shim
|
|
246
|
+
// must never fail a tool call to save itself 23ms.
|
|
247
|
+
try { require('node:module').enableCompileCache() } catch { /* older Node, or an unwritable cache dir: run uncached */ }
|
|
248
|
+
${SHIM_REQUIRES}
|
|
249
|
+
|
|
250
|
+
${SHIM_VALID_HOOK_EVENTS}
|
|
251
|
+
|
|
252
|
+
${SHIM_TRY_SERVER}
|
|
253
|
+
|
|
254
|
+
${SHIM_TRY_IN_PROCESS}
|
|
255
|
+
|
|
256
|
+
${SHIM_MAX_BUFFER_CONST}
|
|
257
|
+
|
|
258
|
+
${SHIM_ASYNC_DETACH}
|
|
259
|
+
|
|
260
|
+
${SHIM_OWN_COMMAND_BYPASS}
|
|
261
|
+
|
|
262
|
+
async function main() {
|
|
263
|
+
const eventName = process.argv[2] || ''
|
|
264
|
+
if (!VALID_HOOK_EVENTS.has(eventName)) {
|
|
265
|
+
process.stdout.write('{}')
|
|
266
|
+
return
|
|
267
|
+
}
|
|
268
|
+
let input = ''
|
|
269
|
+
try {
|
|
270
|
+
input = require('node:fs').readFileSync(0, 'utf8')
|
|
271
|
+
} catch {
|
|
272
|
+
process.stdout.write('{}')
|
|
273
|
+
return
|
|
274
|
+
}
|
|
275
|
+
// A pre_tool_use Bash call that is token-goat's own CLI has nothing for the pipeline below to
|
|
276
|
+
// say, so this skips the round trip entirely rather than backgrounding it -- see
|
|
277
|
+
// isOwnTokenGoatCommand's docstring in shim_common.ts for the measured emission rate this
|
|
278
|
+
// forfeits.
|
|
279
|
+
if (eventName === 'pre_tool_use') {
|
|
280
|
+
try {
|
|
281
|
+
const payload = JSON.parse(input)
|
|
282
|
+
if (payload['tool_name'] === 'Bash' && isOwnTokenGoatCommand(payload['tool_input'] && payload['tool_input']['command'])) {
|
|
283
|
+
process.stdout.write('{}')
|
|
284
|
+
return
|
|
285
|
+
}
|
|
286
|
+
} catch {
|
|
287
|
+
// Fall through to normal handling on unparseable stdin.
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
// Print this before the in-process/spawn round trip below, not after: the harness detaches on
|
|
291
|
+
// the first stdout line it sees, and the whole point is not waiting out that round trip for a
|
|
292
|
+
// call that was always going to answer '{}'. asyncDetachAtMs, taken at this exact print, is the
|
|
293
|
+
// last instant this process's elapsed time and the harness's own wait are the same number --
|
|
294
|
+
// record it now so the finally block in relayInProcess (relay.ts) can report what Claude Code
|
|
295
|
+
// actually waited on instead of this call's full lifetime.
|
|
296
|
+
let asyncDetachAtMs
|
|
297
|
+
if (isAsyncDetachEligible(eventName, input)) {
|
|
298
|
+
asyncDetachAtMs = performance.now()
|
|
299
|
+
process.stdout.write('{"async":true}\\n')
|
|
300
|
+
}
|
|
301
|
+
// process.argv[3], when present, is the absolute path to the running token-goat CLI
|
|
302
|
+
// entry (mirrors the same argv[3]-baked-entry convention used by the Codex/Copilot
|
|
303
|
+
// CLI shims). Try the in-process hook lib first (tryInProcess above), which avoids
|
|
304
|
+
// spawning a second node process altogether; fall back to the entry path directly via
|
|
305
|
+
// process.execPath, then finally to the old PATH-based shell:true invocation (an
|
|
306
|
+
// older cached hook config with no argv[3], or a config wired directly to
|
|
307
|
+
// \`token-goat hook <event>\` rather than through this shim). A 3000ms
|
|
308
|
+
// timeout/killSignal on both spawnSync fallbacks means token-goat degrades to its own
|
|
309
|
+
// fail-open '{}' rather than being force-killed by Claude Code's own hook timeout.
|
|
310
|
+
const entryPath = process.argv[3]
|
|
311
|
+
let stdout = await tryInProcess(entryPath, eventName, input, asyncDetachAtMs)
|
|
312
|
+
if (stdout === undefined) {
|
|
313
|
+
// Reaching here with asyncDetachAtMs set means tryInProcess failed after
|
|
314
|
+
// isAsyncDetachEligible had already parsed this same input successfully, so the cause is an
|
|
315
|
+
// install missing its dist/token-goat-hook.mjs sibling or a broken import -- never a bad
|
|
316
|
+
// payload. asyncDetachAtMs is this process's own elapsed time and has no meaning in the
|
|
317
|
+
// spawned child's clock, so it is deliberately not threaded across that boundary; the child
|
|
318
|
+
// falls back to timing its own lifetime, the same already-approximate number every hook got
|
|
319
|
+
// on this fallback path before async-detach existed.
|
|
320
|
+
${SHIM_SPAWN_LADDER}
|
|
321
|
+
: spawnSync('token-goat hook ' + eventName, {
|
|
322
|
+
input,
|
|
323
|
+
encoding: 'utf8',
|
|
324
|
+
shell: true,
|
|
325
|
+
timeout: 3000,
|
|
326
|
+
killSignal: 'SIGKILL',
|
|
327
|
+
maxBuffer: SHIM_MAX_BUFFER_BYTES,
|
|
328
|
+
})
|
|
329
|
+
if (res.status !== 0 || !res.stdout) {
|
|
330
|
+
process.stdout.write('{}')
|
|
331
|
+
return
|
|
332
|
+
}
|
|
333
|
+
stdout = res.stdout
|
|
334
|
+
}
|
|
335
|
+
process.stdout.write(stdout)
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
main().catch(() => {
|
|
339
|
+
process.stdout.write('{}')
|
|
340
|
+
})
|
|
341
|
+
`;
|
|
342
|
+
|
|
343
|
+
// src/bridges/guidance_block.ts
|
|
344
|
+
init_define_import_meta_env();
|
|
345
|
+
function buildGuidanceBody(fallbackToolClause, opts = {}) {
|
|
346
|
+
const gdrive = opts.gdrive !== false;
|
|
347
|
+
return [
|
|
348
|
+
"## token-goat",
|
|
349
|
+
"",
|
|
350
|
+
"**Gate \u2014 before every file read, answer one question first: is there a token-goat command that returns just what I need?** If yes, run it. A read tool invoked without answering the gate is a violation, not an oversight. The gate is per file: batched or parallel reads do not exempt it.",
|
|
351
|
+
"",
|
|
352
|
+
`This gate decides *whether* to reach for a read tool at all. ${fallbackToolClause} only pick the *fallback* once token-goat has been ruled out for this read \u2014 they never authorize skipping the gate.`,
|
|
353
|
+
"",
|
|
354
|
+
"Fallback clauses may name your harness's own native read, search, and edit tools, or its shell helpers. Shell binaries and editor programs are commands invoked through the shell tool, never tool identifiers, and must never appear in an agent's tools frontmatter or an allowed-tools list. This paragraph deliberately names no specific tool or binary: instruction-file loaders harvest such names into a tool allowlist and then warn that every one of them is unknown.",
|
|
355
|
+
"",
|
|
356
|
+
"Exemptions (gate passes, read directly): the file is under ~200 lines and you need all of it; it was never indexed (new, untracked, or generated this turn); it is a genuinely opaque binary (not an image); the target has no symbol handle (e.g. a literal mid-function).",
|
|
357
|
+
"",
|
|
358
|
+
"Failure shapes to catch yourself in, and the command that replaces each:",
|
|
359
|
+
'- not knowing which command answers a question you can already state in words \u2192 `answer "<question>"`, which resolves the subject in the index, runs the right command, prints `via: <command>`, and refuses rather than guess',
|
|
360
|
+
'- a shell text search with context flags to find a function body \u2192 `read "file::symbol"`',
|
|
361
|
+
'- paging one function with view/view_range \u2192 `read "file::symbol"`',
|
|
362
|
+
"- a read refused by a `[tg]` deny, retried with a shifted range or a different read tool \u2192 the command the deny names",
|
|
363
|
+
'- reading a symbol plus chasing its callers and containing doc section as separate reads \u2192 `brief "file::symbol"`',
|
|
364
|
+
'- reading one heading of a large doc \u2192 `section "file::Heading"`',
|
|
365
|
+
"- searching for a symbol's callers \u2192 `refs file::symbol --callers`",
|
|
366
|
+
'- searching across symbols, headings, text, and concepts concurrently \u2192 `search "<query>"`',
|
|
367
|
+
'- searching for a *concept* rather than a literal string \u2192 `semantic "description"`',
|
|
368
|
+
"- re-reading output you already captured \u2192 `bash-output`/`web-output`/`mcp-output` by ID",
|
|
369
|
+
"- a directory listing or recursive wildcard walk to orient in an unfamiliar repo \u2192 `map --compact`",
|
|
370
|
+
"- pulling one value or subtree out of a JSON/YAML/XML file (manifest, lockfile, spec, config) \u2192 `json-query file 'a.b.c'` / `yaml-query file 'a.b.c'` / `xml-query file 'a.b.c'`",
|
|
371
|
+
"- opening an image to check its dimensions, format, or size \u2192 `image-meta file`",
|
|
372
|
+
"- opening a screenshot, diagram, or scan to read the text in it \u2192 `image-text file`",
|
|
373
|
+
"- opening a PDF or Office document \u2192 inspect its format first, then read a narrow slice: PDF `pdf-meta`/`pdf-outline` then `pdf-locate` to find the pages and `pdf-extract` only those; Word `docx-outline` then `docx-tables`/`docx-text`; PowerPoint `pptx-outline` then `pptx-slide`/`pptx-notes`; Excel `xlsx-sheets` then `xlsx-columns`/`xlsx-head`/`xlsx-range`/`xlsx-query`",
|
|
374
|
+
"- running tests immediately on edited code without fast static validation \u2192 run language validator first (e.g. `ruff check --select F821 <file>`, `node --check`, `tsc --noEmit`) to catch missing imports and syntax errors before test execution",
|
|
375
|
+
"- passing concatenated or unquoted paths to shell tools \u2192 verify whitespace and argument separation in multi-path commands (e.g. `git add path1 path2`, never `git add path1path2`)",
|
|
376
|
+
"",
|
|
377
|
+
'Commands: `search "<query>"`, `answer "<question>"`, `symbol NAME`, `read "file::symbol"`, `brief "file::symbol"`, `section "file::Heading"`, `semantic "description"`, `outline file`/`skeleton file`, `map --compact`, `refs file::symbol --callers`, `changed --symbol`, `config-get file KEY`, `json-query file \'a.b.c\'`/`yaml-query`/`xml-query`, `json-outline file`/`yaml-outline`/`xml-outline`, `bash-output`/`web-output`/`mcp-output`, ' + (gdrive ? "`gdrive-sections <file-id>`, " : "") + "`image-meta file`/`image-text file`, `pdf-meta`/`pdf-outline`/`pdf-locate`/`pdf-extract`, `docx-outline`/`docx-tables`/`docx-text`, `pptx-outline`/`pptx-slide`/`pptx-notes`/`pptx-text`, `xlsx-sheets`/`xlsx-columns`/`xlsx-head`/`xlsx-range`/`xlsx-query`.",
|
|
378
|
+
"",
|
|
379
|
+
"Sub-agent briefs must carry this gate verbatim: a sub-agent inherits none of this context and its reads spend the same token budget.",
|
|
380
|
+
"",
|
|
381
|
+
"`token-goat stats` \u2014 self-check. Flat counts during code work mean the gate is being skipped."
|
|
382
|
+
].join("\n");
|
|
383
|
+
}
|
|
384
|
+
function skillDescriptionLine(gdrive) {
|
|
385
|
+
return `description: Use before reading whole files or grepping wide. token-goat commands (symbol, read, section, semantic, outline, skeleton, map, refs, changed, config-get, bash-output, web-output${gdrive ? ", gdrive-sections" : ""}) return narrow slices of code and docs at a fraction of the token cost.`;
|
|
386
|
+
}
|
|
387
|
+
function buildGuidanceBlock(h) {
|
|
388
|
+
return [h.beginMarker, buildGuidanceBody(h.fallbackToolClause, h.gdrive === void 0 ? {} : { gdrive: h.gdrive }), h.endMarker].join("\n");
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// src/install.ts
|
|
392
|
+
init_define_import_meta_env();
|
|
393
|
+
import * as fs2 from "node:fs";
|
|
394
|
+
import * as path2 from "node:path";
|
|
395
|
+
|
|
396
|
+
// src/canonical_skill.ts
|
|
397
|
+
init_define_import_meta_env();
|
|
398
|
+
import { gunzipSync } from "node:zlib";
|
|
399
|
+
var CANONICAL_SKILL_GZIP_BASE64 = "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";
|
|
400
|
+
var CANONICAL_SKILL_MD = gunzipSync(Buffer.from(CANONICAL_SKILL_GZIP_BASE64, "base64")).toString("utf8");
|
|
401
|
+
|
|
402
|
+
// src/native_hook.ts
|
|
403
|
+
init_define_import_meta_env();
|
|
404
|
+
import { spawnSync } from "node:child_process";
|
|
405
|
+
import * as crypto from "node:crypto";
|
|
406
|
+
import * as fs from "node:fs";
|
|
407
|
+
import * as path from "node:path";
|
|
408
|
+
var NATIVE_TARGETS = /* @__PURE__ */ new Set(["win32-x64", "win32-arm64", "linux-x64", "linux-arm64"]);
|
|
409
|
+
var SELFTEST_TIMEOUT_MS = 5e3;
|
|
410
|
+
function exeName(platform = process.platform) {
|
|
411
|
+
return platform === "win32" ? "tg-hook.exe" : "tg-hook";
|
|
412
|
+
}
|
|
413
|
+
function packagedNativeBinary(entryPath = process.argv[1]) {
|
|
414
|
+
if (entryPath === void 0 || entryPath === "") return void 0;
|
|
415
|
+
const target = `${process.platform}-${process.arch}`;
|
|
416
|
+
if (!NATIVE_TARGETS.has(target)) return void 0;
|
|
417
|
+
const bin = path.join(path.dirname(entryPath), "native", target, exeName());
|
|
418
|
+
return fs.existsSync(bin) ? bin : void 0;
|
|
419
|
+
}
|
|
420
|
+
function nativeCopyPath(entryPath, home = dataDir()) {
|
|
421
|
+
let bundleDir = path.dirname(entryPath);
|
|
422
|
+
try {
|
|
423
|
+
bundleDir = fs.realpathSync.native(bundleDir);
|
|
424
|
+
} catch {
|
|
425
|
+
}
|
|
426
|
+
const id = crypto.createHash("sha256").update(bundleDir.toLowerCase()).digest("hex").slice(0, 16);
|
|
427
|
+
return path.join(home, "native", id, exeName("win32"));
|
|
428
|
+
}
|
|
429
|
+
var LEFTOVER = /^tg-hook\.exe\.[0-9a-f]+\.(?:old|new)$/;
|
|
430
|
+
function reclaimLeftovers(dir) {
|
|
431
|
+
let names;
|
|
432
|
+
try {
|
|
433
|
+
names = fs.readdirSync(dir);
|
|
434
|
+
} catch {
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
for (const name of names) {
|
|
438
|
+
if (!LEFTOVER.test(name)) continue;
|
|
439
|
+
try {
|
|
440
|
+
fs.unlinkSync(path.join(dir, name));
|
|
441
|
+
} catch {
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
function syncNativeCopy(src, dest) {
|
|
446
|
+
let want;
|
|
447
|
+
try {
|
|
448
|
+
want = fs.readFileSync(src);
|
|
449
|
+
} catch {
|
|
450
|
+
return false;
|
|
451
|
+
}
|
|
452
|
+
try {
|
|
453
|
+
if (fs.readFileSync(dest).equals(want)) return true;
|
|
454
|
+
} catch {
|
|
455
|
+
}
|
|
456
|
+
const dir = path.dirname(dest);
|
|
457
|
+
const tag = crypto.randomBytes(6).toString("hex");
|
|
458
|
+
const staged = `${dest}.${tag}.new`;
|
|
459
|
+
try {
|
|
460
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
461
|
+
reclaimLeftovers(dir);
|
|
462
|
+
fs.writeFileSync(staged, want, { mode: 493 });
|
|
463
|
+
} catch {
|
|
464
|
+
discardStaged(staged);
|
|
465
|
+
return false;
|
|
466
|
+
}
|
|
467
|
+
try {
|
|
468
|
+
fs.renameSync(staged, dest);
|
|
469
|
+
return true;
|
|
470
|
+
} catch {
|
|
471
|
+
}
|
|
472
|
+
const ready = `${dest}.${crypto.randomBytes(6).toString("hex")}.new`;
|
|
473
|
+
try {
|
|
474
|
+
withRetryOnLock(() => fs.renameSync(staged, ready));
|
|
475
|
+
} catch {
|
|
476
|
+
discardStaged(staged);
|
|
477
|
+
return false;
|
|
478
|
+
}
|
|
479
|
+
const aside = `${dest}.${tag}.old`;
|
|
480
|
+
let movedAside = false;
|
|
481
|
+
try {
|
|
482
|
+
if (fs.existsSync(dest)) {
|
|
483
|
+
withRetryOnLock(() => fs.renameSync(dest, aside));
|
|
484
|
+
movedAside = true;
|
|
485
|
+
}
|
|
486
|
+
withRetryOnLock(() => fs.renameSync(ready, dest));
|
|
487
|
+
return true;
|
|
488
|
+
} catch {
|
|
489
|
+
if (movedAside) {
|
|
490
|
+
try {
|
|
491
|
+
withRetryOnLock(() => fs.renameSync(aside, dest));
|
|
492
|
+
} catch {
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
discardStaged(ready);
|
|
496
|
+
return false;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
function discardStaged(staged) {
|
|
500
|
+
try {
|
|
501
|
+
fs.rmSync(staged, { force: true });
|
|
502
|
+
} catch {
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
function nativeCopyCurrent(src, dest) {
|
|
506
|
+
try {
|
|
507
|
+
return fs.readFileSync(dest).equals(fs.readFileSync(src));
|
|
508
|
+
} catch {
|
|
509
|
+
return false;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
var _selftests = /* @__PURE__ */ new Map();
|
|
513
|
+
function nativeSelftest(bin) {
|
|
514
|
+
const cached = _selftests.get(bin);
|
|
515
|
+
if (cached !== void 0) return cached;
|
|
516
|
+
let result;
|
|
517
|
+
const res = spawnSync(bin, ["--selftest"], { encoding: "utf8", timeout: SELFTEST_TIMEOUT_MS, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
518
|
+
if (res.error !== void 0) result = { ok: false, reason: res.error.code === "ETIMEDOUT" ? `no answer within ${SELFTEST_TIMEOUT_MS} ms` : res.error.message };
|
|
519
|
+
else if (res.status !== 0) result = { ok: false, reason: res.signal !== null ? `killed by ${res.signal}` : `exit code ${String(res.status)}` };
|
|
520
|
+
else result = { ok: true };
|
|
521
|
+
_selftests.set(bin, result);
|
|
522
|
+
return result;
|
|
523
|
+
}
|
|
524
|
+
var _decisions = /* @__PURE__ */ new Map();
|
|
525
|
+
registerReset(() => {
|
|
526
|
+
_selftests.clear();
|
|
527
|
+
_decisions.clear();
|
|
528
|
+
});
|
|
529
|
+
function nativeHookBinary(entryPath = process.argv[1], opts = {}) {
|
|
530
|
+
if (entryPath === void 0 || entryPath === "" || !nativeHooksEnabled()) return void 0;
|
|
531
|
+
const sync = opts.sync !== false;
|
|
532
|
+
const key = `${String(sync)}\0${entryPath}`;
|
|
533
|
+
const cached = _decisions.get(key);
|
|
534
|
+
if (cached !== void 0) return cached ?? void 0;
|
|
535
|
+
const packaged = packagedNativeBinary(entryPath);
|
|
536
|
+
let bin = packaged;
|
|
537
|
+
if (packaged !== void 0 && process.platform === "win32") {
|
|
538
|
+
const copy = nativeCopyPath(entryPath);
|
|
539
|
+
const current = sync ? syncNativeCopy(packaged, copy) : nativeCopyCurrent(packaged, copy);
|
|
540
|
+
bin = current ? copy : void 0;
|
|
541
|
+
}
|
|
542
|
+
if (bin !== void 0 && !nativeSelftest(bin).ok) bin = void 0;
|
|
543
|
+
_decisions.set(key, bin ?? null);
|
|
544
|
+
if (sync) _decisions.set(`false\0${entryPath}`, bin ?? null);
|
|
545
|
+
return bin;
|
|
546
|
+
}
|
|
547
|
+
function nativeHookFlags(harness, event, entry, scriptPath) {
|
|
548
|
+
const flags = ["--harness", harness, "--event", event, "--entry", entry];
|
|
549
|
+
if (harness === "copilot_cli") flags.push("--script-dir", path.dirname(scriptPath));
|
|
550
|
+
return flags;
|
|
551
|
+
}
|
|
552
|
+
function nodeHookArgv(scriptPath, event, entry) {
|
|
553
|
+
if (entry === void 0 || entry === "") return void 0;
|
|
554
|
+
return [process.execPath, scriptPath, event, entry];
|
|
555
|
+
}
|
|
556
|
+
var PATH_FLAGS = /* @__PURE__ */ new Set(["--entry", "--script-dir"]);
|
|
557
|
+
function nativeWords(bin, harness, scriptPath, event, entry) {
|
|
558
|
+
const flags = nativeHookFlags(harness, event, entry, scriptPath);
|
|
559
|
+
const flagWords = flags.map((text, i) => ({ text, quote: i > 0 && PATH_FLAGS.has(flags[i - 1]) }));
|
|
560
|
+
return [{ text: bin, quote: true }, ...flagWords, { text: "--", quote: false }, { text: process.execPath, quote: true }, { text: scriptPath, quote: true }, { text: event, quote: false }, { text: entry, quote: true }];
|
|
561
|
+
}
|
|
562
|
+
function quoteFor(shell, text) {
|
|
563
|
+
if (shell === "sh") return quotePosixShellWord(text);
|
|
564
|
+
if (shell === "powershell") return quotePowershellPath(text);
|
|
565
|
+
return `"${text}"`;
|
|
566
|
+
}
|
|
567
|
+
function nativeHookCommandLine(shell, bin, harness, scriptPath, event, entry = process.argv[1]) {
|
|
568
|
+
if (nodeHookArgv(scriptPath, event, entry) === void 0) return void 0;
|
|
569
|
+
const line = nativeWords(bin, harness, scriptPath, event, entry).map((w) => w.quote ? quoteFor(shell, w.text) : w.text).join(" ");
|
|
570
|
+
return shell === "powershell" ? powershellHookLine(line) : line;
|
|
571
|
+
}
|
|
572
|
+
function nativeHookExecParts(bin, harness, scriptPath, event, entry = process.argv[1]) {
|
|
573
|
+
if (nodeHookArgv(scriptPath, event, entry) === void 0) return void 0;
|
|
574
|
+
return { command: bin, args: nativeWords(bin, harness, scriptPath, event, entry).slice(1).map((w) => w.text) };
|
|
575
|
+
}
|
|
576
|
+
function splitHookCommand(command, shell) {
|
|
577
|
+
const words = [];
|
|
578
|
+
let text = command.trim();
|
|
579
|
+
if (shell === "powershell" && text.startsWith("& ")) text = text.slice(2);
|
|
580
|
+
const posix = shell === "sh";
|
|
581
|
+
const dqEscapes = posix && process.platform !== "win32";
|
|
582
|
+
let cur = "";
|
|
583
|
+
let inWord = false;
|
|
584
|
+
for (let i = 0; i < text.length; i++) {
|
|
585
|
+
const ch = text[i];
|
|
586
|
+
if (ch === ";" && shell === "powershell") break;
|
|
587
|
+
if (/\s/.test(ch)) {
|
|
588
|
+
if (inWord) words.push(cur);
|
|
589
|
+
cur = "";
|
|
590
|
+
inWord = false;
|
|
591
|
+
continue;
|
|
592
|
+
}
|
|
593
|
+
inWord = true;
|
|
594
|
+
if (ch === "'" && shell !== "cmd") {
|
|
595
|
+
for (i++; i < text.length; i++) {
|
|
596
|
+
if (text[i] !== "'") cur += text[i];
|
|
597
|
+
else if (shell === "powershell" && text[i + 1] === "'") cur += text[++i];
|
|
598
|
+
else break;
|
|
599
|
+
}
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
if (ch === '"') {
|
|
603
|
+
for (i++; i < text.length && text[i] !== '"'; i++) {
|
|
604
|
+
if (dqEscapes && text[i] === "\\" && i + 1 < text.length) cur += text[++i];
|
|
605
|
+
else cur += text[i];
|
|
606
|
+
}
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
if (posix && ch === "\\" && i + 1 < text.length && (process.platform !== "win32" || text[i + 1] === "'")) {
|
|
610
|
+
cur += text[++i];
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
cur += ch;
|
|
614
|
+
}
|
|
615
|
+
if (inWord) words.push(cur);
|
|
616
|
+
return words;
|
|
617
|
+
}
|
|
618
|
+
var HookCommandRewriteError = class extends Error {
|
|
619
|
+
};
|
|
620
|
+
function hookCommandRewrittenSpan(command, reader) {
|
|
621
|
+
return (reader === "cmd" ? /%[^%\r\n]+%/ : /\$(?:[A-Za-z_][A-Za-z0-9_]*|\{[^}]*\})/).exec(command)?.[0];
|
|
622
|
+
}
|
|
623
|
+
function parseNativeInvocation(argv) {
|
|
624
|
+
const bin = argv[0];
|
|
625
|
+
if (bin === void 0 || !/^tg-hook(?:\.exe)?$/i.test(path.basename(bin.replace(/\\/g, "/")))) return void 0;
|
|
626
|
+
const split = argv.indexOf("--");
|
|
627
|
+
if (split < 0) return void 0;
|
|
628
|
+
const flags = argv.slice(1, split);
|
|
629
|
+
const h = flags.indexOf("--harness");
|
|
630
|
+
return { bin, harness: h >= 0 ? flags[h + 1] : void 0, wrapped: argv.slice(split + 1) };
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// src/install.ts
|
|
634
|
+
var HOOK_EVENT_MAP = [
|
|
635
|
+
["PreToolUse", "pre_tool_use"],
|
|
636
|
+
["PostToolUse", "post_tool_use"],
|
|
637
|
+
// A failed call never reaches PostToolUse: Claude Code 2.1.281 sends a missing-file Read and a non-zero Bash exit here instead, carrying `error`, `is_interrupt` and `duration_ms` (captured, 2026-09-24).
|
|
638
|
+
["PostToolUseFailure", "post_tool_use_failure"],
|
|
639
|
+
["PreCompact", "pre_compact"],
|
|
640
|
+
["PostCompact", "post_compact"],
|
|
641
|
+
["UserPromptSubmit", "user_prompt_submit"],
|
|
642
|
+
["SubagentStop", "subagent_stop"],
|
|
643
|
+
["SessionStart", "session_start"]
|
|
644
|
+
];
|
|
645
|
+
var SHIM_COMMAND_MARKER = "token-goat-shim";
|
|
646
|
+
var COMMAND_MARKER = "token-goat hook";
|
|
647
|
+
var LEGACY_COMMAND_MARKERS = ["tokenwise", "token_goat", "tg-hook", "token-goat-hook"];
|
|
648
|
+
function anchoredMarkerPattern(marker) {
|
|
649
|
+
const escaped = escapeRegExp(marker);
|
|
650
|
+
return new RegExp(`(?<![a-zA-Z0-9_-])${escaped}(?![a-zA-Z0-9_-])`);
|
|
651
|
+
}
|
|
652
|
+
var HOOK_MARKER_PATTERNS = [SHIM_COMMAND_MARKER, COMMAND_MARKER, ...LEGACY_COMMAND_MARKERS].map(anchoredMarkerPattern);
|
|
653
|
+
function isTokenGoatHookCommand(command, args) {
|
|
654
|
+
const haystack = args !== void 0 && args.length > 0 ? `${command} ${args.join(" ")}` : command;
|
|
655
|
+
return HOOK_MARKER_PATTERNS.some((pattern) => pattern.test(haystack));
|
|
656
|
+
}
|
|
657
|
+
var CLAUDE_EXEC_FORM_MIN_VERSION = "2.1.139";
|
|
658
|
+
var _claudeExecFormHooksSupported;
|
|
659
|
+
function claudeExecFormHooksSupported() {
|
|
660
|
+
const override = process.env["TOKEN_GOAT_CLAUDE_EXEC_FORM_HOOKS"];
|
|
661
|
+
if (override === "1") return true;
|
|
662
|
+
if (override === "0") return false;
|
|
663
|
+
if (_claudeExecFormHooksSupported !== void 0) return _claudeExecFormHooksSupported;
|
|
664
|
+
_claudeExecFormHooksSupported = probeClaudeExecFormHooksSupported();
|
|
665
|
+
return _claudeExecFormHooksSupported;
|
|
666
|
+
}
|
|
667
|
+
function probeClaudeExecFormHooksSupported() {
|
|
668
|
+
const resolved = resolveOnPath("claude");
|
|
669
|
+
if (resolved === null) return false;
|
|
670
|
+
try {
|
|
671
|
+
const result = spawnResolvedSync(resolved, ["--version"], { encoding: "utf-8", timeout: 5e3, windowsHide: true });
|
|
672
|
+
if (result.status !== 0) return false;
|
|
673
|
+
return execFormSupportedForVersionOutput(result.stdout ?? "");
|
|
674
|
+
} catch {
|
|
675
|
+
return false;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
function execFormSupportedForVersionOutput(stdout) {
|
|
679
|
+
const m = /(\d+\.\d+\.\d+)/.exec(stdout);
|
|
680
|
+
if (!m) return false;
|
|
681
|
+
return compareSemver(m[1], CLAUDE_EXEC_FORM_MIN_VERSION) >= 0;
|
|
682
|
+
}
|
|
683
|
+
function expectedHookEntryFor(scriptPath, event, opts = {}) {
|
|
684
|
+
const bin = nativeHookBinary(process.argv[1], opts);
|
|
685
|
+
if (claudeExecFormHooksSupported()) return (bin === void 0 ? void 0 : nativeHookExecParts(bin, "claudecode", scriptPath, event)) ?? hookExecPartsFor(scriptPath, event);
|
|
686
|
+
return { command: (bin === void 0 ? void 0 : nativeHookCommandLine("sh", bin, "claudecode", scriptPath, event)) ?? hookCommandFor(scriptPath, event) };
|
|
687
|
+
}
|
|
688
|
+
function realPathOrNull(p) {
|
|
689
|
+
if (!path2.isAbsolute(p)) return null;
|
|
690
|
+
try {
|
|
691
|
+
return fs2.realpathSync.native(p);
|
|
692
|
+
} catch {
|
|
693
|
+
return null;
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
function sameHookWord(a, b) {
|
|
697
|
+
if (a === b) return true;
|
|
698
|
+
const realA = realPathOrNull(a);
|
|
699
|
+
return realA !== null && realA === realPathOrNull(b);
|
|
700
|
+
}
|
|
701
|
+
function stringFormHookWords(command) {
|
|
702
|
+
return splitHookCommand(command, "sh");
|
|
703
|
+
}
|
|
704
|
+
function hookEntryMatches(command, args, expected) {
|
|
705
|
+
const execForm = expected.args !== void 0;
|
|
706
|
+
if (!execForm && args !== void 0 && args.length > 0) return false;
|
|
707
|
+
const a = execForm ? [command, ...args ?? []] : stringFormHookWords(command);
|
|
708
|
+
const b = execForm ? [expected.command, ...expected.args] : stringFormHookWords(expected.command);
|
|
709
|
+
return a.length === b.length && a.every((v, i) => sameHookWord(v, b[i]));
|
|
710
|
+
}
|
|
711
|
+
function claudeHookScriptPath() {
|
|
712
|
+
return path2.join(claudeConfigDir(), "hooks", SHIM_FILE);
|
|
713
|
+
}
|
|
714
|
+
function claudeLegacyHookScriptPath() {
|
|
715
|
+
return path2.join(claudeConfigDir(), "hooks", LEGACY_SHIM_FILE);
|
|
716
|
+
}
|
|
717
|
+
function anyScopeReferencesShim(scriptPaths, currentScope, alreadyStripped) {
|
|
718
|
+
const referencesIn = (map) => {
|
|
719
|
+
for (const groups of Object.values(map ?? {})) {
|
|
720
|
+
for (const group of Array.isArray(groups) ? groups : []) {
|
|
721
|
+
for (const h of hooksOf(group)) {
|
|
722
|
+
const fields = commandHookFields(h);
|
|
723
|
+
if (fields !== void 0 && scriptPaths.some((p) => fields.command.includes(p) || (fields.args ?? []).some((a) => a.includes(p)))) return true;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
return false;
|
|
728
|
+
};
|
|
729
|
+
if (referencesIn(alreadyStripped)) return true;
|
|
730
|
+
for (const scope of ["user", "project"]) {
|
|
731
|
+
if (scope === currentScope) continue;
|
|
732
|
+
let other;
|
|
733
|
+
try {
|
|
734
|
+
other = readSettings(settingsPath(scope), { strict: true });
|
|
735
|
+
} catch (e) {
|
|
736
|
+
if (e instanceof SettingsParseError) return true;
|
|
737
|
+
throw e;
|
|
738
|
+
}
|
|
739
|
+
if (referencesIn(other.hooks)) return true;
|
|
740
|
+
}
|
|
741
|
+
return false;
|
|
742
|
+
}
|
|
743
|
+
function settingsPath(scope) {
|
|
744
|
+
const base = scope === "user" ? claudeConfigDir() : path2.join(normalizeDarwinSystemAlias(process.cwd()), ".claude");
|
|
745
|
+
return path2.join(base, "settings.json");
|
|
746
|
+
}
|
|
747
|
+
var SettingsParseError = class extends Error {
|
|
748
|
+
};
|
|
749
|
+
function readSettings(p, opts = {}) {
|
|
750
|
+
const refuse = (problem, detail) => new SettingsParseError(
|
|
751
|
+
(opts.command === "uninstall" ? `settings file '${p}' is unreadable: it ${problem}. Uninstall left it untouched, along with the hook shim it may still name and the file's backups; fix the file and run uninstall again.` : `settings file '${p}' ${problem}. Fix or back up the file before running install.`) + (detail === void 0 ? "" : ` (${detail})`)
|
|
752
|
+
);
|
|
753
|
+
let raw;
|
|
754
|
+
try {
|
|
755
|
+
raw = fs2.readFileSync(p, "utf8");
|
|
756
|
+
} catch (e) {
|
|
757
|
+
const code = e.code;
|
|
758
|
+
if (opts.strict === true && code !== "ENOENT" && code !== "ENOTDIR") throw refuse("exists but cannot be read", code ?? extractErrorMessage(e));
|
|
759
|
+
return {};
|
|
760
|
+
}
|
|
761
|
+
let parsed;
|
|
762
|
+
try {
|
|
763
|
+
parsed = JSON.parse(stripBom(raw));
|
|
764
|
+
} catch {
|
|
765
|
+
if (opts.strict === true) throw refuse("exists but contains invalid JSON");
|
|
766
|
+
return {};
|
|
767
|
+
}
|
|
768
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
769
|
+
const hooksValue = parsed.hooks;
|
|
770
|
+
if (hooksValue === void 0 || typeof hooksValue === "object" && hooksValue !== null && !Array.isArray(hooksValue)) return parsed;
|
|
771
|
+
if (opts.strict === true) throw refuse('has a "hooks" value that is not a JSON object');
|
|
772
|
+
const { hooks: _ignored, ...rest } = parsed;
|
|
773
|
+
return rest;
|
|
774
|
+
}
|
|
775
|
+
if (opts.strict === true) throw refuse("does not contain a JSON object at the top level");
|
|
776
|
+
return {};
|
|
777
|
+
}
|
|
778
|
+
function wiredClaudeHookWords(scope) {
|
|
779
|
+
const out = [];
|
|
780
|
+
for (const groups of Object.values(readSettings(settingsPath(scope)).hooks ?? {})) {
|
|
781
|
+
for (const g of Array.isArray(groups) ? groups : []) {
|
|
782
|
+
for (const h of Array.isArray(g?.hooks) ? g.hooks : []) {
|
|
783
|
+
const fields = commandHookFields(h);
|
|
784
|
+
if (fields === void 0 || !isTokenGoatHookCommand(fields.command, fields.args)) continue;
|
|
785
|
+
out.push(fields.args !== void 0 && fields.args.length > 0 ? [fields.command, ...fields.args] : stringFormHookWords(fields.command));
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
return out;
|
|
790
|
+
}
|
|
791
|
+
function hooksOf(group) {
|
|
792
|
+
return Array.isArray(group?.hooks) ? group.hooks : [];
|
|
793
|
+
}
|
|
794
|
+
function groupHasTokenGoat(groups, predicate) {
|
|
795
|
+
if (!Array.isArray(groups)) return false;
|
|
796
|
+
for (const group of groups) {
|
|
797
|
+
for (const h of hooksOf(group)) {
|
|
798
|
+
if (isOwnHookEntry(h, predicate)) return true;
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
return false;
|
|
802
|
+
}
|
|
803
|
+
function installHooks(scope = "user") {
|
|
804
|
+
return withInstallScope(hookScopeRoot(scope), () => installHooksScoped(scope));
|
|
805
|
+
}
|
|
806
|
+
function hookScopeRoot(scope) {
|
|
807
|
+
return scope === "project" ? normalizeDarwinSystemAlias(process.cwd()) : void 0;
|
|
808
|
+
}
|
|
809
|
+
function installHooksScoped(scope) {
|
|
810
|
+
const p = settingsPath(scope);
|
|
811
|
+
const settings = readSettings(p, { strict: true });
|
|
812
|
+
const hooks = settings.hooks ?? {};
|
|
813
|
+
const scriptPath = claudeHookScriptPath();
|
|
814
|
+
const scriptChanged = withInstallScope(void 0, () => {
|
|
815
|
+
ensureDirRecordingCreation(path2.dirname(scriptPath));
|
|
816
|
+
const forwarderChanged = writeIfDifferent(claudeLegacyHookScriptPath(), legacyShimForwarder("{}"));
|
|
817
|
+
const scriptChanged2 = writeIfDifferent(scriptPath, CLAUDECODE_HOOK_SCRIPT);
|
|
818
|
+
return scriptChanged2 || forwarderChanged;
|
|
819
|
+
});
|
|
820
|
+
let settingsChanged = false;
|
|
821
|
+
const skippedEvents = [];
|
|
822
|
+
for (const [eventKey, eventArg] of HOOK_EVENT_MAP) {
|
|
823
|
+
const expected = expectedHookEntryFor(scriptPath, eventArg);
|
|
824
|
+
const rawGroups = hooks[eventKey];
|
|
825
|
+
if (rawGroups !== void 0 && !Array.isArray(rawGroups)) {
|
|
826
|
+
skippedEvents.push(eventKey);
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
const existingGroups = rawGroups ?? [];
|
|
830
|
+
const groups = [];
|
|
831
|
+
let strippedStale = false;
|
|
832
|
+
for (const group of existingGroups) {
|
|
833
|
+
if (typeof group !== "object" || group === null) {
|
|
834
|
+
groups.push(group);
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
const keptHooks = hooksOf(group).filter((h) => {
|
|
838
|
+
const isStale = isOwnHookEntry(h, (command, args) => isTokenGoatHookCommand(command, args) && !hookEntryMatches(command, args, expected));
|
|
839
|
+
if (isStale) strippedStale = true;
|
|
840
|
+
return !isStale;
|
|
841
|
+
});
|
|
842
|
+
if (keptHooks.length > 0) {
|
|
843
|
+
groups.push({ ...group, hooks: keptHooks });
|
|
844
|
+
} else if (hooksOf(group).length === 0) {
|
|
845
|
+
groups.push(group);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
const isOurs = (command, args) => hookEntryMatches(command, args, expected);
|
|
849
|
+
if (groupHasTokenGoat(groups, isOurs)) {
|
|
850
|
+
const narrowed = toolMatcherFor(eventArg);
|
|
851
|
+
let renarrowed = false;
|
|
852
|
+
if (narrowed !== null) {
|
|
853
|
+
for (let i = 0; i < groups.length; i++) {
|
|
854
|
+
const group = groups[i];
|
|
855
|
+
if (group === void 0) continue;
|
|
856
|
+
const ownHooks = hooksOf(group);
|
|
857
|
+
const isOwnGroup = ownHooks.length > 0 && ownHooks.every((h) => isOwnHookEntry(h, isOurs));
|
|
858
|
+
if (isOwnGroup && group.matcher !== narrowed) {
|
|
859
|
+
groups[i] = { ...group, matcher: narrowed };
|
|
860
|
+
renarrowed = true;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
if (strippedStale || renarrowed) {
|
|
865
|
+
hooks[eventKey] = groups;
|
|
866
|
+
settingsChanged = true;
|
|
867
|
+
}
|
|
868
|
+
continue;
|
|
869
|
+
}
|
|
870
|
+
const matcher = toolMatcherFor(eventArg) ?? "";
|
|
871
|
+
groups.push({ matcher, hooks: [{ type: "command", command: expected.command, ...expected.args !== void 0 ? { args: expected.args } : {} }] });
|
|
872
|
+
hooks[eventKey] = groups;
|
|
873
|
+
settingsChanged = true;
|
|
874
|
+
}
|
|
875
|
+
if (skippedEvents.length > 0) {
|
|
876
|
+
process.stderr.write(`token-goat: left ${p} untouched under hooks.${skippedEvents.join(", hooks.")}: not a list of hook groups, so no token-goat hook was added there. Fix the value and run install again.
|
|
877
|
+
`);
|
|
878
|
+
}
|
|
879
|
+
if (!settingsChanged && !scriptChanged) {
|
|
880
|
+
return { scope, settingsPath: p, alreadyInstalled: true, ...skippedEvents.length > 0 ? { skippedEvents } : {} };
|
|
881
|
+
}
|
|
882
|
+
if (settingsChanged) {
|
|
883
|
+
settings.hooks = hooks;
|
|
884
|
+
recordCreatedBy([p], () => writeJsonSettings(p, settings));
|
|
885
|
+
}
|
|
886
|
+
return { scope, settingsPath: p, alreadyInstalled: false, ...skippedEvents.length > 0 ? { skippedEvents } : {} };
|
|
887
|
+
}
|
|
888
|
+
function uninstallHooks(scope = "user") {
|
|
889
|
+
return withInstallScope(hookScopeRoot(scope), () => uninstallHooksScoped(scope));
|
|
890
|
+
}
|
|
891
|
+
function uninstallHooksScoped(scope) {
|
|
892
|
+
const p = settingsPath(scope);
|
|
893
|
+
const settings = readSettings(p, { strict: true, command: "uninstall" });
|
|
894
|
+
const hooks = settings.hooks ?? {};
|
|
895
|
+
const removed = stripOwnHooksFromMap(hooks, isTokenGoatHookCommand);
|
|
896
|
+
const scriptPath = claudeHookScriptPath();
|
|
897
|
+
let removedScript = false;
|
|
898
|
+
if (!anyScopeReferencesShim([scriptPath, claudeLegacyHookScriptPath()], scope, hooks)) {
|
|
899
|
+
removedScript = withInstallScope(void 0, () => {
|
|
900
|
+
const removedAny = [scriptPath, claudeLegacyHookScriptPath()].map((p2) => removeFileInScope(p2)).some(Boolean);
|
|
901
|
+
removeCreatedIfEmpty(path2.dirname(scriptPath));
|
|
902
|
+
return removedAny;
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
const result = finishHookUninstall(p, settings, removed) || removedScript;
|
|
906
|
+
removeCreatedTree([p]);
|
|
907
|
+
return result;
|
|
908
|
+
}
|
|
909
|
+
function finishHookUninstall(p, settings, removed, write = writeJsonSettings) {
|
|
910
|
+
if (removed) {
|
|
911
|
+
if (settings.hooks !== void 0 && Object.keys(settings.hooks).length === 0) delete settings.hooks;
|
|
912
|
+
write(p, settings);
|
|
913
|
+
}
|
|
914
|
+
removeCreatedBackups(p);
|
|
915
|
+
return removed;
|
|
916
|
+
}
|
|
917
|
+
function isInstalled(scope = "user") {
|
|
918
|
+
if (!fs2.existsSync(claudeHookScriptPath())) return false;
|
|
919
|
+
const gaps = hookEventGaps(scope);
|
|
920
|
+
return gaps !== null && gaps.missing.length === 0 && gaps.outdated.length === 0 && gaps.broken.length === 0;
|
|
921
|
+
}
|
|
922
|
+
var LIVE_HOOK_MARKER_PATTERNS = [SHIM_COMMAND_MARKER, COMMAND_MARKER].map(anchoredMarkerPattern);
|
|
923
|
+
var SHIM_FILE_WORD = /(?:^|[\\/])token-goat-shim\.c?js$/;
|
|
924
|
+
function isLiveTokenGoatHookCommand(command, args) {
|
|
925
|
+
const execForm = args !== void 0 && args.length > 0;
|
|
926
|
+
const haystack = execForm ? `${command} ${args.join(" ")}` : command;
|
|
927
|
+
if (!LIVE_HOOK_MARKER_PATTERNS.some((pattern) => pattern.test(haystack))) return false;
|
|
928
|
+
const words = execForm ? [command, ...args] : stringFormHookWords(command);
|
|
929
|
+
const native = parseNativeInvocation(words);
|
|
930
|
+
if (native !== void 0 && !fs2.existsSync(native.bin)) return false;
|
|
931
|
+
const shimFile = words.find((word) => SHIM_FILE_WORD.test(word));
|
|
932
|
+
return shimFile === void 0 || fs2.existsSync(shimFile);
|
|
933
|
+
}
|
|
934
|
+
function isBrokenNativeHookCommand(command, args) {
|
|
935
|
+
const words = args !== void 0 && args.length > 0 ? [command, ...args] : stringFormHookWords(command);
|
|
936
|
+
const native = parseNativeInvocation(words);
|
|
937
|
+
return native !== void 0 && native.wrapped.some((word) => SHIM_FILE_WORD.test(word)) && !fs2.existsSync(native.bin);
|
|
938
|
+
}
|
|
939
|
+
function hookEventGaps(scope = "user") {
|
|
940
|
+
const hooks = readSettings(settingsPath(scope)).hooks;
|
|
941
|
+
if (hooks === void 0) return null;
|
|
942
|
+
if (!HOOK_EVENT_MAP.some(([eventKey]) => groupHasTokenGoat(hooks[eventKey], isTokenGoatHookCommand))) return null;
|
|
943
|
+
const scriptPath = claudeHookScriptPath();
|
|
944
|
+
const missing = [];
|
|
945
|
+
const outdated = [];
|
|
946
|
+
const broken = [];
|
|
947
|
+
for (const [eventKey, eventArg] of HOOK_EVENT_MAP) {
|
|
948
|
+
const expected = expectedHookEntryFor(scriptPath, eventArg, { sync: false });
|
|
949
|
+
if (groupHasTokenGoat(hooks[eventKey], (c, a) => hookEntryMatches(c, a, expected))) continue;
|
|
950
|
+
if (groupHasTokenGoat(hooks[eventKey], isLiveTokenGoatHookCommand)) outdated.push(eventKey);
|
|
951
|
+
else if (groupHasTokenGoat(hooks[eventKey], isBrokenNativeHookCommand)) broken.push(eventKey);
|
|
952
|
+
else missing.push(eventKey);
|
|
953
|
+
}
|
|
954
|
+
return { missing, outdated, broken };
|
|
955
|
+
}
|
|
956
|
+
var CLAUDE_MD_BEGIN = "<!-- token-goat-begin -->";
|
|
957
|
+
var CLAUDE_MD_END = "<!-- token-goat-end -->";
|
|
958
|
+
function claudeMdPath(scope = "user") {
|
|
959
|
+
return scope === "user" ? path2.join(claudeConfigDir(), "CLAUDE.md") : path2.join(normalizeDarwinSystemAlias(process.cwd()), "CLAUDE.md");
|
|
960
|
+
}
|
|
961
|
+
function buildClaudeMdBlock() {
|
|
962
|
+
return buildGuidanceBlock({
|
|
963
|
+
beginMarker: CLAUDE_MD_BEGIN,
|
|
964
|
+
endMarker: CLAUDE_MD_END,
|
|
965
|
+
fallbackToolClause: "Claude Code's own Read, Grep, and Glob preference rules",
|
|
966
|
+
gdrive: loadConfig().gdrive.enabled
|
|
967
|
+
});
|
|
968
|
+
}
|
|
969
|
+
function writeClaudeMdBlock(p) {
|
|
970
|
+
return upsertDelimitedBlock(p, CLAUDE_MD_BEGIN, CLAUDE_MD_END, buildClaudeMdBlock());
|
|
971
|
+
}
|
|
972
|
+
function stripClaudeMdBlock(p) {
|
|
973
|
+
return stripDelimitedBlock(p, CLAUDE_MD_BEGIN, CLAUDE_MD_END);
|
|
974
|
+
}
|
|
975
|
+
function installedClaudeMdBlock() {
|
|
976
|
+
let text;
|
|
977
|
+
try {
|
|
978
|
+
text = fs2.readFileSync(claudeMdPath(), "utf8");
|
|
979
|
+
} catch {
|
|
980
|
+
return null;
|
|
981
|
+
}
|
|
982
|
+
const begin = text.indexOf(CLAUDE_MD_BEGIN);
|
|
983
|
+
if (begin === -1) return null;
|
|
984
|
+
const end = text.indexOf(CLAUDE_MD_END, begin + CLAUDE_MD_BEGIN.length);
|
|
985
|
+
return end === -1 ? null : text.slice(begin, end + CLAUDE_MD_END.length);
|
|
986
|
+
}
|
|
987
|
+
function installClaudeMd(scope = "user") {
|
|
988
|
+
return withInstallScope(hookScopeRoot(scope), () => {
|
|
989
|
+
const p = claudeMdPath(scope);
|
|
990
|
+
const existed = fs2.existsSync(p);
|
|
991
|
+
const changed = writeClaudeMdBlock(p);
|
|
992
|
+
if (!existed) recordCreatedConfig(p);
|
|
993
|
+
return { path: p, alreadyInstalled: !changed };
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
function uninstallClaudeMd(scope = "user") {
|
|
997
|
+
return withInstallScope(hookScopeRoot(scope), () => {
|
|
998
|
+
const p = claudeMdPath(scope);
|
|
999
|
+
const stripped = stripClaudeMdBlock(p);
|
|
1000
|
+
removeCreatedIfEmpty(p);
|
|
1001
|
+
return stripped;
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
function findStrayClaudeMdBlocks(searchRoot) {
|
|
1005
|
+
const root = searchRoot ?? claudeConfigDir();
|
|
1006
|
+
const canonical = path2.resolve(claudeMdPath());
|
|
1007
|
+
const found = [];
|
|
1008
|
+
if (!fs2.existsSync(root)) return found;
|
|
1009
|
+
const SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
|
|
1010
|
+
const MAX_DEPTH = 6;
|
|
1011
|
+
const hasRealBlock = (text) => {
|
|
1012
|
+
let sawBegin = false;
|
|
1013
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1014
|
+
const trimmed = line.trim();
|
|
1015
|
+
if (trimmed === CLAUDE_MD_BEGIN) sawBegin = true;
|
|
1016
|
+
else if (sawBegin && trimmed === CLAUDE_MD_END) return true;
|
|
1017
|
+
}
|
|
1018
|
+
return false;
|
|
1019
|
+
};
|
|
1020
|
+
const walk = (dir, depth) => {
|
|
1021
|
+
if (depth > MAX_DEPTH) return;
|
|
1022
|
+
let entries;
|
|
1023
|
+
try {
|
|
1024
|
+
entries = fs2.readdirSync(dir, { withFileTypes: true });
|
|
1025
|
+
} catch {
|
|
1026
|
+
return;
|
|
1027
|
+
}
|
|
1028
|
+
for (const entry of entries) {
|
|
1029
|
+
const full = path2.join(dir, entry.name);
|
|
1030
|
+
if (entry.isDirectory()) {
|
|
1031
|
+
if (!SKIP_DIRS.has(entry.name)) walk(full, depth + 1);
|
|
1032
|
+
continue;
|
|
1033
|
+
}
|
|
1034
|
+
if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) continue;
|
|
1035
|
+
if (path2.resolve(full) === canonical) continue;
|
|
1036
|
+
let text;
|
|
1037
|
+
try {
|
|
1038
|
+
text = fs2.readFileSync(full, "utf8");
|
|
1039
|
+
} catch {
|
|
1040
|
+
continue;
|
|
1041
|
+
}
|
|
1042
|
+
if (hasRealBlock(text)) found.push(full);
|
|
1043
|
+
}
|
|
1044
|
+
};
|
|
1045
|
+
walk(root, 0);
|
|
1046
|
+
return found.sort();
|
|
1047
|
+
}
|
|
1048
|
+
function skillMdContent() {
|
|
1049
|
+
return CANONICAL_SKILL_MD;
|
|
1050
|
+
}
|
|
1051
|
+
function skillDir(scope = "user") {
|
|
1052
|
+
return path2.join(scope === "user" ? claudeConfigDir() : path2.join(normalizeDarwinSystemAlias(process.cwd()), ".claude"), "skills", "token-goat");
|
|
1053
|
+
}
|
|
1054
|
+
function skillPath(scope = "user") {
|
|
1055
|
+
return path2.join(skillDir(scope), "SKILL.md");
|
|
1056
|
+
}
|
|
1057
|
+
function installedSkillDescription() {
|
|
1058
|
+
let text;
|
|
1059
|
+
try {
|
|
1060
|
+
text = fs2.readFileSync(skillPath(), "utf8");
|
|
1061
|
+
} catch {
|
|
1062
|
+
return null;
|
|
1063
|
+
}
|
|
1064
|
+
const lines = text.split(/\r?\n/);
|
|
1065
|
+
if (lines[0] !== "---") return null;
|
|
1066
|
+
for (const line of lines.slice(1)) {
|
|
1067
|
+
if (line === "---") return null;
|
|
1068
|
+
if (line.startsWith("description:")) return line;
|
|
1069
|
+
}
|
|
1070
|
+
return null;
|
|
1071
|
+
}
|
|
1072
|
+
function installSkill(scope = "user") {
|
|
1073
|
+
return withInstallScope(hookScopeRoot(scope), () => installSkillScoped(scope));
|
|
1074
|
+
}
|
|
1075
|
+
function installSkillScoped(scope) {
|
|
1076
|
+
const p = skillPath(scope);
|
|
1077
|
+
let existing = null;
|
|
1078
|
+
try {
|
|
1079
|
+
existing = fs2.readFileSync(p, "utf8");
|
|
1080
|
+
} catch {
|
|
1081
|
+
}
|
|
1082
|
+
const skillContent = skillMdContent();
|
|
1083
|
+
if (existing === skillContent) return { path: p, alreadyInstalled: true };
|
|
1084
|
+
recordCreatedBy([skillDir(scope)], () => ensureDirSync(skillDir(scope)));
|
|
1085
|
+
backupFile(p);
|
|
1086
|
+
atomicWriteText(p, skillContent);
|
|
1087
|
+
return { path: p, alreadyInstalled: false };
|
|
1088
|
+
}
|
|
1089
|
+
function uninstallSkill(scope = "user") {
|
|
1090
|
+
return withInstallScope(hookScopeRoot(scope), () => uninstallSkillScoped(scope));
|
|
1091
|
+
}
|
|
1092
|
+
function uninstallSkillScoped(scope) {
|
|
1093
|
+
const dir = skillDir(scope);
|
|
1094
|
+
const present = fs2.existsSync(dir);
|
|
1095
|
+
if (present) {
|
|
1096
|
+
removeCreatedBackups(skillPath(scope));
|
|
1097
|
+
assertWriteInScope(dir);
|
|
1098
|
+
fs2.rmSync(dir, { recursive: true, force: true });
|
|
1099
|
+
}
|
|
1100
|
+
removeCreatedTree([dir]);
|
|
1101
|
+
return present;
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
// src/bridges/codex.ts
|
|
1105
|
+
init_define_import_meta_env();
|
|
1106
|
+
var CODEX_HOOK_SCRIPT = `#!/usr/bin/env node
|
|
1107
|
+
// token-goat Codex hook shim. Forwards the hook payload to \`token-goat hook <event>\`, then strips _tg_* keys and injects hookEventName so the response satisfies Codex's strict (additionalProperties:false) schema.
|
|
1108
|
+
'use strict'
|
|
1109
|
+
${SHIM_REQUIRES}
|
|
1110
|
+
|
|
1111
|
+
${SHIM_VALID_HOOK_EVENTS}
|
|
1112
|
+
|
|
1113
|
+
// Codex sets no env var of its own identifying a hook subprocess; see this module's docblock.
|
|
1114
|
+
process.env.TOKEN_GOAT_HARNESS_OVERRIDE = 'codex'
|
|
1115
|
+
|
|
1116
|
+
// Keep in sync with CLAUDE_CODE_EVENT_NAMES in src/hook_registry.ts -- the
|
|
1117
|
+
// live/wired 'token-goat hook <event>' path (src/relay.ts) always emits this
|
|
1118
|
+
// PascalCase spelling for hookSpecificOutput.hookEventName, never the raw
|
|
1119
|
+
// snake_case event name.
|
|
1120
|
+
const HOOK_EVENT_NAME_MAP = {
|
|
1121
|
+
pre_tool_use: 'PreToolUse',
|
|
1122
|
+
post_tool_use: 'PostToolUse',
|
|
1123
|
+
notification: 'Notification',
|
|
1124
|
+
stop: 'Stop',
|
|
1125
|
+
pre_compact: 'PreCompact',
|
|
1126
|
+
post_compact: 'PostCompact',
|
|
1127
|
+
user_prompt_submit: 'UserPromptSubmit',
|
|
1128
|
+
subagent_stop: 'SubagentStop',
|
|
1129
|
+
subagent_start: 'SubagentStart',
|
|
1130
|
+
session_start: 'SessionStart',
|
|
1131
|
+
post_tool_use_failure: 'PostToolUseFailure',
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
function stripTg(value) {
|
|
1135
|
+
if (Array.isArray(value)) return value.map(stripTg)
|
|
1136
|
+
if (value && typeof value === 'object') {
|
|
1137
|
+
const out = {}
|
|
1138
|
+
for (const [k, v] of Object.entries(value)) {
|
|
1139
|
+
if (k.startsWith('_tg_')) continue
|
|
1140
|
+
out[k] = stripTg(v)
|
|
1141
|
+
}
|
|
1142
|
+
return out
|
|
1143
|
+
}
|
|
1144
|
+
return value
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
${SHIM_TRY_SERVER}
|
|
1148
|
+
|
|
1149
|
+
${SHIM_TRY_IN_PROCESS}
|
|
1150
|
+
|
|
1151
|
+
${SHIM_MAX_BUFFER_CONST}
|
|
1152
|
+
|
|
1153
|
+
async function main() {
|
|
1154
|
+
const eventName = process.argv[2] || ''
|
|
1155
|
+
if (!VALID_HOOK_EVENTS.has(eventName)) {
|
|
1156
|
+
process.stdout.write('{}')
|
|
1157
|
+
return
|
|
1158
|
+
}
|
|
1159
|
+
let input = ''
|
|
1160
|
+
try {
|
|
1161
|
+
input = require('node:fs').readFileSync(0, 'utf8')
|
|
1162
|
+
} catch {
|
|
1163
|
+
process.stdout.write('{}')
|
|
1164
|
+
return
|
|
1165
|
+
}
|
|
1166
|
+
// process.argv[3], when present, is the absolute path to the token-goat CLI entry
|
|
1167
|
+
// that ran 'token-goat install --codex' (baked in by hookCommandFor in
|
|
1168
|
+
// codex_install.ts). Try the in-process hook lib first (tryInProcess above) --
|
|
1169
|
+
// this avoids spawning a second node process altogether. If that's unavailable,
|
|
1170
|
+
// invoking the entry directly via process.execPath sidesteps PATH/shell resolution
|
|
1171
|
+
// for this inner call, the same single-point-of-failure class fixed for the Copilot
|
|
1172
|
+
// CLI bridge's inner hook call (a bare 'token-goat' on PATH failing to resolve
|
|
1173
|
+
// crashes this call, and Codex -- like Copilot -- fails closed on a non-zero-exit
|
|
1174
|
+
// hook). Falls back further to the old PATH-based shell:true invocation when argv[3]
|
|
1175
|
+
// is absent (an older cached hook config). A 3000ms timeout/killSignal on both
|
|
1176
|
+
// spawnSync fallbacks bounds them well under Codex's own hook timeout budget, so
|
|
1177
|
+
// token-goat degrades to its own fail-open '{}' rather than being force-killed by
|
|
1178
|
+
// Codex first.
|
|
1179
|
+
const entryPath = process.argv[3]
|
|
1180
|
+
let stdout = await tryInProcess(entryPath, eventName, input)
|
|
1181
|
+
if (stdout === undefined) {
|
|
1182
|
+
${SHIM_SPAWN_LADDER}
|
|
1183
|
+
: spawnSync('token-goat hook ' + eventName, {
|
|
1184
|
+
input,
|
|
1185
|
+
encoding: 'utf8',
|
|
1186
|
+
shell: true,
|
|
1187
|
+
timeout: 3000,
|
|
1188
|
+
killSignal: 'SIGKILL',
|
|
1189
|
+
maxBuffer: SHIM_MAX_BUFFER_BYTES,
|
|
1190
|
+
})
|
|
1191
|
+
if (res.status !== 0 || !res.stdout) {
|
|
1192
|
+
process.stdout.write('{}')
|
|
1193
|
+
return
|
|
1194
|
+
}
|
|
1195
|
+
stdout = res.stdout
|
|
1196
|
+
}
|
|
1197
|
+
let parsed
|
|
1198
|
+
try {
|
|
1199
|
+
parsed = JSON.parse(stdout)
|
|
1200
|
+
} catch {
|
|
1201
|
+
process.stdout.write('{}')
|
|
1202
|
+
return
|
|
1203
|
+
}
|
|
1204
|
+
parsed = stripTg(parsed)
|
|
1205
|
+
const hso = parsed && parsed.hookSpecificOutput
|
|
1206
|
+
if (hso && typeof hso === 'object' && !hso.hookEventName) {
|
|
1207
|
+
hso.hookEventName = HOOK_EVENT_NAME_MAP[eventName] || eventName
|
|
1208
|
+
}
|
|
1209
|
+
process.stdout.write(JSON.stringify(parsed))
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
main().catch(() => {
|
|
1213
|
+
process.stdout.write('{}')
|
|
1214
|
+
})
|
|
1215
|
+
`;
|
|
1216
|
+
|
|
1217
|
+
// src/bridges/codex_install.ts
|
|
1218
|
+
init_define_import_meta_env();
|
|
1219
|
+
import * as crypto2 from "node:crypto";
|
|
1220
|
+
import * as fs3 from "node:fs";
|
|
1221
|
+
import * as os from "node:os";
|
|
1222
|
+
import * as path3 from "node:path";
|
|
1223
|
+
|
|
1224
|
+
// src/bridges/matcher_group.ts
|
|
1225
|
+
init_define_import_meta_env();
|
|
1226
|
+
function findTokenGoatEntryPosition(groups, matcher, predicate) {
|
|
1227
|
+
if (groups === void 0) return void 0;
|
|
1228
|
+
for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
|
|
1229
|
+
const group = groups[groupIndex];
|
|
1230
|
+
if (group.matcher !== matcher) continue;
|
|
1231
|
+
const hookList = group.hooks ?? [];
|
|
1232
|
+
for (let hookIndex = 0; hookIndex < hookList.length; hookIndex++) {
|
|
1233
|
+
if (predicate(hookList[hookIndex].command)) return { groupIndex, hookIndex };
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
return void 0;
|
|
1237
|
+
}
|
|
1238
|
+
function findAnyTokenGoatEntryPosition(groups, predicate) {
|
|
1239
|
+
if (groups === void 0) return void 0;
|
|
1240
|
+
for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
|
|
1241
|
+
const hookList = groups[groupIndex].hooks ?? [];
|
|
1242
|
+
for (let hookIndex = 0; hookIndex < hookList.length; hookIndex++) {
|
|
1243
|
+
if (predicate(hookList[hookIndex].command)) return { groupIndex, hookIndex };
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
return void 0;
|
|
1247
|
+
}
|
|
1248
|
+
function groupHasTokenGoat2(groups, matcher, predicate) {
|
|
1249
|
+
return findTokenGoatEntryPosition(groups, matcher, predicate) !== void 0;
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
// src/bridges/codex_install.ts
|
|
1253
|
+
var CODEX_COMMAND_MARKER = "token-goat-shim";
|
|
1254
|
+
var CODEX_MATCHERS = ["view_image|Bash|exec|shell|bash", "apply_patch", "web_search"];
|
|
1255
|
+
var CODEX_HOOK_EVENTS = ["PreToolUse", "PostToolUse"];
|
|
1256
|
+
var CODEX_EVENT_ARG = {
|
|
1257
|
+
PreToolUse: "pre_tool_use",
|
|
1258
|
+
PostToolUse: "post_tool_use"
|
|
1259
|
+
};
|
|
1260
|
+
var CODEX_GLOBAL_HOOK_EVENTS = ["PreCompact", "UserPromptSubmit", "SubagentStop"];
|
|
1261
|
+
var CODEX_GLOBAL_EVENT_ARG = {
|
|
1262
|
+
PreCompact: "pre_compact",
|
|
1263
|
+
UserPromptSubmit: "user_prompt_submit",
|
|
1264
|
+
SubagentStop: "subagent_stop"
|
|
1265
|
+
};
|
|
1266
|
+
var CodexConfigParseError = class extends Error {
|
|
1267
|
+
};
|
|
1268
|
+
function codexConfigPath() {
|
|
1269
|
+
return path3.join(os.homedir(), ".codex", "config.toml");
|
|
1270
|
+
}
|
|
1271
|
+
function codexAgentsPath() {
|
|
1272
|
+
return path3.join(os.homedir(), ".codex", "AGENTS.md");
|
|
1273
|
+
}
|
|
1274
|
+
function codexHookScriptPath() {
|
|
1275
|
+
return path3.join(os.homedir(), ".codex", "hooks", SHIM_FILE);
|
|
1276
|
+
}
|
|
1277
|
+
function codexLegacyHookScriptPath() {
|
|
1278
|
+
return path3.join(os.homedir(), ".codex", "hooks", LEGACY_SHIM_FILE);
|
|
1279
|
+
}
|
|
1280
|
+
function readCodexConfig(p, opts = {}) {
|
|
1281
|
+
const refuse = (problem, detail) => new CodexConfigParseError(
|
|
1282
|
+
(opts.command === "uninstall" ? `Codex config file '${p}' is unreadable: it ${problem}. Uninstall left it untouched, along with the hook shim it may still name, the AGENTS.md block and the file's backups; fix the file and run uninstall again.` : `Codex config file '${p}' ${problem}. Fix or back up the file before running install.`) + (detail === void 0 ? "" : ` (${detail})`)
|
|
1283
|
+
);
|
|
1284
|
+
let raw;
|
|
1285
|
+
try {
|
|
1286
|
+
raw = fs3.readFileSync(p, "utf8");
|
|
1287
|
+
} catch (e) {
|
|
1288
|
+
const code = e.code;
|
|
1289
|
+
if (opts.strict === true && code !== "ENOENT" && code !== "ENOTDIR") throw refuse("exists but cannot be read", code ?? extractErrorMessage(e));
|
|
1290
|
+
return {};
|
|
1291
|
+
}
|
|
1292
|
+
try {
|
|
1293
|
+
const parsed = parse(raw);
|
|
1294
|
+
return parsed;
|
|
1295
|
+
} catch (e) {
|
|
1296
|
+
if (opts.strict === true) throw refuse("exists but contains invalid TOML", extractErrorMessage(e));
|
|
1297
|
+
return {};
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
var CODEX_MARKER_PATTERN = anchoredMarkerPattern(CODEX_COMMAND_MARKER);
|
|
1301
|
+
function isCodexTokenGoatCommand(command) {
|
|
1302
|
+
return typeof command === "string" && CODEX_MARKER_PATTERN.test(command);
|
|
1303
|
+
}
|
|
1304
|
+
function anyGroupHasTokenGoat(groups, predicate = isCodexTokenGoatCommand) {
|
|
1305
|
+
return findAnyTokenGoatEntryPosition(groups, predicate) !== void 0;
|
|
1306
|
+
}
|
|
1307
|
+
function codexHookCommandFor(scriptPath, eventArg, opts = {}) {
|
|
1308
|
+
const bin = nativeHookBinary(process.argv[1], opts);
|
|
1309
|
+
const native = bin === void 0 ? void 0 : nativeHookCommandLine(process.platform === "win32" ? "powershell" : "sh", bin, "codex", scriptPath, eventArg);
|
|
1310
|
+
if (native !== void 0) return native;
|
|
1311
|
+
return process.platform === "win32" ? powershellHookLine(hookPowershellCommand(scriptPath, eventArg)) : hookCommandFor(scriptPath, eventArg);
|
|
1312
|
+
}
|
|
1313
|
+
function computeCodexHookHash(eventArg, command, matcher) {
|
|
1314
|
+
const norm = {
|
|
1315
|
+
event_name: eventArg,
|
|
1316
|
+
hooks: [
|
|
1317
|
+
{
|
|
1318
|
+
async: false,
|
|
1319
|
+
command,
|
|
1320
|
+
timeout: 600,
|
|
1321
|
+
type: "command"
|
|
1322
|
+
}
|
|
1323
|
+
]
|
|
1324
|
+
};
|
|
1325
|
+
if (matcher !== void 0) {
|
|
1326
|
+
norm["matcher"] = matcher;
|
|
1327
|
+
}
|
|
1328
|
+
const serialized = JSON.stringify(norm);
|
|
1329
|
+
const hash = crypto2.createHash("sha256").update(serialized).digest("hex");
|
|
1330
|
+
return `sha256:${hash}`;
|
|
1331
|
+
}
|
|
1332
|
+
var MANAGED_BEGIN = "# >>> token-goat codex hooks (managed block; token-goat uninstall removes it) >>>";
|
|
1333
|
+
var MANAGED_BEGIN_NO_EOL = "# >>> token-goat codex hooks (managed block; token-goat uninstall removes it; file had no final newline) >>>";
|
|
1334
|
+
var MANAGED_END = "# <<< token-goat codex hooks <<<";
|
|
1335
|
+
function removeManagedBlock(text) {
|
|
1336
|
+
for (const begin of [MANAGED_BEGIN_NO_EOL, MANAGED_BEGIN]) {
|
|
1337
|
+
const start = text.indexOf(begin);
|
|
1338
|
+
if (start < 0 || start > 0 && text[start - 1] !== "\n") continue;
|
|
1339
|
+
const endMark = text.indexOf(MANAGED_END, start);
|
|
1340
|
+
if (endMark < 0) return void 0;
|
|
1341
|
+
const nl = text.indexOf("\n", endMark);
|
|
1342
|
+
const end = nl < 0 ? text.length : nl + 1;
|
|
1343
|
+
const sep = start === 0 ? 0 : begin === MANAGED_BEGIN_NO_EOL ? 2 : 1;
|
|
1344
|
+
if (text.slice(start - sep, start) !== "\n".repeat(sep)) return void 0;
|
|
1345
|
+
return text.slice(0, start - sep) + text.slice(end);
|
|
1346
|
+
}
|
|
1347
|
+
return void 0;
|
|
1348
|
+
}
|
|
1349
|
+
function canonicalToml(v) {
|
|
1350
|
+
if (Array.isArray(v)) return `[${v.map(canonicalToml).join(",")}]`;
|
|
1351
|
+
if (v instanceof Date) return `d${v.toISOString()}`;
|
|
1352
|
+
if (typeof v === "bigint") return `n${v}`;
|
|
1353
|
+
if (typeof v === "object" && v !== null) {
|
|
1354
|
+
return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonicalToml(v[k])}`).join(",")}}`;
|
|
1355
|
+
}
|
|
1356
|
+
return JSON.stringify(v) ?? "undefined";
|
|
1357
|
+
}
|
|
1358
|
+
function appendManagedBlock(original, target) {
|
|
1359
|
+
const base = removeManagedBlock(original) ?? original;
|
|
1360
|
+
try {
|
|
1361
|
+
const baseHooks = parse(base).hooks ?? {};
|
|
1362
|
+
const targetHooks = target.hooks ?? {};
|
|
1363
|
+
const added = {};
|
|
1364
|
+
for (const [event, groups] of Object.entries(targetHooks)) {
|
|
1365
|
+
if (event === "state" || !Array.isArray(groups)) continue;
|
|
1366
|
+
const have = Array.isArray(baseHooks[event]) ? baseHooks[event].length : 0;
|
|
1367
|
+
if (groups.length > have) added[event] = groups.slice(have);
|
|
1368
|
+
}
|
|
1369
|
+
const baseState = baseHooks["state"] ?? {};
|
|
1370
|
+
const addedState = Object.fromEntries(Object.entries(targetHooks["state"] ?? {}).filter(([k]) => !(k in baseState)));
|
|
1371
|
+
if (Object.keys(addedState).length > 0) added["state"] = addedState;
|
|
1372
|
+
let candidate = base;
|
|
1373
|
+
if (Object.keys(added).length > 0) {
|
|
1374
|
+
const noEol = base.length > 0 && !base.endsWith("\n");
|
|
1375
|
+
const lead = base.length === 0 ? "" : noEol ? "\n\n" : "\n";
|
|
1376
|
+
candidate = `${base}${lead}${noEol ? MANAGED_BEGIN_NO_EOL : MANAGED_BEGIN}
|
|
1377
|
+
${stringify({ hooks: added }).trimEnd()}
|
|
1378
|
+
${MANAGED_END}
|
|
1379
|
+
`;
|
|
1380
|
+
}
|
|
1381
|
+
return canonicalToml(parse(candidate)) === canonicalToml(target) ? candidate : void 0;
|
|
1382
|
+
} catch {
|
|
1383
|
+
return void 0;
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
function removeManagedBlockText(original, target, rekey) {
|
|
1387
|
+
const without = removeManagedBlock(original);
|
|
1388
|
+
if (without === void 0) return void 0;
|
|
1389
|
+
const renamed = without.replace(/^([ \t]*)\[hooks\.state\.("(?:[^"\\\n]|\\.)*"|'[^'\n]*')\]([ \t]*(?:#[^\r\n]*)?)(\r?)$/gm, (whole, indent, quoted, tail, cr) => {
|
|
1390
|
+
let key;
|
|
1391
|
+
try {
|
|
1392
|
+
key = quoted.startsWith('"') ? JSON.parse(quoted) : quoted.slice(1, -1);
|
|
1393
|
+
} catch {
|
|
1394
|
+
return whole;
|
|
1395
|
+
}
|
|
1396
|
+
const next = rekey.get(key);
|
|
1397
|
+
return next === void 0 ? whole : `${indent}[hooks.state.${JSON.stringify(next)}]${tail}${cr}`;
|
|
1398
|
+
});
|
|
1399
|
+
try {
|
|
1400
|
+
return canonicalToml(parse(renamed)) === canonicalToml(target) ? renamed : void 0;
|
|
1401
|
+
} catch {
|
|
1402
|
+
return void 0;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
function codexEventLabel(event) {
|
|
1406
|
+
const known = CODEX_EVENT_ARG[event] ?? CODEX_GLOBAL_EVENT_ARG[event];
|
|
1407
|
+
return known ?? event.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
1408
|
+
}
|
|
1409
|
+
function planStateCleanup(configPath, hooks) {
|
|
1410
|
+
const ownKeys = /* @__PURE__ */ new Set();
|
|
1411
|
+
const ownHashes = /* @__PURE__ */ new Set();
|
|
1412
|
+
const rekey = /* @__PURE__ */ new Map();
|
|
1413
|
+
for (const [event, groups] of Object.entries(hooks)) {
|
|
1414
|
+
if (event === "state" || !Array.isArray(groups)) continue;
|
|
1415
|
+
const label = codexEventLabel(event);
|
|
1416
|
+
const keyOf = (g, h) => `${configPath}:${label}:${g}:${h}`;
|
|
1417
|
+
let newGroup = 0;
|
|
1418
|
+
groups.forEach((group, gi) => {
|
|
1419
|
+
const list = Array.isArray(group?.hooks) ? group.hooks : [];
|
|
1420
|
+
const matcher = typeof group?.matcher === "string" ? group.matcher : void 0;
|
|
1421
|
+
const mine = list.map((h) => isCodexTokenGoatCommand(h?.command));
|
|
1422
|
+
list.forEach((h, hi) => {
|
|
1423
|
+
if (!mine[hi]) return;
|
|
1424
|
+
ownKeys.add(keyOf(gi, hi));
|
|
1425
|
+
ownHashes.add(computeCodexHookHash(label, h.command, matcher));
|
|
1426
|
+
ownHashes.add(computeCodexHookHash(label, h.command));
|
|
1427
|
+
});
|
|
1428
|
+
const kept = mine.filter((m) => !m).length;
|
|
1429
|
+
if (kept === 0 && list.length > 0) return;
|
|
1430
|
+
let newHook = 0;
|
|
1431
|
+
list.forEach((_h, hi) => {
|
|
1432
|
+
if (mine[hi]) return;
|
|
1433
|
+
if (newGroup !== gi || newHook !== hi) rekey.set(keyOf(gi, hi), keyOf(newGroup, newHook));
|
|
1434
|
+
newHook++;
|
|
1435
|
+
});
|
|
1436
|
+
newGroup++;
|
|
1437
|
+
});
|
|
1438
|
+
}
|
|
1439
|
+
return { ownKeys, ownHashes, rekey };
|
|
1440
|
+
}
|
|
1441
|
+
function installCodex() {
|
|
1442
|
+
return recordCreatedBy(codexArtifactPaths(), installCodexFiles);
|
|
1443
|
+
}
|
|
1444
|
+
function codexArtifactPaths() {
|
|
1445
|
+
return [codexConfigPath(), codexAgentsPath(), codexHookScriptPath(), codexLegacyHookScriptPath()];
|
|
1446
|
+
}
|
|
1447
|
+
function installCodexFiles() {
|
|
1448
|
+
const configPath = codexConfigPath();
|
|
1449
|
+
const agentsPath = codexAgentsPath();
|
|
1450
|
+
const scriptPath = codexHookScriptPath();
|
|
1451
|
+
ensureDirSync(path3.dirname(scriptPath));
|
|
1452
|
+
atomicWriteText(scriptPath, CODEX_HOOK_SCRIPT);
|
|
1453
|
+
atomicWriteText(codexLegacyHookScriptPath(), legacyShimForwarder("{}"));
|
|
1454
|
+
const config = readCodexConfig(configPath, { strict: true });
|
|
1455
|
+
const hooks = config.hooks ?? {};
|
|
1456
|
+
let hooksChanged = false;
|
|
1457
|
+
const staleStateKeysToRemove = [];
|
|
1458
|
+
for (const event of CODEX_HOOK_EVENTS) {
|
|
1459
|
+
const eventArg = CODEX_EVENT_ARG[event];
|
|
1460
|
+
const expectedCommand = codexHookCommandFor(scriptPath, eventArg);
|
|
1461
|
+
const groups = Array.isArray(hooks[event]) ? [...hooks[event]] : [];
|
|
1462
|
+
let removedGroups = 0;
|
|
1463
|
+
for (let idx = 0; idx < groups.length; idx++) {
|
|
1464
|
+
const g = groups[idx];
|
|
1465
|
+
if (g.matcher === void 0 || CODEX_MATCHERS.includes(g.matcher)) continue;
|
|
1466
|
+
const hookList = g.hooks ?? [];
|
|
1467
|
+
const keptHooks = hookList.filter((h) => !isCodexTokenGoatCommand(h.command));
|
|
1468
|
+
if (keptHooks.length === hookList.length) continue;
|
|
1469
|
+
const originalIdx = idx + removedGroups;
|
|
1470
|
+
hookList.forEach((h, hi) => {
|
|
1471
|
+
if (isCodexTokenGoatCommand(h.command)) staleStateKeysToRemove.push(`${configPath}:${eventArg}:${originalIdx}:${hi}`);
|
|
1472
|
+
});
|
|
1473
|
+
hooksChanged = true;
|
|
1474
|
+
if (keptHooks.length > 0) {
|
|
1475
|
+
groups[idx] = { ...g, hooks: keptHooks };
|
|
1476
|
+
} else {
|
|
1477
|
+
groups.splice(idx, 1);
|
|
1478
|
+
idx--;
|
|
1479
|
+
removedGroups++;
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
for (const matcher of CODEX_MATCHERS) {
|
|
1483
|
+
if (groupHasTokenGoat2(groups, matcher, (c) => c === expectedCommand)) continue;
|
|
1484
|
+
const nextGroups = stripStaleGroupHooks(groups, isCodexTokenGoatCommand, { matcher });
|
|
1485
|
+
groups.length = 0;
|
|
1486
|
+
groups.push(...nextGroups);
|
|
1487
|
+
groups.push({ matcher, hooks: [{ type: "command", command: expectedCommand }] });
|
|
1488
|
+
hooksChanged = true;
|
|
1489
|
+
}
|
|
1490
|
+
hooks[event] = groups;
|
|
1491
|
+
}
|
|
1492
|
+
for (const event of CODEX_GLOBAL_HOOK_EVENTS) {
|
|
1493
|
+
const eventArg = CODEX_GLOBAL_EVENT_ARG[event];
|
|
1494
|
+
const expectedCommand = codexHookCommandFor(scriptPath, eventArg);
|
|
1495
|
+
const groups = Array.isArray(hooks[event]) ? [...hooks[event]] : [];
|
|
1496
|
+
if (anyGroupHasTokenGoat(groups, (c) => c === expectedCommand)) {
|
|
1497
|
+
hooks[event] = groups;
|
|
1498
|
+
continue;
|
|
1499
|
+
}
|
|
1500
|
+
const nextGroups = stripStaleGroupHooks(groups, isCodexTokenGoatCommand);
|
|
1501
|
+
nextGroups.push({ hooks: [{ type: "command", command: expectedCommand }] });
|
|
1502
|
+
hooks[event] = nextGroups;
|
|
1503
|
+
hooksChanged = true;
|
|
1504
|
+
}
|
|
1505
|
+
const agentsChanged = writeAgentsBlock(agentsPath);
|
|
1506
|
+
const hooksState = hooks["state"] ?? {};
|
|
1507
|
+
for (const key of staleStateKeysToRemove) {
|
|
1508
|
+
if (key in hooksState) {
|
|
1509
|
+
delete hooksState[key];
|
|
1510
|
+
hooksChanged = true;
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
for (const event of CODEX_HOOK_EVENTS) {
|
|
1514
|
+
const eventArg = CODEX_EVENT_ARG[event];
|
|
1515
|
+
const groups = hooks[event] ?? [];
|
|
1516
|
+
for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
|
|
1517
|
+
const g = groups[groupIndex];
|
|
1518
|
+
if (g && g.matcher && CODEX_MATCHERS.includes(g.matcher)) {
|
|
1519
|
+
const hookList = g.hooks ?? [];
|
|
1520
|
+
for (let hookIndex = 0; hookIndex < hookList.length; hookIndex++) {
|
|
1521
|
+
const h = hookList[hookIndex];
|
|
1522
|
+
if (h && isCodexTokenGoatCommand(h.command)) {
|
|
1523
|
+
const stateKey = `${configPath}:${eventArg}:${groupIndex}:${hookIndex}`;
|
|
1524
|
+
const hash = computeCodexHookHash(eventArg, h.command, g.matcher);
|
|
1525
|
+
if (hooksState[stateKey]?.trusted_hash !== hash) {
|
|
1526
|
+
hooksState[stateKey] = { ...hooksState[stateKey], trusted_hash: hash };
|
|
1527
|
+
hooksChanged = true;
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
for (const event of CODEX_GLOBAL_HOOK_EVENTS) {
|
|
1535
|
+
const eventArg = CODEX_GLOBAL_EVENT_ARG[event];
|
|
1536
|
+
const groups = hooks[event] ?? [];
|
|
1537
|
+
for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
|
|
1538
|
+
const g = groups[groupIndex];
|
|
1539
|
+
if (!g) continue;
|
|
1540
|
+
const hookList = g.hooks ?? [];
|
|
1541
|
+
for (let hookIndex = 0; hookIndex < hookList.length; hookIndex++) {
|
|
1542
|
+
const h = hookList[hookIndex];
|
|
1543
|
+
if (h && isCodexTokenGoatCommand(h.command)) {
|
|
1544
|
+
const stateKey = `${configPath}:${eventArg}:${groupIndex}:${hookIndex}`;
|
|
1545
|
+
const hash = computeCodexHookHash(eventArg, h.command);
|
|
1546
|
+
if (hooksState[stateKey]?.trusted_hash !== hash) {
|
|
1547
|
+
hooksState[stateKey] = { ...hooksState[stateKey], trusted_hash: hash };
|
|
1548
|
+
hooksChanged = true;
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
if (Object.keys(hooksState).length > 0) {
|
|
1555
|
+
hooks["state"] = hooksState;
|
|
1556
|
+
}
|
|
1557
|
+
if (hooksChanged) {
|
|
1558
|
+
config.hooks = hooks;
|
|
1559
|
+
ensureDirSync(path3.dirname(configPath));
|
|
1560
|
+
backupFile(configPath);
|
|
1561
|
+
const before = fs3.existsSync(configPath) ? fs3.readFileSync(configPath, "utf8") : "";
|
|
1562
|
+
writeConfigText(configPath, appendManagedBlock(before, config) ?? stringify(config));
|
|
1563
|
+
}
|
|
1564
|
+
return {
|
|
1565
|
+
configPath,
|
|
1566
|
+
agentsPath,
|
|
1567
|
+
hookScriptPath: scriptPath,
|
|
1568
|
+
alreadyInstalled: !hooksChanged && !agentsChanged
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
function uninstallCodex() {
|
|
1572
|
+
const configPath = codexConfigPath();
|
|
1573
|
+
const agentsPath = codexAgentsPath();
|
|
1574
|
+
const scriptPath = codexHookScriptPath();
|
|
1575
|
+
let removedAny = false;
|
|
1576
|
+
const config = readCodexConfig(configPath, { strict: true, command: "uninstall" });
|
|
1577
|
+
const hooks = config.hooks;
|
|
1578
|
+
let keepBackups = false;
|
|
1579
|
+
if (hooks !== void 0) {
|
|
1580
|
+
const plan = planStateCleanup(configPath, structuredClone(hooks));
|
|
1581
|
+
const hooksRemoved = stripOwnHooksFromMap(hooks, isCodexTokenGoatCommand);
|
|
1582
|
+
const hooksState = hooks["state"];
|
|
1583
|
+
let stateChanged = false;
|
|
1584
|
+
if (hooksState && typeof hooksState === "object") {
|
|
1585
|
+
const kept = [];
|
|
1586
|
+
const moved = [];
|
|
1587
|
+
for (const [key, value] of Object.entries(hooksState)) {
|
|
1588
|
+
const hash = value?.trusted_hash;
|
|
1589
|
+
if (plan.ownKeys.has(key) || typeof hash === "string" && plan.ownHashes.has(hash)) {
|
|
1590
|
+
stateChanged = true;
|
|
1591
|
+
continue;
|
|
1592
|
+
}
|
|
1593
|
+
const next = plan.rekey.get(key);
|
|
1594
|
+
if (next === void 0) kept.push([key, value]);
|
|
1595
|
+
else {
|
|
1596
|
+
moved.push([next, value]);
|
|
1597
|
+
stateChanged = true;
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
for (const k of Object.keys(hooksState)) delete hooksState[k];
|
|
1601
|
+
for (const [k, v] of [...kept, ...moved]) hooksState[k] = v;
|
|
1602
|
+
if (Object.keys(hooksState).length === 0) {
|
|
1603
|
+
delete hooks["state"];
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
if (hooksRemoved || stateChanged) {
|
|
1607
|
+
if (Object.keys(hooks).length === 0) {
|
|
1608
|
+
delete config.hooks;
|
|
1609
|
+
} else {
|
|
1610
|
+
config.hooks = hooks;
|
|
1611
|
+
}
|
|
1612
|
+
backupFile(configPath);
|
|
1613
|
+
const before = fs3.readFileSync(configPath, "utf8");
|
|
1614
|
+
const text = removeManagedBlockText(before, config, plan.rekey);
|
|
1615
|
+
if (text === void 0) {
|
|
1616
|
+
try {
|
|
1617
|
+
keepBackups = stringify(parse(before)) !== before;
|
|
1618
|
+
} catch {
|
|
1619
|
+
keepBackups = true;
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
writeConfigText(configPath, text ?? stringify(config));
|
|
1623
|
+
removedAny = true;
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
if (stripAgentsBlock(agentsPath)) {
|
|
1627
|
+
removedAny = true;
|
|
1628
|
+
}
|
|
1629
|
+
for (const p of [scriptPath, codexLegacyHookScriptPath()]) {
|
|
1630
|
+
try {
|
|
1631
|
+
fs3.unlinkSync(p);
|
|
1632
|
+
removedAny = true;
|
|
1633
|
+
} catch {
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
if (!keepBackups) removeCreatedBackups(configPath);
|
|
1637
|
+
removeCreatedTree(codexArtifactPaths());
|
|
1638
|
+
return removedAny;
|
|
1639
|
+
}
|
|
1640
|
+
function wiredCodexHookWords() {
|
|
1641
|
+
const hooks = readCodexConfig(codexConfigPath()).hooks ?? {};
|
|
1642
|
+
const scriptPath = codexHookScriptPath();
|
|
1643
|
+
const expected = new Set([...Object.values(CODEX_EVENT_ARG), ...Object.values(CODEX_GLOBAL_EVENT_ARG)].map((arg) => codexHookCommandFor(scriptPath, arg, { sync: false })));
|
|
1644
|
+
const out = [];
|
|
1645
|
+
for (const [event, groups] of Object.entries(hooks)) {
|
|
1646
|
+
if (event === "state" || !Array.isArray(groups)) continue;
|
|
1647
|
+
for (const g of groups) {
|
|
1648
|
+
for (const h of Array.isArray(g?.hooks) ? g.hooks : []) {
|
|
1649
|
+
if (isCodexTokenGoatCommand(h?.command)) out.push({ words: splitHookCommand(h.command, process.platform === "win32" ? "powershell" : "sh"), current: expected.has(h.command) });
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
return out;
|
|
1654
|
+
}
|
|
1655
|
+
function isCodexInstalled() {
|
|
1656
|
+
const configPath = codexConfigPath();
|
|
1657
|
+
const config = readCodexConfig(configPath);
|
|
1658
|
+
const hooks = config.hooks;
|
|
1659
|
+
if (hooks === void 0) return false;
|
|
1660
|
+
const scriptPath = codexHookScriptPath();
|
|
1661
|
+
const hooksState = hooks["state"] ?? {};
|
|
1662
|
+
for (const event of CODEX_HOOK_EVENTS) {
|
|
1663
|
+
const eventArg = CODEX_EVENT_ARG[event];
|
|
1664
|
+
const expectedCommand = codexHookCommandFor(scriptPath, eventArg, { sync: false });
|
|
1665
|
+
const groups = hooks[event] ?? [];
|
|
1666
|
+
for (const matcher of CODEX_MATCHERS) {
|
|
1667
|
+
const position = findTokenGoatEntryPosition(groups, matcher, (c) => c === expectedCommand);
|
|
1668
|
+
if (position === void 0) return false;
|
|
1669
|
+
const stateKey = `${configPath}:${eventArg}:${position.groupIndex}:${position.hookIndex}`;
|
|
1670
|
+
const expectedHash = computeCodexHookHash(eventArg, expectedCommand, matcher);
|
|
1671
|
+
if (hooksState[stateKey]?.trusted_hash !== expectedHash) return false;
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
for (const event of CODEX_GLOBAL_HOOK_EVENTS) {
|
|
1675
|
+
const eventArg = CODEX_GLOBAL_EVENT_ARG[event];
|
|
1676
|
+
const expectedCommand = codexHookCommandFor(scriptPath, eventArg, { sync: false });
|
|
1677
|
+
const groups = hooks[event] ?? [];
|
|
1678
|
+
const position = findAnyTokenGoatEntryPosition(groups, (c) => c === expectedCommand);
|
|
1679
|
+
if (position === void 0) return false;
|
|
1680
|
+
const stateKey = `${configPath}:${eventArg}:${position.groupIndex}:${position.hookIndex}`;
|
|
1681
|
+
const expectedHash = computeCodexHookHash(eventArg, expectedCommand);
|
|
1682
|
+
if (hooksState[stateKey]?.trusted_hash !== expectedHash) return false;
|
|
1683
|
+
}
|
|
1684
|
+
if (!fs3.existsSync(scriptPath)) return false;
|
|
1685
|
+
let agents;
|
|
1686
|
+
try {
|
|
1687
|
+
agents = fs3.readFileSync(codexAgentsPath(), "utf8");
|
|
1688
|
+
} catch {
|
|
1689
|
+
return false;
|
|
1690
|
+
}
|
|
1691
|
+
return agents.includes(AGENTS_BEGIN) && agents.includes(AGENTS_END);
|
|
1692
|
+
}
|
|
1693
|
+
var AGENTS_BEGIN = "<!-- token-goat-codex-begin -->";
|
|
1694
|
+
var AGENTS_END = "<!-- token-goat-codex-end -->";
|
|
1695
|
+
function buildAgentsBlock() {
|
|
1696
|
+
return buildGuidanceBlock({
|
|
1697
|
+
beginMarker: AGENTS_BEGIN,
|
|
1698
|
+
endMarker: AGENTS_END,
|
|
1699
|
+
fallbackToolClause: "Codex's native `exec`, `apply_patch`, and `view_image` tools (shell commands like `cat`/`type` run inside `exec`)",
|
|
1700
|
+
gdrive: loadConfig().gdrive.enabled
|
|
1701
|
+
});
|
|
1702
|
+
}
|
|
1703
|
+
function writeAgentsBlock(p) {
|
|
1704
|
+
return upsertDelimitedBlock(p, AGENTS_BEGIN, AGENTS_END, buildAgentsBlock());
|
|
1705
|
+
}
|
|
1706
|
+
function stripAgentsBlock(p) {
|
|
1707
|
+
return stripDelimitedBlock(p, AGENTS_BEGIN, AGENTS_END);
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
// src/bridges/copilot_cli.ts
|
|
1711
|
+
init_define_import_meta_env();
|
|
1712
|
+
|
|
1713
|
+
// src/bridges/shrink_block.ts
|
|
1714
|
+
init_define_import_meta_env();
|
|
1715
|
+
var MATERIALIZE_SHRUNK_IMAGE_JS = `// Best-effort sweep of previously materialized shrunk copies in the OS temp dir. The temp file only needs to outlive the single tool call whose path argument was rewritten to it, so anything older than an hour is finished with; the "token-goat-shrink-" prefix check confines the sweep to this mechanism's own files (same defense-in-depth rule as pruneShrinkCache in src/image_shrink.ts). Throttled per process; runs only when a shrink payload actually arrives, so the common no-image path never pays for it.
|
|
1716
|
+
const MATERIALIZED_SHRINK_MAX_AGE_MS = 60 * 60 * 1000
|
|
1717
|
+
let lastMaterializedShrinkSweepAtMs = 0
|
|
1718
|
+
function pruneMaterializedShrinks() {
|
|
1719
|
+
const now = Date.now()
|
|
1720
|
+
if (now - lastMaterializedShrinkSweepAtMs < MATERIALIZED_SHRINK_MAX_AGE_MS) return
|
|
1721
|
+
lastMaterializedShrinkSweepAtMs = now
|
|
1722
|
+
try {
|
|
1723
|
+
const dir = os.tmpdir()
|
|
1724
|
+
for (const file of fs.readdirSync(dir)) {
|
|
1725
|
+
if (!file.startsWith("token-goat-shrink-")) continue
|
|
1726
|
+
const full = path.join(dir, file)
|
|
1727
|
+
try {
|
|
1728
|
+
const st = fs.statSync(full)
|
|
1729
|
+
if (st.isFile() && now - st.mtimeMs > MATERIALIZED_SHRINK_MAX_AGE_MS) fs.unlinkSync(full)
|
|
1730
|
+
} catch {
|
|
1731
|
+
// Best-effort per-file cleanup; one bad stat/unlink must not abort the sweep.
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
} catch {
|
|
1735
|
+
// Best-effort; a readdir failure must never break the materialization below.
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
// Decode a token-goat image-shrink additionalContext payload ("<summary>\\ndata:image/<fmt>;base64,<data>") into a real file on disk, since the host's pre-tool hook has no context-injection channel to hand the shrunk image to the model directly -- only argument rewriting. The temp filename is derived from pid/time/random alone, never from the source image's own name, so an attacker-chosen filename cannot steer the write; the format suffix comes from the data-URL's media subtype, whose character class ([a-zA-Z0-9.+-]) admits no path separators. Returns undefined (leaving the original path argument untouched, so a failed shrink falls back to the original image) if the context isn't a shrink payload or anything goes wrong writing it.
|
|
1740
|
+
function materializeShrunkImage(context) {
|
|
1741
|
+
if (typeof context !== "string") return undefined
|
|
1742
|
+
const idx = context.indexOf("data:image/")
|
|
1743
|
+
if (idx === -1) return undefined
|
|
1744
|
+
const match = /^data:image\\/([a-zA-Z0-9.+-]+);base64,([A-Za-z0-9+/=]+)$/.exec(context.slice(idx).trim())
|
|
1745
|
+
if (!match) return undefined
|
|
1746
|
+
try {
|
|
1747
|
+
pruneMaterializedShrinks()
|
|
1748
|
+
const buf = Buffer.from(match[2], "base64")
|
|
1749
|
+
const name = \`token-goat-shrink-\${process.pid}-\${Date.now()}-\${globalThis.crypto.randomUUID()}.\${match[1]}\`
|
|
1750
|
+
const file = path.join(os.tmpdir(), name)
|
|
1751
|
+
// Owner-only: the copy is of a workspace image and sits in the shared temp dir.
|
|
1752
|
+
fs.writeFileSync(file, buf, { mode: 0o600 })
|
|
1753
|
+
return file
|
|
1754
|
+
} catch {
|
|
1755
|
+
return undefined
|
|
1756
|
+
}
|
|
1757
|
+
}`;
|
|
1758
|
+
|
|
1759
|
+
// src/bridges/copilot_cli.ts
|
|
1760
|
+
var COPILOT_CLI_HOOK_SCRIPT = `#!/usr/bin/env node
|
|
1761
|
+
// token-goat Copilot CLI hook shim. Translates Copilot's hook event names and
|
|
1762
|
+
// request/response schema to/from token-goat's internal hook protocol.
|
|
1763
|
+
'use strict'
|
|
1764
|
+
const { spawnSync } = require('node:child_process')
|
|
1765
|
+
const fs = require('node:fs')
|
|
1766
|
+
const os = require('node:os')
|
|
1767
|
+
const path = require('node:path')
|
|
1768
|
+
const { pathToFileURL } = require('node:url')
|
|
1769
|
+
|
|
1770
|
+
// Copilot event name -> token-goat internal HookEventName (src/types.ts's
|
|
1771
|
+
// HOOK_EVENTS). Only these nine have a token-goat handler; every other real
|
|
1772
|
+
// Copilot event (sessionEnd, errorOccurred, notification, permissionRequest)
|
|
1773
|
+
// is left unimplemented rather than guessed at, and falls through to the
|
|
1774
|
+
// default no-op below. subagentStart answers with the spawn briefing as
|
|
1775
|
+
// additionalContext, which Copilot CLI 1.0.88 prepends to the subagent's own
|
|
1776
|
+
// prompt (capture C4a), so the briefing no longer rides a rewrite of the
|
|
1777
|
+
// parent's task call and stays out of the parent's history.
|
|
1778
|
+
// postToolUseFailure is the newest of the eight and the only one whose channel
|
|
1779
|
+
// costs tokens instead of saving them: it fires instead of postToolUse when a
|
|
1780
|
+
// tool result is a failure, and accepts only additionalContext back --
|
|
1781
|
+
// modifiedResult and suppressOutput are not honored there, so a failed result
|
|
1782
|
+
// still cannot be fenced, compressed or shrunk. It is wired anyway because
|
|
1783
|
+
// additionalContext demonstrably reaches the model (see the postToolUseFailure
|
|
1784
|
+
// branch in translate() for the bundle offset), and hooks_tool_failure.ts
|
|
1785
|
+
// spends that channel only on an exact repeat failure, where staying silent
|
|
1786
|
+
// costs a whole wasted retry.
|
|
1787
|
+
// 'sessionStart' was previously a permanent no-op on the stated grounds that
|
|
1788
|
+
// token-goat has no internal session_start handler. That was simply wrong --
|
|
1789
|
+
// hooks_session_start.ts has long emitted the command-routing reminder that
|
|
1790
|
+
// every other harness receives -- and the no-op was the reason Copilot CLI
|
|
1791
|
+
// sessions alone never got told token-goat exists. It is wired now: verified
|
|
1792
|
+
// against Copilot CLI 1.0.77 that a hooks.json sessionStart entry returning
|
|
1793
|
+
// {additionalContext} does reach the model. The github/copilot-cli#2142
|
|
1794
|
+
// fire-and-forget bug that would have made this dead wiring was fixed in a
|
|
1795
|
+
// pre-release months before that version, and its companion multi-extension
|
|
1796
|
+
// hook-overwrite bug never applied here: it hit runtime *extension* hooks,
|
|
1797
|
+
// while this config-file hooks.json path goes through Copilot's own merge.
|
|
1798
|
+
const COPILOT_TO_TG_EVENT = {
|
|
1799
|
+
sessionStart: 'session_start',
|
|
1800
|
+
preToolUse: 'pre_tool_use',
|
|
1801
|
+
postToolUse: 'post_tool_use',
|
|
1802
|
+
preCompact: 'pre_compact',
|
|
1803
|
+
agentStop: 'stop',
|
|
1804
|
+
subagentStop: 'subagent_stop',
|
|
1805
|
+
userPromptSubmitted: 'user_prompt_submit',
|
|
1806
|
+
postToolUseFailure: 'post_tool_use_failure',
|
|
1807
|
+
subagentStart: 'subagent_start',
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
// Keys only VS Code reads. VS Code 1.137 parses this same hooks file and
|
|
1811
|
+
// accepts a key either from its camelCase Copilot table, which has no
|
|
1812
|
+
// subagentStart, or when the key is already its own PascalCase hook type
|
|
1813
|
+
// (workbench.desktop.main.js: iut(key) ?? eut(key)). So VS Code's subagent
|
|
1814
|
+
// hook needs the key spelled SubagentStart. A Copilot CLI payload arriving on
|
|
1815
|
+
// one of these keys is answered with nothing, so a Copilot build that also
|
|
1816
|
+
// honored the PascalCase spelling could not brief a subagent twice.
|
|
1817
|
+
const VSCODE_ONLY_TO_TG_EVENT = {
|
|
1818
|
+
SubagentStart: 'subagent_start',
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
// Copilot built-in tool name -> token-goat internal tool name. Confirmed via
|
|
1822
|
+
// @github/copilot-sdk type definitions and multiple real GitHub issue payload
|
|
1823
|
+
// dumps -- supersedes an earlier docs-based guess (shell/read/write/url) that
|
|
1824
|
+
// didn't hold up in practice; 'write' in particular was never a real
|
|
1825
|
+
// toolName value, only a Copilot permission-pattern keyword. 'powershell'
|
|
1826
|
+
// maps to the same 'Bash' handler as 'bash' since both are shell-command
|
|
1827
|
+
// execution from token-goat's perspective (mirrors how hooks_bash.ts's own
|
|
1828
|
+
// filters already treat powershell-wrapped commands as part of the Bash
|
|
1829
|
+
// pipeline, not a separate tool). 'task', 'ask_user', 'memory', and
|
|
1830
|
+
// MCP-server tool invocations (<server-name>-<tool-name>) have no
|
|
1831
|
+
// token-goat equivalent and are passed through unmapped (safe no-op for
|
|
1832
|
+
// handlers that don't recognize the name).
|
|
1833
|
+
// 'read_bash'/'read_powershell' are the background-shell output pollers, and
|
|
1834
|
+
// they are the exact shape of Claude Code's BashOutput: Copilot's shell tool
|
|
1835
|
+
// is async, so a long-running command is started once and then re-read over
|
|
1836
|
+
// and over within one turn, each read returning the accumulated output again.
|
|
1837
|
+
// hooks_bashoutput.ts already collapses that into a delta (or a short
|
|
1838
|
+
// "unchanged" marker) for Claude Code, and now does the same here. Both the
|
|
1839
|
+
// names and the argument key were read out of the shipping 1.0.80 bundle
|
|
1840
|
+
// rather than guessed: the builtin tool-name table in
|
|
1841
|
+
// prebuilds/win32-x64/runtime.node lists read_bash/stop_bash/list_bash and
|
|
1842
|
+
// read_powershell/stop_powershell/list_powershell, and the poller's own input
|
|
1843
|
+
// schema in app.js is {shellId, delay} -- so the shell id needs the
|
|
1844
|
+
// POLL_ID_ARG_KEY remap below to reach postBashOutputHandler, which reads
|
|
1845
|
+
// 'bash_id'. read_shell/stop_shell/list_shells, which an earlier static sweep
|
|
1846
|
+
// of the same binary suggested were the real names, are internal Rust
|
|
1847
|
+
// identifiers (tool_read_shell_prepare_input, tool_list_shells_descriptor,
|
|
1848
|
+
// PreparedStopShellInput, and the serde field names of the shell config
|
|
1849
|
+
// struct), never wire tool names, so they are deliberately absent here.
|
|
1850
|
+
// stop_bash/list_bash and their powershell twins stay unmapped because
|
|
1851
|
+
// token-goat has no KillShell-equivalent handler for them to reach; a mapping
|
|
1852
|
+
// would be pure decoration.
|
|
1853
|
+
// 'bash'/'powershell' stay exactly as they were. The same sweep suggested the
|
|
1854
|
+
// executor had been renamed to write_bash/write_powershell and that this
|
|
1855
|
+
// mapping was dead, and that is not what the bundle says: app.js resolves the
|
|
1856
|
+
// executor as shellConfig?.shellToolName ?? "bash" (with "powershell" as the
|
|
1857
|
+
// Windows default of the same config), and its command lives under 'command'
|
|
1858
|
+
// exactly as hooks_bash.ts expects. write_bash/write_powershell are real tool
|
|
1859
|
+
// names, but they are a different tool -- their schema is {shellId, input,
|
|
1860
|
+
// delay} and the bundle files them under the subtype "write_shell", i.e. send
|
|
1861
|
+
// stdin to an already-running shell, not run a command. Mapping them to Bash
|
|
1862
|
+
// would label a stdin write as a shell execution, so they are left unmapped.
|
|
1863
|
+
// 'task', 'read_agent' and 'memory'-family tools are likewise left alone:
|
|
1864
|
+
// task's result is assembled in the native addon and its shape is unknown,
|
|
1865
|
+
// read_agent is an incremental poll that postAgentHandler is not written for,
|
|
1866
|
+
// and the real tool names behind memory were never confirmed. Each would put
|
|
1867
|
+
// a handler that rewrites model-visible output in front of a payload shape
|
|
1868
|
+
// nobody has seen, which is worse than leaving the compression on the table.
|
|
1869
|
+
// Own properties only, for every map in this shim -- see the event map in main() for why a
|
|
1870
|
+
// bare lookup on a plain object literal is not a gate. A tool named 'constructor' resolved to
|
|
1871
|
+
// a Function, which JSON.stringify drops, so the forwarded payload carried no tool_name and
|
|
1872
|
+
// every hook keyed on one no-opped; '__proto__' forwarded a whole prototype instead. The key
|
|
1873
|
+
// is third-party text: Copilot namespaces MCP tools as server:tool and the stripped half is
|
|
1874
|
+
// whatever that server called its tool.
|
|
1875
|
+
function ownGet(map, key) {
|
|
1876
|
+
return typeof key === 'string' && Object.prototype.hasOwnProperty.call(map, key) ? map[key] : undefined
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
const TOOL_TO_TG = {
|
|
1880
|
+
bash: 'Bash',
|
|
1881
|
+
powershell: 'Bash',
|
|
1882
|
+
read_bash: 'BashOutput',
|
|
1883
|
+
read_powershell: 'BashOutput',
|
|
1884
|
+
view: 'Read',
|
|
1885
|
+
create: 'Write',
|
|
1886
|
+
edit: 'Edit',
|
|
1887
|
+
web_fetch: 'WebFetch',
|
|
1888
|
+
web_search: 'WebSearch',
|
|
1889
|
+
grep: 'Grep',
|
|
1890
|
+
glob: 'Glob',
|
|
1891
|
+
skill: 'Skill',
|
|
1892
|
+
exit_plan_mode: 'ExitPlanMode',
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
function foldToolName(name) {
|
|
1896
|
+
return typeof name === 'string' ? name.toLowerCase().replace(/[_-]/g, '') : ''
|
|
1897
|
+
}
|
|
1898
|
+
|
|
1899
|
+
const FOLDED_TOOL_TO_TG = {}
|
|
1900
|
+
for (const [k, v] of Object.entries(TOOL_TO_TG)) {
|
|
1901
|
+
FOLDED_TOOL_TO_TG[foldToolName(k)] = v
|
|
1902
|
+
}
|
|
1903
|
+
// Also register folded entries for canonical TG tool names directly (e.g. WebSearch -> websearch)
|
|
1904
|
+
for (const v of Object.values(TOOL_TO_TG)) {
|
|
1905
|
+
FOLDED_TOOL_TO_TG[foldToolName(v)] = v
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
function resolveCanonicalToolName(name) {
|
|
1909
|
+
if (!name || typeof name !== 'string') return name
|
|
1910
|
+
const direct = ownGet(TOOL_TO_TG, name)
|
|
1911
|
+
if (direct !== undefined) return direct
|
|
1912
|
+
const stripped = name.indexOf(':') !== -1 ? name.split(':').pop() : name
|
|
1913
|
+
const strippedDirect = ownGet(TOOL_TO_TG, stripped)
|
|
1914
|
+
if (strippedDirect !== undefined) return strippedDirect
|
|
1915
|
+
const folded = foldToolName(name)
|
|
1916
|
+
const foldedStripped = foldToolName(stripped)
|
|
1917
|
+
return ownGet(FOLDED_TOOL_TO_TG, folded) || ownGet(FOLDED_TOOL_TO_TG, foldedStripped) || name
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
// Confirmed via github/copilot-cli#3349 (open, unresolved as of writing): some
|
|
1921
|
+
// real Copilot CLI invocations send toolArgs as a JSON-*encoded string*
|
|
1922
|
+
// rather than a parsed object, contradicting the documented schema. Left
|
|
1923
|
+
// unhandled, canonical.tool_input would become a raw string and every
|
|
1924
|
+
// downstream event.toolInput[key] lookup in token-goat's handlers would
|
|
1925
|
+
// silently return undefined -- the deny/dedup mechanism would no-op with no
|
|
1926
|
+
// error surfaced. Parse it defensively; on a non-string, absent, or
|
|
1927
|
+
// unparsable value, fall back to {} rather than throwing (this shim's
|
|
1928
|
+
// convention throughout is fail-open, never crash on a malformed payload).
|
|
1929
|
+
function parseMaybeJsonObject(value) {
|
|
1930
|
+
if (value && typeof value === 'object') return value
|
|
1931
|
+
if (typeof value === 'string') {
|
|
1932
|
+
try {
|
|
1933
|
+
const parsed = JSON.parse(value)
|
|
1934
|
+
if (parsed && typeof parsed === 'object') return parsed
|
|
1935
|
+
} catch {
|
|
1936
|
+
// fall through to {}
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
return {}
|
|
1940
|
+
}
|
|
1941
|
+
|
|
1942
|
+
// view/edit/create send the file path under 'path'; every token-goat handler these
|
|
1943
|
+
// three tools reach only ever looks for 'file_path' (getFilePath in hooks_common.ts).
|
|
1944
|
+
// Keyed by the ORIGINAL Copilot tool name (before TOOL_TO_TG renames it) since that's
|
|
1945
|
+
// the name toolArgs' shape is keyed to, not token-goat's internal tool name.
|
|
1946
|
+
const FILE_PATH_ARG_KEY = {
|
|
1947
|
+
view: 'path',
|
|
1948
|
+
edit: 'path',
|
|
1949
|
+
create: 'path',
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
// read_bash/read_powershell send the background shell's id under 'shellId' (confirmed
|
|
1953
|
+
// against the poller's input schema in the shipping 1.0.80 app.js: {shellId, delay});
|
|
1954
|
+
// postBashOutputHandler reads 'bash_id'. Without this the tool-name mapping above would
|
|
1955
|
+
// be inert -- the handler bails on a missing bash_id and every poll would keep costing
|
|
1956
|
+
// the full accumulated output. Same keying convention as FILE_PATH_ARG_KEY: the ORIGINAL
|
|
1957
|
+
// Copilot tool name, since that is what the argument shape belongs to.
|
|
1958
|
+
const POLL_ID_ARG_KEY = {
|
|
1959
|
+
read_bash: 'shellId',
|
|
1960
|
+
read_powershell: 'shellId',
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
// Copilot spawns a brand-new process for every single hook invocation (no long-lived plugin
|
|
1964
|
+
// process the way OpenClaw's is -- OPENCLAW_HOOK_SCRIPT's own \`copilot-\${process.pid}-\${Date.now()}\`
|
|
1965
|
+
// fallback is safe there specifically because that process lives for the whole session, so the
|
|
1966
|
+
// pid stays constant across calls). If Copilot ever omits \`sessionId\` from a payload, falling
|
|
1967
|
+
// back to \`process.pid\` here would mint a DIFFERENT id on every single call for what's really
|
|
1968
|
+
// the same session, since process.pid varies per invocation -- breaking token-goat's
|
|
1969
|
+
// session-based dedup/state ledger, which never accumulates across calls as a result. Derive a
|
|
1970
|
+
// stable id instead from the one thing that's actually constant across calls for the same
|
|
1971
|
+
// session: the working directory Copilot reports. Copilot CLI's command hooks send it as \`cwd\`:
|
|
1972
|
+
// every payload 1.0.88 sent in the tg-captures run carried \`cwd\` and none carried
|
|
1973
|
+
// \`workingDirectory\` (tests/fixtures/copilot_cli_1_0_88/). The SDK's BaseHookInput in
|
|
1974
|
+
// copilot-sdk/types.d.ts declares the same value as \`workingDirectory\`, so both names are read,
|
|
1975
|
+
// that one first. Were neither read, the fallback id would come from process.cwd() and
|
|
1976
|
+
// \`canonical.cwd\` below would be undefined; tests/harness_schema_manifest.test.ts drives the
|
|
1977
|
+
// captured payload from a different directory to catch exactly that.
|
|
1978
|
+
function stableFallbackSessionId(cwd) {
|
|
1979
|
+
const key = typeof cwd === 'string' && cwd ? cwd : process.cwd()
|
|
1980
|
+
const hash = require('node:crypto').createHash('sha256').update(key).digest('hex').slice(0, 16)
|
|
1981
|
+
return 'copilot-' + hash
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
function remapToolInput(copilotToolName, input) {
|
|
1985
|
+
if (!input || typeof input !== 'object') return input
|
|
1986
|
+
let out = input
|
|
1987
|
+
// Add the canonical key alongside the original rather than renaming it, so nothing that
|
|
1988
|
+
// might read the original 'path'/'shellId' key elsewhere (e.g. a future handler) loses it.
|
|
1989
|
+
const stripped = typeof copilotToolName === 'string' && copilotToolName.indexOf(':') !== -1
|
|
1990
|
+
? copilotToolName.split(':').pop()
|
|
1991
|
+
: copilotToolName
|
|
1992
|
+
const folded = foldToolName(stripped)
|
|
1993
|
+
const pathKey = ownGet(FILE_PATH_ARG_KEY, copilotToolName) || ownGet(FILE_PATH_ARG_KEY, stripped) || (folded === 'view' || folded === 'edit' || folded === 'create' ? 'path' : undefined)
|
|
1994
|
+
if (pathKey !== undefined && pathKey in out) {
|
|
1995
|
+
out = Object.assign({}, out, { file_path: out[pathKey] })
|
|
1996
|
+
}
|
|
1997
|
+
const idKey = ownGet(POLL_ID_ARG_KEY, copilotToolName) || ownGet(POLL_ID_ARG_KEY, stripped) || (folded === 'readbash' || folded === 'readpowershell' ? 'shellId' : undefined)
|
|
1998
|
+
if (idKey !== undefined && idKey in out) {
|
|
1999
|
+
out = Object.assign({}, out, { bash_id: out[idKey] })
|
|
2000
|
+
}
|
|
2001
|
+
if (Array.isArray(out.view_range) && out.view_range.length >= 1) {
|
|
2002
|
+
const rawStart = Number(out.view_range[0])
|
|
2003
|
+
if (Number.isFinite(rawStart) && rawStart >= 1) {
|
|
2004
|
+
const mapped = { offset: Math.floor(rawStart) }
|
|
2005
|
+
if (out.view_range.length >= 2) {
|
|
2006
|
+
const rawEnd = Number(out.view_range[1])
|
|
2007
|
+
if (Number.isFinite(rawEnd) && rawEnd >= rawStart) {
|
|
2008
|
+
mapped.limit = Math.floor(rawEnd - rawStart + 1)
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
out = Object.assign({}, out, mapped)
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
if ('old_str' in out && !('old_string' in out)) {
|
|
2015
|
+
out = Object.assign({}, out, { old_string: out.old_str })
|
|
2016
|
+
}
|
|
2017
|
+
if ('new_str' in out && !('new_string' in out)) {
|
|
2018
|
+
out = Object.assign({}, out, { new_string: out.new_str })
|
|
2019
|
+
}
|
|
2020
|
+
return out
|
|
2021
|
+
}
|
|
2022
|
+
|
|
2023
|
+
${SHIM_TRY_SERVER}
|
|
2024
|
+
|
|
2025
|
+
// Attempts the resident server (tryServer above), then the in-process hook call: import()s dist/token-goat-hook.mjs (a sibling of
|
|
2026
|
+
// the baked token-goat entry path, built with zero load-time side effects -- unlike
|
|
2027
|
+
// the CLI entry, which runs the full argv-parsing CLI as a side effect of being
|
|
2028
|
+
// loaded) and calls its exported relayInProcess() directly, avoiding a second node
|
|
2029
|
+
// process spawn entirely. Returns undefined (triggering the spawnSync fallback below)
|
|
2030
|
+
// when entryPath is absent, the sibling file doesn't exist (an older install predating
|
|
2031
|
+
// this file), or anything else goes wrong -- this must never throw.
|
|
2032
|
+
async function tryInProcess(entryPath, tgEvent, canonical, harness) {
|
|
2033
|
+
if (!entryPath) return undefined
|
|
2034
|
+
try {
|
|
2035
|
+
// Set before either path: the resident server runs the call under this process's environment.
|
|
2036
|
+
process.env.TOKEN_GOAT_HARNESS_OVERRIDE = harness
|
|
2037
|
+
// Which hooks directory VS Code loaded this shim from is the only thing separating a
|
|
2038
|
+
// user-scope copy from a project-scope one -- the two files are byte-identical and so are
|
|
2039
|
+
// their payloads. vscode_duplicate.ts needs it to stand the redundant copy down.
|
|
2040
|
+
if (harness === 'vscode') process.env.TOKEN_GOAT_VSCODE_HOOKS_DIR = __dirname
|
|
2041
|
+
// Whether this hooks file wires subagentStart decides where a subagent's spawn briefing goes
|
|
2042
|
+
// (hooks_agent_spawn.ts subagentStartWired), and only this directory says which file that is.
|
|
2043
|
+
else process.env.TOKEN_GOAT_COPILOT_HOOKS_DIR = __dirname
|
|
2044
|
+
const served = await tryServer(entryPath, tgEvent, canonical)
|
|
2045
|
+
if (served !== undefined) return served
|
|
2046
|
+
const hookLibPath = path.join(path.dirname(entryPath), 'token-goat-hook.mjs')
|
|
2047
|
+
if (!require('node:fs').existsSync(hookLibPath)) return undefined
|
|
2048
|
+
const mod = await import(pathToFileURL(hookLibPath).href)
|
|
2049
|
+
return await mod.relayInProcess(tgEvent, canonical)
|
|
2050
|
+
} catch {
|
|
2051
|
+
return undefined
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
// VS Code's built-in agent reads this same hooks file (~/.copilot/hooks and .github/hooks are both
|
|
2056
|
+
// on its hook-source list) and runs these same entries, but it sends Claude Code's payload shape:
|
|
2057
|
+
// hook_event_name, session_id, tool_name, tool_input, tool_response. Copilot CLI's payload never
|
|
2058
|
+
// carries hook_event_name and always names its tool in toolName, so that pair tells them apart.
|
|
2059
|
+
// The payload goes to token-goat as-is under the vscode harness, which does its own tool-name
|
|
2060
|
+
// mapping and writes a response VS Code reads directly, so nothing here translates it.
|
|
2061
|
+
function isVscodePayload(payload) {
|
|
2062
|
+
return payload !== null && typeof payload === 'object' && typeof payload.hook_event_name === 'string' && payload.toolName === undefined
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
async function relayVscode(entryPath, tgEvent, payload) {
|
|
2066
|
+
// VS Code omits session_id when the chat has no session resource yet; key the state on the workspace instead, the same fallback the Copilot path uses.
|
|
2067
|
+
const input = typeof payload.session_id === 'string' && payload.session_id !== ''
|
|
2068
|
+
? payload
|
|
2069
|
+
: Object.assign({}, payload, { session_id: stableFallbackSessionId(process.cwd()) })
|
|
2070
|
+
let stdout = await tryInProcess(entryPath, tgEvent, input, 'vscode')
|
|
2071
|
+
if (stdout === undefined) {
|
|
2072
|
+
// tgEvent is a value of the closed COPILOT_TO_TG_EVENT map (gated in main) and the harness is a literal, so nothing caller-controlled reaches the shell string below.
|
|
2073
|
+
const spawnOpts = {
|
|
2074
|
+
input: JSON.stringify(input),
|
|
2075
|
+
encoding: 'utf8',
|
|
2076
|
+
windowsHide: true,
|
|
2077
|
+
timeout: 3000,
|
|
2078
|
+
killSignal: 'SIGKILL',
|
|
2079
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
2080
|
+
env: Object.assign({}, process.env, { TOKEN_GOAT_HARNESS_OVERRIDE: 'vscode', TOKEN_GOAT_VSCODE_HOOKS_DIR: __dirname }),
|
|
2081
|
+
}
|
|
2082
|
+
const res = entryPath
|
|
2083
|
+
? spawnSync(process.execPath, [entryPath, 'hook', tgEvent, '--harness', 'vscode'], spawnOpts)
|
|
2084
|
+
: spawnSync('token-goat hook ' + tgEvent + ' --harness vscode', Object.assign({ shell: true }, spawnOpts))
|
|
2085
|
+
if (res.status !== 0 || !res.stdout) return '{}'
|
|
2086
|
+
stdout = res.stdout
|
|
2087
|
+
}
|
|
2088
|
+
try {
|
|
2089
|
+
const parsed = JSON.parse(stdout)
|
|
2090
|
+
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? JSON.stringify(parsed) : '{}'
|
|
2091
|
+
} catch {
|
|
2092
|
+
return '{}'
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
async function main() {
|
|
2097
|
+
const copilotEvent = process.argv[2] || ''
|
|
2098
|
+
|
|
2099
|
+
// ownGet, not a bare lookup: the map is a plain object literal, so eight keys it never declares ('constructor', 'toString', '__proto__' and the rest of Object.prototype) come back truthy and sail past the check below. tgEvent is then a Function, and 'token-goat hook ' + tgEvent is concatenated into a shell command string by the fallback at the bottom of this shim. No member of Object.prototype stringifies with a shell metacharacter, so this was a failed spawn rather than a second command -- but argv reaching a shell string through a gate that reads like it stops it is the shape worth closing, not the payload that happened to be harmless. The four shims built on shim_common.ts validate against a closed Set, which has no equivalent hole.
|
|
2100
|
+
const vscodeOnly = ownGet(VSCODE_ONLY_TO_TG_EVENT, copilotEvent)
|
|
2101
|
+
const tgEvent = ownGet(COPILOT_TO_TG_EVENT, copilotEvent) || vscodeOnly
|
|
2102
|
+
if (!tgEvent) {
|
|
2103
|
+
process.stdout.write('{}')
|
|
2104
|
+
return
|
|
2105
|
+
}
|
|
2106
|
+
|
|
2107
|
+
let raw = ''
|
|
2108
|
+
try {
|
|
2109
|
+
raw = require('node:fs').readFileSync(0, 'utf8')
|
|
2110
|
+
} catch {
|
|
2111
|
+
process.stdout.write('{}')
|
|
2112
|
+
return
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
let payload
|
|
2116
|
+
try {
|
|
2117
|
+
payload = JSON.parse(raw)
|
|
2118
|
+
} catch {
|
|
2119
|
+
process.stdout.write('{}')
|
|
2120
|
+
return
|
|
2121
|
+
}
|
|
2122
|
+
|
|
2123
|
+
if (isVscodePayload(payload)) {
|
|
2124
|
+
process.stdout.write(await relayVscode(process.argv[3], tgEvent, payload))
|
|
2125
|
+
return
|
|
2126
|
+
}
|
|
2127
|
+
if (vscodeOnly) {
|
|
2128
|
+
process.stdout.write('{}')
|
|
2129
|
+
return
|
|
2130
|
+
}
|
|
2131
|
+
|
|
2132
|
+
const toolName = payload && payload.toolName
|
|
2133
|
+
const canonical = {
|
|
2134
|
+
session_id:
|
|
2135
|
+
(payload && payload.sessionId) ||
|
|
2136
|
+
stableFallbackSessionId(payload && (payload.workingDirectory || payload.cwd)),
|
|
2137
|
+
cwd: payload && (payload.workingDirectory || payload.cwd),
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
// Subagent correlation and W3C Trace Context propagation from Copilot CLI payloads
|
|
2141
|
+
const agentId = payload && (payload.agent_id || payload.agentId)
|
|
2142
|
+
if (typeof agentId === 'string' && agentId !== '') {
|
|
2143
|
+
canonical.agent_id = agentId
|
|
2144
|
+
}
|
|
2145
|
+
const traceparent = payload && (payload.traceparent || payload.traceParent)
|
|
2146
|
+
if (typeof traceparent === 'string' && traceparent !== '') {
|
|
2147
|
+
canonical.traceparent = traceparent
|
|
2148
|
+
}
|
|
2149
|
+
const tracestate = payload && (payload.tracestate || payload.traceState)
|
|
2150
|
+
if (typeof tracestate === 'string' && tracestate !== '') {
|
|
2151
|
+
canonical.tracestate = tracestate
|
|
2152
|
+
}
|
|
2153
|
+
|
|
2154
|
+
// userPromptSubmitted only: Copilot declares \`prompt\` required on UserPromptSubmittedHookInput.
|
|
2155
|
+
// hooks_session.ts's userPromptSubmitHandler reads it as \`event.raw['prompt']\` and gates every
|
|
2156
|
+
// branch it has on the text, so without this it saw '' on every Copilot prompt and the
|
|
2157
|
+
// embedded-skill dedup hint could never fire. Same shape as the postToolUseFailure \`error\`
|
|
2158
|
+
// drop: a required field the canonical builder simply did not list.
|
|
2159
|
+
if (typeof (payload && payload.prompt) === 'string' && payload.prompt !== '') {
|
|
2160
|
+
canonical.prompt = payload.prompt
|
|
2161
|
+
}
|
|
2162
|
+
// subagentStop only: the subagent's final answer arrives as response (Copilot CLI 1.0.88,
|
|
2163
|
+
// tg-captures C4a-013). Forwarded under Claude Code's name for the same text,
|
|
2164
|
+
// last_assistant_message, which both subagent_stop handlers read. Unforwarded, they saw ''.
|
|
2165
|
+
if (typeof (payload && payload.response) === 'string' && payload.response !== '') {
|
|
2166
|
+
canonical.last_assistant_message = payload.response
|
|
2167
|
+
}
|
|
2168
|
+
let originalToolArgs = {}
|
|
2169
|
+
if (toolName) {
|
|
2170
|
+
originalToolArgs = parseMaybeJsonObject(payload && payload.toolArgs)
|
|
2171
|
+
canonical.tool_name = resolveCanonicalToolName(toolName)
|
|
2172
|
+
canonical.tool_input = remapToolInput(toolName, originalToolArgs)
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
// postToolUse only: confirmed via https://docs.github.com/en/copilot/reference/hooks-reference
|
|
2176
|
+
// that Copilot's toolResult is an object ({resultType, textResultForLlm}), not a bare string
|
|
2177
|
+
// or array. Without this, token-goat's tool_response consumers (hooks_read.ts's
|
|
2178
|
+
// extractReadOutput, hooks_bash.ts's extractBashOutput, etc. -- all of which check for a
|
|
2179
|
+
// string or an object keyed by output/content/text/body) never see any content, so
|
|
2180
|
+
// post-read/post-bash stats stay empty no matter how many tool calls happen. Extract the
|
|
2181
|
+
// LLM-facing text directly rather than forwarding the raw object, since textResultForLlm
|
|
2182
|
+
// isn't one of those recognized object keys.
|
|
2183
|
+
// postToolUseFailure only: Copilot's PostToolUseFailureHookInput (copilot-sdk/types.d.ts:1042)
|
|
2184
|
+
// carries {toolName, toolArgs, error} and no toolResult at all -- the failure text lives in
|
|
2185
|
+
// \`error\`, a plain string. Without forwarding it, hooks_tool_failure.ts's extractFailureText
|
|
2186
|
+
// finds nothing to key on and the repeat-failure brake returns pass on every single call: wired,
|
|
2187
|
+
// green, and doing nothing. Found by driving the installed shim rather than by a test, because
|
|
2188
|
+
// the handler's own tests hand it a raw payload that already has the field.
|
|
2189
|
+
if (typeof (payload && payload.error) === 'string' && payload.error !== '') {
|
|
2190
|
+
canonical.error = payload.error
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
const rawResult = payload && payload.toolResult
|
|
2194
|
+
if (rawResult && typeof rawResult === 'object') {
|
|
2195
|
+
const tr = rawResult
|
|
2196
|
+
// text_result_for_llm: Copilot's docs also describe a "VS Code compatible" snake_case
|
|
2197
|
+
// wire format (tool_result.text_result_for_llm) alongside the camelCase one above; try
|
|
2198
|
+
// both rather than assuming only the camelCase shape ever reaches this shim.
|
|
2199
|
+
const text = typeof tr.textResultForLlm === 'string' ? tr.textResultForLlm : tr.text_result_for_llm
|
|
2200
|
+
if (typeof text === 'string') canonical.tool_response = text
|
|
2201
|
+
}
|
|
2202
|
+
|
|
2203
|
+
// process.argv[3], when present, is the absolute path to the token-goat CLI entry that ran
|
|
2204
|
+
// \`token-goat install --copilot\` (baked in by hookCommandFor in copilot_cli_install.ts).
|
|
2205
|
+
// Invoking it directly via process.execPath sidesteps PATH/cmd.exe resolution for this
|
|
2206
|
+
// inner call too -- confirmed live-production root cause of an *intermittent* (not the
|
|
2207
|
+
// original, already-fixed github/copilot-cli#4001) "(hook errored)" deny-all: even once the
|
|
2208
|
+
// outer command launches via its own baked process.execPath, this inner call still shelled
|
|
2209
|
+
// out to a bare \`token-goat\`, which depends on the npm global bin being on whatever PATH
|
|
2210
|
+
// Copilot spawns this hook subprocess with. Falls back to the old PATH-based shell:true
|
|
2211
|
+
// invocation when argv[3] is absent (an older cached hook config still pointing at a
|
|
2212
|
+
// freshly-reinstalled shim, or a direct dev/test invocation), so this is a pure hardening,
|
|
2213
|
+
// never a behavior break for configs installed before this fix. An args array (not a
|
|
2214
|
+
// template string) is safe here specifically because entryPath and tgEvent never touch a
|
|
2215
|
+
// shell -- no DEP0190 concern, unlike the shell:true fallback below.
|
|
2216
|
+
const entryPath = process.argv[3]
|
|
2217
|
+
// Try the in-process hook lib first (tryInProcess above), which avoids spawning a
|
|
2218
|
+
// second node process altogether. If that's unavailable, invoking the entry directly
|
|
2219
|
+
// via process.execPath sidesteps PATH/cmd.exe resolution for this inner call, per the
|
|
2220
|
+
// note above this function's original single-spawn form documented. A 3000ms
|
|
2221
|
+
// timeout/killSignal on both spawnSync fallbacks keeps them well under Copilot CLI's
|
|
2222
|
+
// own hook timeout budget (~30000ms), so token-goat degrades to its own fail-open
|
|
2223
|
+
// '{}' rather than being force-killed by Copilot first.
|
|
2224
|
+
let stdout = await tryInProcess(entryPath, tgEvent, canonical, 'copilot_cli')
|
|
2225
|
+
if (stdout === undefined) {
|
|
2226
|
+
const res = entryPath
|
|
2227
|
+
? spawnSync(process.execPath, [entryPath, 'hook', tgEvent], {
|
|
2228
|
+
input: JSON.stringify(canonical),
|
|
2229
|
+
encoding: 'utf8',
|
|
2230
|
+
windowsHide: true,
|
|
2231
|
+
timeout: 3000,
|
|
2232
|
+
killSignal: 'SIGKILL',
|
|
2233
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
2234
|
+
env: Object.assign({}, process.env, { TOKEN_GOAT_HARNESS_OVERRIDE: 'copilot_cli', TOKEN_GOAT_COPILOT_HOOKS_DIR: __dirname }),
|
|
2235
|
+
})
|
|
2236
|
+
: spawnSync('token-goat hook ' + tgEvent, {
|
|
2237
|
+
input: JSON.stringify(canonical),
|
|
2238
|
+
encoding: 'utf8',
|
|
2239
|
+
shell: true,
|
|
2240
|
+
windowsHide: true,
|
|
2241
|
+
timeout: 3000,
|
|
2242
|
+
killSignal: 'SIGKILL',
|
|
2243
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
2244
|
+
env: Object.assign({}, process.env, { TOKEN_GOAT_HARNESS_OVERRIDE: 'copilot_cli', TOKEN_GOAT_COPILOT_HOOKS_DIR: __dirname }),
|
|
2245
|
+
})
|
|
2246
|
+
if (res.status !== 0 || !res.stdout) {
|
|
2247
|
+
process.stdout.write('{}')
|
|
2248
|
+
return
|
|
2249
|
+
}
|
|
2250
|
+
stdout = res.stdout
|
|
2251
|
+
}
|
|
2252
|
+
|
|
2253
|
+
let resp
|
|
2254
|
+
try {
|
|
2255
|
+
resp = JSON.parse(stdout)
|
|
2256
|
+
} catch {
|
|
2257
|
+
process.stdout.write('{}')
|
|
2258
|
+
return
|
|
2259
|
+
}
|
|
2260
|
+
|
|
2261
|
+
process.stdout.write(JSON.stringify(translate(copilotEvent, resp, toolName, originalToolArgs)))
|
|
2262
|
+
}
|
|
2263
|
+
|
|
2264
|
+
${MATERIALIZE_SHRUNK_IMAGE_JS}
|
|
2265
|
+
|
|
2266
|
+
function translate(copilotEvent, resp, toolName, originalToolArgs) {
|
|
2267
|
+
if (copilotEvent === 'preToolUse') {
|
|
2268
|
+
const hso = resp && resp.hookSpecificOutput
|
|
2269
|
+
const denied = resp && (resp.decision === 'block' || (hso && hso.permissionDecision === 'deny'))
|
|
2270
|
+
if (denied) {
|
|
2271
|
+
const reason =
|
|
2272
|
+
(resp && resp.reason) || (hso && hso.permissionDecisionReason) || 'blocked by token-goat'
|
|
2273
|
+
return { permissionDecision: 'deny', permissionDecisionReason: reason }
|
|
2274
|
+
}
|
|
2275
|
+
const context = extractContext(resp)
|
|
2276
|
+
// A shrink payload is a base64 data URL, not prose. It rides the same additionalContext field every other pre-tool hint does, so the two have to be told apart before either is forwarded: handing the model a data URL would cost far more context than the image it was shrunk from ever did. It is only ever materialized to a temp file the read argument is pointed at.
|
|
2277
|
+
const shrinkPayload = typeof context === 'string' && context.indexOf('data:image/') !== -1
|
|
2278
|
+
const out = {}
|
|
2279
|
+
const updated = hso && hso.updatedInput
|
|
2280
|
+
if (updated && typeof updated === 'object') {
|
|
2281
|
+
out.modifiedArgs = updated
|
|
2282
|
+
} else if (shrinkPayload && (toolName === 'view' || foldToolName(toolName) === 'view')) {
|
|
2283
|
+
// modifiedArgs REPLACES the tool call's args wholesale (ESr in the 1.0.80 bundle, see this module's header docblock), so the full original toolArgs are spread and only Copilot's own path key is swapped.
|
|
2284
|
+
const shrunkPath = materializeShrunkImage(context)
|
|
2285
|
+
if (shrunkPath) out.modifiedArgs = Object.assign({}, originalToolArgs, { path: shrunkPath })
|
|
2286
|
+
}
|
|
2287
|
+
// Every pre-tool hint token-goat emits -- read-dedup nudges, the bash surgical-read advisories, the write-path notices -- used to stop here, on the stated grounds that Copilot's preToolUse output schema has no additionalContext field. It has one, and has had one for every version this bridge was ever checked against: copilot-sdk/types.d.ts declares additionalContext as an optional string on PreToolUseHookOutput in 1.0.80, 1.0.82, 1.0.86, 1.0.87 and 1.0.88 alike, and the 1.0.88 native runtime (prebuilds/win32-x64/runtime.node) carries it in the preToolUse response key list beside the three keys already known to work -- permissionDecision, permissionDecisionReason, modifiedArgs, additionalContext, in that order, immediately before "preToolUse hook timed out; allowing the tool call to proceed". The same binary carries an aggregation limit message naming the field generically ("Ignoring additionalContext returned by a ... hook because aggregating it would exceed the ... byte limit"), which is the mechanism 1.0.88's own release note calls combining contributions within a limit. Forwarded alongside modifiedArgs rather than instead of it: the schema accepts both, and a rewritten argument is no reason to drop the sentence explaining it.
|
|
2288
|
+
if (context && !shrinkPayload) out.additionalContext = context
|
|
2289
|
+
return out
|
|
2290
|
+
}
|
|
2291
|
+
|
|
2292
|
+
if (copilotEvent === 'postToolUse') {
|
|
2293
|
+
// Each field carries one thing. modifiedResult replaces the tool output, so it is sent only for a real rewrite (compression, fencing, image shrink). additionalContext carries the hint: Copilot CLI 1.0.88 appends it to the tool output itself, under the heading Tool "<name>" succeeded. Additional guidance from postToolUse hooks:, followed by the text, once (captured on the wire, tg-captures C1a; with a modifiedResult alongside, C1c, each arrives once). This branch used to also fold the hint into modifiedResult, on a 1.0.80 reading that additionalContext was dropped here, so on 1.0.88 the model got every post-tool hint twice.
|
|
2294
|
+
const hso = resp && resp.hookSpecificOutput
|
|
2295
|
+
const updatedToolOutput = hso && hso.updatedToolOutput
|
|
2296
|
+
const context = extractContext(resp)
|
|
2297
|
+
const out = {}
|
|
2298
|
+
if (typeof updatedToolOutput === 'string') out.modifiedResult = { resultType: 'success', textResultForLlm: updatedToolOutput }
|
|
2299
|
+
if (context) out.additionalContext = context
|
|
2300
|
+
return out
|
|
2301
|
+
}
|
|
2302
|
+
|
|
2303
|
+
if (copilotEvent === 'postToolUseFailure') {
|
|
2304
|
+
// The failed-tool twin of postToolUse, and the only response field it accepts is
|
|
2305
|
+
// additionalContext: the shipped copilot-sdk/types.d.ts says "modifiedResult or suppressOutput
|
|
2306
|
+
// are not honored for failure hooks", so nothing here can fence, compress or shrink the failed
|
|
2307
|
+
// output -- that gap is real and stays open. What is NOT open, and was the reason this event
|
|
2308
|
+
// went unwired for so long, is whether additionalContext reaches the model at all. It does:
|
|
2309
|
+
// app.js 1.0.80 at offset 2043380 either folds it into textResultForLlm (when
|
|
2310
|
+
// appendFailureContextToToolResult is set) or has the native
|
|
2311
|
+
// hookAppendPostToolUseFailureContext push {content, source:'system'} onto
|
|
2312
|
+
// toolResult.newMessages. That is the exact opposite of postToolUse, whose additionalContext
|
|
2313
|
+
// the JS side drops on the floor, so neither event's behaviour generalises to the other.
|
|
2314
|
+
//
|
|
2315
|
+
// Because this channel spends tokens rather than saving them, the handler behind it
|
|
2316
|
+
// (hooks_tool_failure.ts) is silent on a first failure and speaks only on an exact repeat.
|
|
2317
|
+
const context = extractContext(resp)
|
|
2318
|
+
if (context) return { additionalContext: context }
|
|
2319
|
+
return {}
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
if (copilotEvent === 'sessionStart' || copilotEvent === 'subagentStart') {
|
|
2323
|
+
// Neither event has a tool result to modify, so only additionalContext applies. sessionStart's
|
|
2324
|
+
// is the one channel that reaches the model before it picks its first read tool, so the routing
|
|
2325
|
+
// reminder lands there. subagentStart's is prepended to the subagent's own prompt (Copilot CLI
|
|
2326
|
+
// 1.0.88, capture C4a), which is where the spawn briefing belongs.
|
|
2327
|
+
const context = extractContext(resp)
|
|
2328
|
+
if (context) return { additionalContext: context }
|
|
2329
|
+
return {}
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
if (copilotEvent === 'agentStop' || copilotEvent === 'subagentStop') {
|
|
2333
|
+
// Confirmed against the hooks reference doc: the only accepted response
|
|
2334
|
+
// shape for these two events is {decision, reason} -- additionalContext
|
|
2335
|
+
// is not part of their schema and Copilot silently ignores it there.
|
|
2336
|
+
// token-goat's internal 'stop'/'subagent_stop' handlers never return a
|
|
2337
|
+
// real deny today (subagentStopHandler only ever logs and passes), but a
|
|
2338
|
+
// future deny is mapped through here rather than silently dropped.
|
|
2339
|
+
if (resp && resp.decision === 'block') {
|
|
2340
|
+
const reason = (resp && resp.reason) || 'blocked by token-goat'
|
|
2341
|
+
return { decision: 'block', reason: reason }
|
|
2342
|
+
}
|
|
2343
|
+
// subagentStop also takes modifiedResponse, which replaces the subagent's answer in the
|
|
2344
|
+
// parent's task result and in the model request built from it (Copilot CLI 1.0.88,
|
|
2345
|
+
// tg-captures C4a: the marker a hook returned there was all the parent's model saw).
|
|
2346
|
+
const stopHso = resp && resp.hookSpecificOutput
|
|
2347
|
+
const modifiedResponse = stopHso && stopHso.updatedToolOutput
|
|
2348
|
+
if (copilotEvent === 'subagentStop' && typeof modifiedResponse === 'string') {
|
|
2349
|
+
return { modifiedResponse: modifiedResponse }
|
|
2350
|
+
}
|
|
2351
|
+
return { decision: 'allow' }
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
if (copilotEvent === 'userPromptSubmitted') {
|
|
2355
|
+
// Copilot's own hooks reference says command-hook output here "is dropped, including
|
|
2356
|
+
// modifiedPrompt", and this branch used to believe it and return nothing. That is wrong for
|
|
2357
|
+
// additionalContext on 1.0.80, established by experiment rather than by reading: a config-file
|
|
2358
|
+
// command hook (at <cwd>/.github/hooks/, the project scope -- the user scope ~/.copilot/hooks/
|
|
2359
|
+
// was never exercised) returned {"additionalContext":"<marker>"} and the marker turned up
|
|
2360
|
+
// verbatim inside the session's user.message.transformedContent, wrapped in a
|
|
2361
|
+
// <system_reminder> block. What settles that it reached the model rather than only the on-disk
|
|
2362
|
+
// record is the billing: the provider's returned usage charged ~140 input tokens for a turn
|
|
2363
|
+
// whose raw content field is 35 bytes, so the marker's bytes were paid for whichever field
|
|
2364
|
+
// carried them. (The weaker argument first offered for this -- that transformedContent carries
|
|
2365
|
+
// an envelope the content field lacks, 29 B vs 195 B -- was measured on the control turn that
|
|
2366
|
+
// had no marker in it, and proves nothing about the marker.) That the model sees it is the
|
|
2367
|
+
// whole point: hook.start/hook.end records also persist and reach nothing.
|
|
2368
|
+
//
|
|
2369
|
+
// On 1.0.80 that was demonstrated once: of two turns, one delivered the marker and one fired
|
|
2370
|
+
// a hook that never ran the script. On 1.0.88 it held 5 times in 5 clean runs (tg-captures
|
|
2371
|
+
// C3): each wire request carried the context once, in the user message itself, as the prompt,
|
|
2372
|
+
// a blank line, and the context inside a <system_reminder> block.
|
|
2373
|
+
//
|
|
2374
|
+
// modifiedPrompt is NOT claimed to work and is not wanted: rewriting a user's prompt is far
|
|
2375
|
+
// more invasive than anything token-goat does, so only additionalContext is forwarded.
|
|
2376
|
+
//
|
|
2377
|
+
// This is also where the compaction manifest reaches the model. Copilot has no postCompact
|
|
2378
|
+
// hook and does not read preCompact's answer (below), so token-goat queues the manifest at
|
|
2379
|
+
// preCompact and the prompt handler puts it first in this answer on the next prompt
|
|
2380
|
+
// (PRE_COMPACT_RESUMES_ON_PROMPT in ../harness_channels.ts; tests/copilot_compaction_resume.test.ts
|
|
2381
|
+
// drives the captured C7 payloads through this shim). Whether the summary is recoverable from
|
|
2382
|
+
// events.jsonl is still not settled; see COPILOT_NO_POST_COMPACT_REASON in ../bridges_status.ts.
|
|
2383
|
+
const context = extractContext(resp)
|
|
2384
|
+
if (context) return { additionalContext: context }
|
|
2385
|
+
return {}
|
|
2386
|
+
}
|
|
2387
|
+
|
|
2388
|
+
// preCompact is the genuine notification-only case. The hooks reference marks it "No --
|
|
2389
|
+
// notification only", both preCompact call sites in app.js (1.0.79, re-checked in 1.0.80) await
|
|
2390
|
+
// the hook and never assign its result, and on 1.0.88 a marker returned here as
|
|
2391
|
+
// additionalContext appeared zero times in the wire requests, the OTel spans and the model's
|
|
2392
|
+
// reply after a manual /compact (tg-captures C7 and C7d). The payload is {sessionId, timestamp,
|
|
2393
|
+
// cwd, transcriptPath, trigger, customInstructions}. There is no field to aim at here.
|
|
2394
|
+
return {}
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2397
|
+
function extractContext(resp) {
|
|
2398
|
+
const hso = resp && resp.hookSpecificOutput
|
|
2399
|
+
if (hso && typeof hso.additionalContext === 'string') return hso.additionalContext
|
|
2400
|
+
if (resp && typeof resp.systemMessage === 'string') return resp.systemMessage
|
|
2401
|
+
return undefined
|
|
2402
|
+
}
|
|
2403
|
+
|
|
2404
|
+
// Hard outer safety net, on top of main()'s own per-step try/catch fallbacks
|
|
2405
|
+
// (JSON.parse, readFileSync, spawnSync): a hook error must never itself cause
|
|
2406
|
+
// Copilot's fail-closed "(hook errored)" behavior, which denies EVERY tool
|
|
2407
|
+
// call unconditionally (the exact live-production failure mode behind
|
|
2408
|
+
// github/copilot-cli#4001). Any uncaught exception anywhere in this script --
|
|
2409
|
+
// including one a future code path adds that the existing per-step guards
|
|
2410
|
+
// don't anticipate -- still guarantees stdout gets valid JSON and the
|
|
2411
|
+
// process exits 0. process.exitCode is set explicitly and unconditionally at
|
|
2412
|
+
// the very end of every path so nothing upstream (e.g. an unhandled-rejection
|
|
2413
|
+
// warning in some Node versions nudging exit-code inference) can flip it.
|
|
2414
|
+
main()
|
|
2415
|
+
.catch(() => {
|
|
2416
|
+
try {
|
|
2417
|
+
process.stdout.write('{}')
|
|
2418
|
+
} catch {
|
|
2419
|
+
// stdout itself is broken; nothing more can be done here.
|
|
2420
|
+
}
|
|
2421
|
+
})
|
|
2422
|
+
.finally(() => {
|
|
2423
|
+
process.exitCode = 0
|
|
2424
|
+
})
|
|
2425
|
+
`;
|
|
2426
|
+
var TOOL_TO_TG_MAPPING = COPILOT_CLI_TOOL_NAME_MAP;
|
|
2427
|
+
var FOLDED_MAPPING = {};
|
|
2428
|
+
for (const [k, v] of Object.entries(TOOL_TO_TG_MAPPING)) {
|
|
2429
|
+
FOLDED_MAPPING[foldToolName(k)] = v;
|
|
2430
|
+
FOLDED_MAPPING[foldToolName(v)] = v;
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
// src/bridges/copilot_cli_install.ts
|
|
2434
|
+
init_define_import_meta_env();
|
|
2435
|
+
import * as fs7 from "node:fs";
|
|
2436
|
+
import * as path7 from "node:path";
|
|
2437
|
+
|
|
2438
|
+
// src/bridges/copilot_mcp_install.ts
|
|
2439
|
+
init_define_import_meta_env();
|
|
2440
|
+
import * as fs5 from "node:fs";
|
|
2441
|
+
import * as path5 from "node:path";
|
|
2442
|
+
|
|
2443
|
+
// src/bridges/mcp_servers_json.ts
|
|
2444
|
+
init_define_import_meta_env();
|
|
2445
|
+
import * as fs4 from "node:fs";
|
|
2446
|
+
import * as path4 from "node:path";
|
|
2447
|
+
import { fileURLToPath } from "node:url";
|
|
2448
|
+
function bundledCliPath() {
|
|
2449
|
+
const here = path4.dirname(fileURLToPath(import.meta.url));
|
|
2450
|
+
const bundled = path4.join(here, "token-goat.mjs");
|
|
2451
|
+
if (fs4.existsSync(bundled)) return bundled;
|
|
2452
|
+
return path4.resolve(here, "..", "..", "dist", "token-goat.mjs");
|
|
2453
|
+
}
|
|
2454
|
+
function managedServer() {
|
|
2455
|
+
return {
|
|
2456
|
+
type: "stdio",
|
|
2457
|
+
command: process.execPath,
|
|
2458
|
+
args: [bundledCliPath(), "mcp-serve"]
|
|
2459
|
+
};
|
|
2460
|
+
}
|
|
2461
|
+
function isManagedServer(value) {
|
|
2462
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
2463
|
+
const entry = value;
|
|
2464
|
+
const args = entry["args"];
|
|
2465
|
+
return entry["type"] === "stdio" && Array.isArray(args) && args.length === 2 && typeof args[0] === "string" && path4.basename(args[0]).toLowerCase() === "token-goat.mjs" && args[1] === "mcp-serve";
|
|
2466
|
+
}
|
|
2467
|
+
function readServersJson(filePath, label) {
|
|
2468
|
+
const text = fs4.existsSync(filePath) ? stripBom(fs4.readFileSync(filePath, "utf8")) : "{}\n";
|
|
2469
|
+
const errors = [];
|
|
2470
|
+
const parsed = jsonc().parse(text, errors, { allowTrailingComma: true, disallowComments: false });
|
|
2471
|
+
if (errors.length > 0) {
|
|
2472
|
+
throw new Error(`malformed ${label} MCP JSON at ${filePath}`);
|
|
2473
|
+
}
|
|
2474
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
2475
|
+
throw new Error(`malformed ${label} MCP JSON at ${filePath}: expected a JSON object`);
|
|
2476
|
+
}
|
|
2477
|
+
return { text, value: parsed };
|
|
2478
|
+
}
|
|
2479
|
+
function serversOf(config, filePath, label, rootKey = "servers") {
|
|
2480
|
+
const servers = config.value[rootKey];
|
|
2481
|
+
if (servers === void 0) return {};
|
|
2482
|
+
if (servers === null || typeof servers !== "object" || Array.isArray(servers)) {
|
|
2483
|
+
throw new Error(`malformed ${label} MCP JSON at ${filePath}: ${rootKey} must be an object`);
|
|
2484
|
+
}
|
|
2485
|
+
return servers;
|
|
2486
|
+
}
|
|
2487
|
+
var FORMAT = { insertSpaces: true, tabSize: 2, eol: "\n" };
|
|
2488
|
+
function editAt(text, jsonPath, value) {
|
|
2489
|
+
let out = text;
|
|
2490
|
+
for (const e of [...jsonc().modify(text, jsonPath, value, {})].sort((a, b) => b.offset - a.offset)) {
|
|
2491
|
+
out = out.slice(0, e.offset) + e.content + out.slice(e.offset + e.length);
|
|
2492
|
+
if (e.content.length > 0) out = jsonc().applyEdits(out, jsonc().format(out, { offset: e.offset, length: e.content.length }, FORMAT));
|
|
2493
|
+
}
|
|
2494
|
+
return out;
|
|
2495
|
+
}
|
|
2496
|
+
function setTokenGoatServer(text, value, rootKey = "servers") {
|
|
2497
|
+
if (value !== void 0 && /^\s*\{\s*\}\s*$/.test(text)) return `${JSON.stringify({ [rootKey]: { "token-goat": value } }, null, 2)}
|
|
2498
|
+
`;
|
|
2499
|
+
return editAt(text, [rootKey, "token-goat"], value);
|
|
2500
|
+
}
|
|
2501
|
+
function holdsOnlyManagedServer(value) {
|
|
2502
|
+
const keys = Object.keys(value);
|
|
2503
|
+
if (keys.length !== 1) return false;
|
|
2504
|
+
const root = keys[0];
|
|
2505
|
+
if (root !== "servers" && root !== "mcpServers") return false;
|
|
2506
|
+
const servers = value[root];
|
|
2507
|
+
if (servers === null || typeof servers !== "object" || Array.isArray(servers)) return false;
|
|
2508
|
+
const names = Object.keys(servers);
|
|
2509
|
+
return names.length === 1 && names[0] === "token-goat" && isManagedServer(servers["token-goat"]);
|
|
2510
|
+
}
|
|
2511
|
+
function isResidueServersJson(text, rootKey = "servers") {
|
|
2512
|
+
const trimmed = text.trim();
|
|
2513
|
+
if (trimmed === "") return true;
|
|
2514
|
+
const parsed = parseObject(trimmed);
|
|
2515
|
+
if (parsed === null) return false;
|
|
2516
|
+
const keys = Object.keys(parsed);
|
|
2517
|
+
if (keys.length !== 1 || keys[0] !== rootKey) return false;
|
|
2518
|
+
const servers = parsed[rootKey];
|
|
2519
|
+
return servers !== null && typeof servers === "object" && !Array.isArray(servers) && Object.keys(servers).length === 0;
|
|
2520
|
+
}
|
|
2521
|
+
function noteRootKeyCreation(filePath, config, rootKey = "servers") {
|
|
2522
|
+
if (config.value[rootKey] === void 0) recordCreatedRootKey(filePath, rootKey);
|
|
2523
|
+
}
|
|
2524
|
+
function dropEmptyServers(text, filePath, rootKey = "servers") {
|
|
2525
|
+
const owned = takeCreatedRootKey(filePath, rootKey) || hasCreatedConfig(filePath);
|
|
2526
|
+
const parsed = parseObject(text);
|
|
2527
|
+
if (!owned || parsed === null) return text;
|
|
2528
|
+
const servers = parsed[rootKey];
|
|
2529
|
+
if (servers === null || typeof servers !== "object" || Array.isArray(servers) || Object.keys(servers).length > 0) return text;
|
|
2530
|
+
return editAt(text, [rootKey], void 0);
|
|
2531
|
+
}
|
|
2532
|
+
function parseObject(text) {
|
|
2533
|
+
const parsed = jsonc().parse(text, [], { allowTrailingComma: true, disallowComments: false });
|
|
2534
|
+
return parsed === null || typeof parsed !== "object" || Array.isArray(parsed) ? null : parsed;
|
|
2535
|
+
}
|
|
2536
|
+
function ensureMcpServersKey(text) {
|
|
2537
|
+
const parsed = parseObject(text);
|
|
2538
|
+
if (parsed === null || "mcpServers" in parsed) return text;
|
|
2539
|
+
return editAt(text, ["mcpServers"], {});
|
|
2540
|
+
}
|
|
2541
|
+
function dropLoneEmptyMcpServers(text) {
|
|
2542
|
+
const parsed = parseObject(text);
|
|
2543
|
+
if (parsed === null || Object.keys(parsed).length !== 1) return text;
|
|
2544
|
+
const mcpServers = parsed["mcpServers"];
|
|
2545
|
+
if (mcpServers === null || typeof mcpServers !== "object" || Array.isArray(mcpServers) || Object.keys(mcpServers).length > 0) return text;
|
|
2546
|
+
return editAt(text, ["mcpServers"], void 0);
|
|
2547
|
+
}
|
|
2548
|
+
function managedServerEntry(filePath, label, rootKey = "servers", isManaged = isManagedServer) {
|
|
2549
|
+
if (!fs4.existsSync(filePath)) return null;
|
|
2550
|
+
try {
|
|
2551
|
+
const entry = serversOf(readServersJson(filePath, label), filePath, label, rootKey)["token-goat"];
|
|
2552
|
+
return isManaged(entry) ? entry : null;
|
|
2553
|
+
} catch {
|
|
2554
|
+
return null;
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
function hasManagedServer(filePath, label, rootKey = "servers", isManaged = isManagedServer) {
|
|
2558
|
+
return managedServerEntry(filePath, label, rootKey, isManaged) !== null;
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
// src/bridges/copilot_mcp_install.ts
|
|
2562
|
+
var MCP_SERVERS_KEY = "mcpServers";
|
|
2563
|
+
var TOKEN_GOAT_ENTRY_KEY = "token-goat";
|
|
2564
|
+
var LABEL = "Copilot CLI";
|
|
2565
|
+
function copilotMcpConfigPath() {
|
|
2566
|
+
return path5.join(copilotCliUserRoot(), "mcp-config.json");
|
|
2567
|
+
}
|
|
2568
|
+
function copilotManagedServer() {
|
|
2569
|
+
return { tools: ["*"], type: "local", command: process.execPath, args: [bundledCliPath(), "mcp-serve"] };
|
|
2570
|
+
}
|
|
2571
|
+
function isCopilotManagedServer(value) {
|
|
2572
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
2573
|
+
const entry = value;
|
|
2574
|
+
const args = entry["args"];
|
|
2575
|
+
return entry["type"] === "local" && typeof entry["command"] === "string" && Array.isArray(args) && args.length === 2 && typeof args[0] === "string" && path5.basename(args[0]).toLowerCase() === "token-goat.mjs" && args[1] === "mcp-serve";
|
|
2576
|
+
}
|
|
2577
|
+
function isReadmeServer(value) {
|
|
2578
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
2579
|
+
const entry = value;
|
|
2580
|
+
const args = entry["args"];
|
|
2581
|
+
return Object.keys(entry).every((k) => k === "command" || k === "args") && entry["command"] === "token-goat" && Array.isArray(args) && args.length === 1 && args[0] === "mcp-serve";
|
|
2582
|
+
}
|
|
2583
|
+
function installCopilotMcpServer() {
|
|
2584
|
+
const mcpPath = copilotMcpConfigPath();
|
|
2585
|
+
const fileExisted = fs5.existsSync(mcpPath);
|
|
2586
|
+
const config = readServersJson(mcpPath, LABEL);
|
|
2587
|
+
const current = serversOf(config, mcpPath, LABEL, MCP_SERVERS_KEY)[TOKEN_GOAT_ENTRY_KEY];
|
|
2588
|
+
if (current !== void 0 && !isCopilotManagedServer(current) && !isReadmeServer(current)) {
|
|
2589
|
+
throw new Error(`Copilot CLI mcp-config.json already has a "${TOKEN_GOAT_ENTRY_KEY}" MCP server entry token-goat did not write, at ${mcpPath}; remove it manually first`);
|
|
2590
|
+
}
|
|
2591
|
+
const nextText = setTokenGoatServer(config.text, copilotManagedServer(), MCP_SERVERS_KEY);
|
|
2592
|
+
if (nextText === config.text) return false;
|
|
2593
|
+
ensureDirSync(path5.dirname(mcpPath));
|
|
2594
|
+
if (!fileExisted) recordCreatedConfig(mcpPath);
|
|
2595
|
+
backupFile(mcpPath);
|
|
2596
|
+
writeConfigText(mcpPath, nextText);
|
|
2597
|
+
noteRootKeyCreation(mcpPath, config, MCP_SERVERS_KEY);
|
|
2598
|
+
return true;
|
|
2599
|
+
}
|
|
2600
|
+
function uninstallCopilotMcpServer() {
|
|
2601
|
+
const mcpPath = copilotMcpConfigPath();
|
|
2602
|
+
if (!fs5.existsSync(mcpPath)) return false;
|
|
2603
|
+
const config = readServersJson(mcpPath, LABEL);
|
|
2604
|
+
if (!isCopilotManagedServer(serversOf(config, mcpPath, LABEL, MCP_SERVERS_KEY)[TOKEN_GOAT_ENTRY_KEY])) return false;
|
|
2605
|
+
const next = dropEmptyServers(setTokenGoatServer(config.text, void 0, MCP_SERVERS_KEY), mcpPath, MCP_SERVERS_KEY);
|
|
2606
|
+
if (/^\s*\{\s*\}\s*$/.test(next) && takeCreatedConfig(mcpPath)) {
|
|
2607
|
+
removeFileInScope(mcpPath);
|
|
2608
|
+
} else {
|
|
2609
|
+
backupFile(mcpPath);
|
|
2610
|
+
writeConfigText(mcpPath, next);
|
|
2611
|
+
}
|
|
2612
|
+
removeCreatedBackups(mcpPath);
|
|
2613
|
+
return true;
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
// src/bridges/visualstudio_install.ts
|
|
2617
|
+
init_define_import_meta_env();
|
|
2618
|
+
import * as fs6 from "node:fs";
|
|
2619
|
+
import * as os2 from "node:os";
|
|
2620
|
+
import * as path6 from "node:path";
|
|
2621
|
+
var LABEL2 = "Visual Studio";
|
|
2622
|
+
var VISUALSTUDIO_GUIDANCE_BEGIN = "<!-- token-goat-visualstudio-begin -->";
|
|
2623
|
+
var VISUALSTUDIO_GUIDANCE_END = "<!-- token-goat-visualstudio-end -->";
|
|
2624
|
+
var SIBLING_GATE_MARKERS = [
|
|
2625
|
+
["<!-- token-goat-vscode-begin -->", "<!-- token-goat-vscode-end -->"],
|
|
2626
|
+
["<!-- token-goat-begin -->", "<!-- token-goat-end -->"]
|
|
2627
|
+
];
|
|
2628
|
+
function visualStudioUserMcpPath() {
|
|
2629
|
+
return path6.join(os2.homedir(), ".mcp.json");
|
|
2630
|
+
}
|
|
2631
|
+
function visualStudioProjectMcpPath(projectRoot = process.cwd()) {
|
|
2632
|
+
return path6.join(path6.resolve(projectRoot), ".mcp.json");
|
|
2633
|
+
}
|
|
2634
|
+
function visualStudioMcpPath(opts = {}) {
|
|
2635
|
+
return opts.project === true ? visualStudioProjectMcpPath(opts.projectRoot) : visualStudioUserMcpPath();
|
|
2636
|
+
}
|
|
2637
|
+
function otherScopeMcpPath(opts) {
|
|
2638
|
+
return opts.project === true ? visualStudioUserMcpPath() : visualStudioProjectMcpPath(opts.projectRoot);
|
|
2639
|
+
}
|
|
2640
|
+
function visualStudioInstructionsPath(opts = {}) {
|
|
2641
|
+
return opts.project === true ? path6.join(path6.resolve(opts.projectRoot ?? process.cwd()), ".github", "copilot-instructions.md") : path6.join(os2.homedir(), "copilot-instructions.md");
|
|
2642
|
+
}
|
|
2643
|
+
function visualStudioOtherScopeHasManagedServer(opts = {}) {
|
|
2644
|
+
return hasManagedServer(otherScopeMcpPath(opts), LABEL2);
|
|
2645
|
+
}
|
|
2646
|
+
function isVisualStudioInstalled(opts = {}) {
|
|
2647
|
+
return hasManagedServer(visualStudioMcpPath(opts), LABEL2);
|
|
2648
|
+
}
|
|
2649
|
+
function visualStudioSolutionVscodeMcpPath(projectRoot = process.cwd()) {
|
|
2650
|
+
return path6.join(path6.resolve(projectRoot), ".vscode", "mcp.json");
|
|
2651
|
+
}
|
|
2652
|
+
function visualStudioManagedRegistrations(projectRoot = process.cwd()) {
|
|
2653
|
+
return [visualStudioUserMcpPath(), visualStudioProjectMcpPath(projectRoot), visualStudioSolutionVscodeMcpPath(projectRoot)].filter((p) => hasManagedServer(p, LABEL2));
|
|
2654
|
+
}
|
|
2655
|
+
function visualStudioDuplicateNote(projectRoot = process.cwd()) {
|
|
2656
|
+
const found = visualStudioManagedRegistrations(projectRoot);
|
|
2657
|
+
if (found.length < 2) return null;
|
|
2658
|
+
const lead = `Note: Visual Studio reads ${found.join(" and ")}, and each registers token-goat, so it will list the token-goat server more than once for this solution.`;
|
|
2659
|
+
if (!found.includes(visualStudioSolutionVscodeMcpPath(projectRoot))) return `${lead} Keep one: run "token-goat uninstall --visualstudio" or "token-goat uninstall --visualstudio -p".`;
|
|
2660
|
+
return `${lead} Keep one: if you do not use VS Code in this folder, run "token-goat uninstall --vscode -p"; otherwise run "token-goat uninstall --visualstudio${found.includes(visualStudioUserMcpPath()) ? "" : " -p"}".`;
|
|
2661
|
+
}
|
|
2662
|
+
function visualStudioMcpStatus(opts = {}) {
|
|
2663
|
+
const checkedPaths = [visualStudioUserMcpPath()];
|
|
2664
|
+
if (opts.projectRoot !== void 0) checkedPaths.push(visualStudioProjectMcpPath(opts.projectRoot));
|
|
2665
|
+
return { configured: checkedPaths.some((p) => hasManagedServer(p, LABEL2)), checkedPaths };
|
|
2666
|
+
}
|
|
2667
|
+
function visualStudioManagedEntry(filePath) {
|
|
2668
|
+
const entry = managedServerEntry(filePath, LABEL2);
|
|
2669
|
+
if (entry === null) return null;
|
|
2670
|
+
const { command, args } = entry;
|
|
2671
|
+
return { command: typeof command === "string" ? command : "", bundlePath: args[0] ?? "" };
|
|
2672
|
+
}
|
|
2673
|
+
var FALLBACK_TOOL_CLAUSE = "Visual Studio\u2019s built-in readfile, code_search, and find_references tools";
|
|
2674
|
+
var RETRIEVE_NOTE = "**Compressed payloads:** a message containing a token-goat payload block (recognizable by a `recovery: token-goat retrieve <id>` line) is compressed text, not an answer. Call the MCP tool `retrieve_text` with that id to recover the original text, then answer the question the message asks using the recovered text. Never present the raw payload to the user as the response; if the `retrieve_text` tool is unavailable (the MCP server is not running, or its tools are not ticked in the chat Tools picker), say so plainly and ask the user to turn on the token-goat tools.";
|
|
2675
|
+
var SUPPORT_NOTE = "Visual Studio support: token-goat install --visualstudio registers a stdio MCP server under the servers root key of %USERPROFILE%\\.mcp.json (with --project, the .mcp.json in the solution folder). Visual Studio runs no token-goat hooks, so nothing denies a repeated read, adds a hint, shrinks an image, or folds what readfile returns there: the narrow reads come only from calling the token-goat MCP tools, or the token-goat CLI through runcommandinterminal.";
|
|
2676
|
+
function buildVisualStudioGuidanceBlock(sharesFileWithGate) {
|
|
2677
|
+
const lead = sharesFileWithGate ? ["## token-goat in Visual Studio", "", `The token-goat gate elsewhere in this file applies in Visual Studio too; there, ${FALLBACK_TOOL_CLAUSE} are the fallback it names.`] : [buildGuidanceBody(FALLBACK_TOOL_CLAUSE, { gdrive: loadConfig().gdrive.enabled })];
|
|
2678
|
+
return [VISUALSTUDIO_GUIDANCE_BEGIN, ...lead, "", RETRIEVE_NOTE, "", SUPPORT_NOTE, VISUALSTUDIO_GUIDANCE_END].join("\n");
|
|
2679
|
+
}
|
|
2680
|
+
function hasBlock(text, begin, end) {
|
|
2681
|
+
const b = text.indexOf(begin);
|
|
2682
|
+
const e = text.indexOf(end);
|
|
2683
|
+
return b !== -1 && e > b;
|
|
2684
|
+
}
|
|
2685
|
+
function readText(filePath) {
|
|
2686
|
+
try {
|
|
2687
|
+
return fs6.readFileSync(filePath, "utf8");
|
|
2688
|
+
} catch {
|
|
2689
|
+
return "";
|
|
2690
|
+
}
|
|
2691
|
+
}
|
|
2692
|
+
function writeGuidance(filePath) {
|
|
2693
|
+
const text = readText(filePath);
|
|
2694
|
+
const shares = SIBLING_GATE_MARKERS.some(([begin, end]) => hasBlock(text, begin, end));
|
|
2695
|
+
return upsertDelimitedBlock(filePath, VISUALSTUDIO_GUIDANCE_BEGIN, VISUALSTUDIO_GUIDANCE_END, buildVisualStudioGuidanceBlock(shares));
|
|
2696
|
+
}
|
|
2697
|
+
function syncVisualStudioProjectGuidance(filePath) {
|
|
2698
|
+
if (!hasBlock(readText(filePath), VISUALSTUDIO_GUIDANCE_BEGIN, VISUALSTUDIO_GUIDANCE_END)) return false;
|
|
2699
|
+
return writeGuidance(filePath);
|
|
2700
|
+
}
|
|
2701
|
+
function installVisualStudio(opts = {}) {
|
|
2702
|
+
return withInstallScope(projectScopeRoot(opts), () => installVisualStudioScoped(opts));
|
|
2703
|
+
}
|
|
2704
|
+
function installVisualStudioScoped(opts) {
|
|
2705
|
+
const scope = opts.project === true ? "project" : "user";
|
|
2706
|
+
const mcpPath = visualStudioMcpPath(opts);
|
|
2707
|
+
const instructionsPath = visualStudioInstructionsPath(opts);
|
|
2708
|
+
if (visualStudioOtherScopeHasManagedServer(opts)) {
|
|
2709
|
+
const otherScope = scope === "project" ? "user" : "project";
|
|
2710
|
+
throw new Error(
|
|
2711
|
+
`token-goat is already registered in Visual Studio ${otherScope} scope (${otherScopeMcpPath(opts)}). Visual Studio reads both files, so installing into ${scope} scope too would register it twice. Run "token-goat uninstall --visualstudio${otherScope === "project" ? " --project" : ""}" first if you want to move it, or drop --visualstudio from this run.`
|
|
2712
|
+
);
|
|
2713
|
+
}
|
|
2714
|
+
const mcpExisted = fs6.existsSync(mcpPath);
|
|
2715
|
+
const config = readServersJson(mcpPath, LABEL2);
|
|
2716
|
+
const ownedAlready = mcpExisted && holdsOnlyManagedServer(config.value);
|
|
2717
|
+
const current = serversOf(config, mcpPath, LABEL2)["token-goat"];
|
|
2718
|
+
if (current !== void 0 && !isManagedServer(current)) {
|
|
2719
|
+
throw new Error(`Visual Studio MCP JSON at ${mcpPath} already has a non-token-goat-managed server named "token-goat"`);
|
|
2720
|
+
}
|
|
2721
|
+
const next = ensureMcpServersKey(setTokenGoatServer(config.text, managedServer()));
|
|
2722
|
+
if (config.text !== next) {
|
|
2723
|
+
ensureDirSync(path6.dirname(mcpPath));
|
|
2724
|
+
backupFile(mcpPath);
|
|
2725
|
+
writeConfigText(mcpPath, next);
|
|
2726
|
+
noteRootKeyCreation(mcpPath, config);
|
|
2727
|
+
if (!mcpExisted || ownedAlready) recordCreatedConfig(mcpPath);
|
|
2728
|
+
}
|
|
2729
|
+
const guidanceChanged = writeGuidance(instructionsPath);
|
|
2730
|
+
return { mcpPath, instructionsPath, alreadyInstalled: config.text === next && !guidanceChanged, scope };
|
|
2731
|
+
}
|
|
2732
|
+
function uninstallVisualStudio(opts = {}) {
|
|
2733
|
+
return withInstallScope(projectScopeRoot(opts), () => uninstallVisualStudioScoped(opts));
|
|
2734
|
+
}
|
|
2735
|
+
function uninstallVisualStudioScoped(opts) {
|
|
2736
|
+
const mcpPath = visualStudioMcpPath(opts);
|
|
2737
|
+
let removed = false;
|
|
2738
|
+
if (fs6.existsSync(mcpPath)) {
|
|
2739
|
+
const config = readServersJson(mcpPath, LABEL2);
|
|
2740
|
+
if (isManagedServer(serversOf(config, mcpPath, LABEL2)["token-goat"])) {
|
|
2741
|
+
const next = dropEmptyServers(setTokenGoatServer(config.text, void 0), mcpPath);
|
|
2742
|
+
if (/^\s*\{\s*\}\s*$/.test(dropLoneEmptyMcpServers(next)) && takeCreatedConfig(mcpPath)) removeFileInScope(mcpPath);
|
|
2743
|
+
else {
|
|
2744
|
+
backupFile(mcpPath);
|
|
2745
|
+
writeConfigText(mcpPath, ensureMcpServersKey(next));
|
|
2746
|
+
}
|
|
2747
|
+
removeCreatedBackups(mcpPath);
|
|
2748
|
+
removed = true;
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2751
|
+
const instructionsPath = visualStudioInstructionsPath(opts);
|
|
2752
|
+
if (stripDelimitedBlock(instructionsPath, VISUALSTUDIO_GUIDANCE_BEGIN, VISUALSTUDIO_GUIDANCE_END)) {
|
|
2753
|
+
removed = true;
|
|
2754
|
+
if (readText(instructionsPath).trim() === "") removeFileInScope(instructionsPath);
|
|
2755
|
+
}
|
|
2756
|
+
return removed;
|
|
2757
|
+
}
|
|
2758
|
+
|
|
2759
|
+
// src/bridges/copilot_cli_install.ts
|
|
2760
|
+
var COPILOT_CLI_HOOK_EVENTS = [
|
|
2761
|
+
"sessionStart",
|
|
2762
|
+
"preToolUse",
|
|
2763
|
+
"postToolUse",
|
|
2764
|
+
"preCompact",
|
|
2765
|
+
"agentStop",
|
|
2766
|
+
"subagentStop",
|
|
2767
|
+
"userPromptSubmitted",
|
|
2768
|
+
"postToolUseFailure",
|
|
2769
|
+
"subagentStart"
|
|
2770
|
+
];
|
|
2771
|
+
var VSCODE_ONLY_HOOK_EVENTS = ["SubagentStart"];
|
|
2772
|
+
function copilotCliUserHooksDir() {
|
|
2773
|
+
return path7.join(copilotCliUserRoot(), "hooks");
|
|
2774
|
+
}
|
|
2775
|
+
function canonicalProjectRoot(projectRoot) {
|
|
2776
|
+
return process.platform === "win32" ? projectRoot.replace(/^[a-z]:/, (drive) => drive.toUpperCase()) : projectRoot;
|
|
2777
|
+
}
|
|
2778
|
+
function copilotCliProjectHooksDir(projectRoot) {
|
|
2779
|
+
return path7.join(canonicalProjectRoot(projectRoot ?? process.cwd()), ".github", "hooks");
|
|
2780
|
+
}
|
|
2781
|
+
function copilotCliHooksDir(opts = {}) {
|
|
2782
|
+
return opts.local === true ? copilotCliProjectHooksDir(opts.projectRoot) : copilotCliUserHooksDir();
|
|
2783
|
+
}
|
|
2784
|
+
function copilotCliConfigPath(opts = {}) {
|
|
2785
|
+
return path7.join(copilotCliHooksDir(opts), HOOKS_CONFIG_FILE);
|
|
2786
|
+
}
|
|
2787
|
+
function copilotCliScriptPath(opts = {}) {
|
|
2788
|
+
return path7.join(copilotCliHooksDir(opts), HOOKS_SCRIPT_FILE);
|
|
2789
|
+
}
|
|
2790
|
+
function copilotCliInstructionsPath(opts = {}) {
|
|
2791
|
+
return path7.join(path7.dirname(copilotCliHooksDir(opts)), "copilot-instructions.md");
|
|
2792
|
+
}
|
|
2793
|
+
var COPILOT_INSTRUCTIONS_BEGIN = "<!-- token-goat-begin -->";
|
|
2794
|
+
var COPILOT_INSTRUCTIONS_END = "<!-- token-goat-end -->";
|
|
2795
|
+
function buildCopilotInstructionsBlock() {
|
|
2796
|
+
return stripInlineCodeSpans(
|
|
2797
|
+
buildGuidanceBlock({
|
|
2798
|
+
beginMarker: COPILOT_INSTRUCTIONS_BEGIN,
|
|
2799
|
+
endMarker: COPILOT_INSTRUCTIONS_END,
|
|
2800
|
+
fallbackToolClause: "Copilot CLI's native `view`, `grep`, and `glob` tools (with PowerShell commands `Get-Content`/`Select-String` as search fallbacks)",
|
|
2801
|
+
gdrive: loadConfig().gdrive?.enabled ?? false
|
|
2802
|
+
})
|
|
2803
|
+
);
|
|
2804
|
+
}
|
|
2805
|
+
function stripInlineCodeSpans(text) {
|
|
2806
|
+
return text.replace(/`([^`]+)`/g, "$1");
|
|
2807
|
+
}
|
|
2808
|
+
function writeCopilotInstructionsBlock(p) {
|
|
2809
|
+
const changed = upsertDelimitedBlock(p, COPILOT_INSTRUCTIONS_BEGIN, COPILOT_INSTRUCTIONS_END, buildCopilotInstructionsBlock());
|
|
2810
|
+
const visualStudioChanged = syncVisualStudioProjectGuidance(p);
|
|
2811
|
+
return changed || visualStudioChanged;
|
|
2812
|
+
}
|
|
2813
|
+
function stripCopilotInstructionsBlock(p) {
|
|
2814
|
+
const removed = stripDelimitedBlock(p, COPILOT_INSTRUCTIONS_BEGIN, COPILOT_INSTRUCTIONS_END);
|
|
2815
|
+
if (removed) syncVisualStudioProjectGuidance(p);
|
|
2816
|
+
return removed;
|
|
2817
|
+
}
|
|
2818
|
+
function hookPowershellCommandFor(scriptPath, event) {
|
|
2819
|
+
return powershellHookLine(hookPowershellCommand(scriptPath, event));
|
|
2820
|
+
}
|
|
2821
|
+
var HOOK_TIMEOUT_SEC = 60;
|
|
2822
|
+
var ALLOWED_ENV_VARS = [
|
|
2823
|
+
"TRACEPARENT",
|
|
2824
|
+
"TRACESTATE",
|
|
2825
|
+
"COPILOT_HOME",
|
|
2826
|
+
"COPILOT_CACHE_HOME",
|
|
2827
|
+
"TOKEN_GOAT_LOG"
|
|
2828
|
+
];
|
|
2829
|
+
function copilotHookCommandsFor(scriptPath, event, opts = {}) {
|
|
2830
|
+
const bin = nativeHookBinary(process.argv[1], opts);
|
|
2831
|
+
const command = bin === void 0 ? void 0 : nativeHookCommandLine(process.platform === "win32" ? "cmd" : "sh", bin, "copilot_cli", scriptPath, event);
|
|
2832
|
+
const sh = bin === void 0 ? void 0 : nativeHookCommandLine("sh", bin, "copilot_cli", scriptPath, event);
|
|
2833
|
+
const ps = bin === void 0 ? void 0 : nativeHookCommandLine("powershell", bin, "copilot_cli", scriptPath, event);
|
|
2834
|
+
if (command !== void 0 && sh !== void 0 && ps !== void 0) return { command, bash: sh, powershell: ps };
|
|
2835
|
+
return { command: hookCommandFor(scriptPath, event), bash: hookCommandFor(scriptPath, event), powershell: hookPowershellCommandFor(scriptPath, event) };
|
|
2836
|
+
}
|
|
2837
|
+
function wiredCopilotHookWords(opts = {}) {
|
|
2838
|
+
let config;
|
|
2839
|
+
try {
|
|
2840
|
+
config = JSON.parse(stripBom(fs7.readFileSync(copilotCliConfigPath(opts), "utf8")));
|
|
2841
|
+
} catch {
|
|
2842
|
+
return [];
|
|
2843
|
+
}
|
|
2844
|
+
const scriptPath = copilotCliScriptPath(opts);
|
|
2845
|
+
const out = [];
|
|
2846
|
+
for (const [event, entries] of Object.entries(config?.hooks ?? {})) {
|
|
2847
|
+
const known = COPILOT_CLI_HOOK_EVENTS.includes(event) || VSCODE_ONLY_HOOK_EVENTS.includes(event);
|
|
2848
|
+
const expected = known ? copilotHookCommandsFor(scriptPath, event, { sync: false }) : void 0;
|
|
2849
|
+
for (const h of Array.isArray(entries) ? entries : []) {
|
|
2850
|
+
if (typeof h?.command !== "string") continue;
|
|
2851
|
+
const current = expected !== void 0 && h.command === expected.command && h.bash === expected.bash && h.powershell === expected.powershell;
|
|
2852
|
+
out.push({ words: splitHookCommand(h.command, process.platform === "win32" ? "cmd" : "sh"), current });
|
|
2853
|
+
}
|
|
2854
|
+
}
|
|
2855
|
+
return out;
|
|
2856
|
+
}
|
|
2857
|
+
function buildConfig(scriptPath, owners) {
|
|
2858
|
+
const hooks = {};
|
|
2859
|
+
const events = owners.has("vscode") ? [...COPILOT_CLI_HOOK_EVENTS, ...VSCODE_ONLY_HOOK_EVENTS] : COPILOT_CLI_HOOK_EVENTS;
|
|
2860
|
+
for (const event of events) {
|
|
2861
|
+
hooks[event] = [
|
|
2862
|
+
{
|
|
2863
|
+
type: "command",
|
|
2864
|
+
...copilotHookCommandsFor(scriptPath, event),
|
|
2865
|
+
timeoutSec: HOOK_TIMEOUT_SEC,
|
|
2866
|
+
allowedEnvVars: [...ALLOWED_ENV_VARS]
|
|
2867
|
+
}
|
|
2868
|
+
];
|
|
2869
|
+
}
|
|
2870
|
+
return { version: 1, hooks };
|
|
2871
|
+
}
|
|
2872
|
+
var HOOKS_SCRIPT_FILE = "token-goat-shim.cjs";
|
|
2873
|
+
var LEGACY_HOOKS_SCRIPT_FILE = "token-goat-shim.js";
|
|
2874
|
+
var HOOKS_SCRIPT_FORWARDER = `#!/usr/bin/env node
|
|
2875
|
+
// Forwarder for compatibility with cached hook definitions in running Copilot CLI sessions.
|
|
2876
|
+
import('./token-goat-shim.cjs').catch(() => {
|
|
2877
|
+
try { process.stdout.write('{}') } catch {}
|
|
2878
|
+
process.exitCode = 0
|
|
2879
|
+
});
|
|
2880
|
+
`;
|
|
2881
|
+
function copilotHooksFilePaths(hooksDir) {
|
|
2882
|
+
return [
|
|
2883
|
+
path7.join(hooksDir, HOOKS_CONFIG_FILE),
|
|
2884
|
+
path7.join(hooksDir, HOOKS_SCRIPT_FILE),
|
|
2885
|
+
path7.join(hooksDir, LEGACY_HOOKS_SCRIPT_FILE),
|
|
2886
|
+
copilotHooksOwnersPath(hooksDir)
|
|
2887
|
+
];
|
|
2888
|
+
}
|
|
2889
|
+
function installCopilotHooksFile(hooksDir, owner) {
|
|
2890
|
+
const configPath = path7.join(hooksDir, HOOKS_CONFIG_FILE);
|
|
2891
|
+
const scriptPath = path7.join(hooksDir, HOOKS_SCRIPT_FILE);
|
|
2892
|
+
const legacyScriptPath = path7.join(hooksDir, LEGACY_HOOKS_SCRIPT_FILE);
|
|
2893
|
+
const owners = readCopilotHooksOwners(hooksDir);
|
|
2894
|
+
ensureDirRecordingCreation(path7.dirname(hooksDir));
|
|
2895
|
+
ensureDirRecordingCreation(hooksDir);
|
|
2896
|
+
const scriptChanged = writeIfDifferent(scriptPath, COPILOT_CLI_HOOK_SCRIPT);
|
|
2897
|
+
const legacyScriptChanged = writeIfDifferent(legacyScriptPath, HOOKS_SCRIPT_FORWARDER);
|
|
2898
|
+
owners.add(owner);
|
|
2899
|
+
const desiredText = JSON.stringify(buildConfig(scriptPath, owners), null, 2) + "\n";
|
|
2900
|
+
const configChanged = writeIfDifferent(configPath, desiredText, true);
|
|
2901
|
+
recordCreatedConfig(configPath);
|
|
2902
|
+
const ownersChanged = writeIfDifferent(copilotHooksOwnersPath(hooksDir), [...owners].sort().join("\n") + "\n");
|
|
2903
|
+
return { configPath, scriptPath, changed: scriptChanged || legacyScriptChanged || configChanged || ownersChanged };
|
|
2904
|
+
}
|
|
2905
|
+
function releaseCopilotHooksFile(hooksDir, owner, keepBackups = false) {
|
|
2906
|
+
const ownersPath = copilotHooksOwnersPath(hooksDir);
|
|
2907
|
+
const hadSidecar = fs7.existsSync(ownersPath);
|
|
2908
|
+
const owners = readCopilotHooksOwners(hooksDir);
|
|
2909
|
+
if (!owners.has(owner) && (hadSidecar || owner !== "copilot")) return false;
|
|
2910
|
+
owners.delete(owner);
|
|
2911
|
+
if (owners.size > 0) {
|
|
2912
|
+
writeIfDifferent(ownersPath, [...owners].sort().join("\n") + "\n");
|
|
2913
|
+
const configPath = path7.join(hooksDir, HOOKS_CONFIG_FILE);
|
|
2914
|
+
if (fs7.existsSync(configPath)) writeIfDifferent(configPath, JSON.stringify(buildConfig(path7.join(hooksDir, HOOKS_SCRIPT_FILE), owners), null, 2) + "\n", true);
|
|
2915
|
+
return true;
|
|
2916
|
+
}
|
|
2917
|
+
const configRemoved = removeFileInScope(path7.join(hooksDir, HOOKS_CONFIG_FILE));
|
|
2918
|
+
if (!keepBackups) removeCreatedBackups(path7.join(hooksDir, HOOKS_CONFIG_FILE));
|
|
2919
|
+
takeCreatedConfig(path7.join(hooksDir, HOOKS_CONFIG_FILE));
|
|
2920
|
+
const scriptRemoved = removeFileInScope(path7.join(hooksDir, HOOKS_SCRIPT_FILE));
|
|
2921
|
+
const legacyScriptRemoved = removeFileInScope(path7.join(hooksDir, LEGACY_HOOKS_SCRIPT_FILE));
|
|
2922
|
+
const ownersRemoved = removeFileInScope(ownersPath);
|
|
2923
|
+
removeCreatedIfEmpty(hooksDir);
|
|
2924
|
+
return configRemoved || scriptRemoved || legacyScriptRemoved || ownersRemoved;
|
|
2925
|
+
}
|
|
2926
|
+
function installCopilotCli(opts = {}) {
|
|
2927
|
+
return withInstallScope(projectScopeRoot(opts), () => installCopilotCliScoped(opts));
|
|
2928
|
+
}
|
|
2929
|
+
function installCopilotCliScoped(opts) {
|
|
2930
|
+
const instructionsPath = copilotCliInstructionsPath(opts);
|
|
2931
|
+
const userScope = opts.local !== true;
|
|
2932
|
+
const scopeDir = path7.dirname(instructionsPath);
|
|
2933
|
+
const scopeDirExisted = fs7.existsSync(scopeDir);
|
|
2934
|
+
const mcpChanged = userScope ? installCopilotMcpServer() : false;
|
|
2935
|
+
if (!scopeDirExisted && fs7.existsSync(scopeDir)) recordCreatedConfig(scopeDir);
|
|
2936
|
+
const hooks = installCopilotHooksFile(copilotCliHooksDir(opts), "copilot");
|
|
2937
|
+
const instructionsExisted = fs7.existsSync(instructionsPath);
|
|
2938
|
+
let instructionsChanged = writeCopilotInstructionsBlock(instructionsPath);
|
|
2939
|
+
if (!instructionsExisted) recordCreatedConfig(instructionsPath);
|
|
2940
|
+
if (userScope) {
|
|
2941
|
+
const projectRoot = path7.resolve(opts.projectRoot ?? process.cwd());
|
|
2942
|
+
const projectInstructions = copilotCliInstructionsPath({ local: true, projectRoot });
|
|
2943
|
+
if (fs7.existsSync(projectInstructions)) {
|
|
2944
|
+
const projectChanged = writeCopilotInstructionsBlock(projectInstructions);
|
|
2945
|
+
if (projectChanged) instructionsChanged = true;
|
|
2946
|
+
}
|
|
2947
|
+
}
|
|
2948
|
+
return {
|
|
2949
|
+
configPath: hooks.configPath,
|
|
2950
|
+
scriptPath: hooks.scriptPath,
|
|
2951
|
+
instructionsPath,
|
|
2952
|
+
...userScope ? { mcpConfigPath: copilotMcpConfigPath() } : {},
|
|
2953
|
+
alreadyInstalled: !hooks.changed && !instructionsChanged && !mcpChanged
|
|
2954
|
+
};
|
|
2955
|
+
}
|
|
2956
|
+
function uninstallCopilotCliScope(opts) {
|
|
2957
|
+
return withInstallScope(projectScopeRoot(opts), () => uninstallCopilotCliScopeInner(opts));
|
|
2958
|
+
}
|
|
2959
|
+
function uninstallCopilotCliScopeInner(opts) {
|
|
2960
|
+
let removedAny = releaseCopilotHooksFile(copilotCliHooksDir(opts), "copilot");
|
|
2961
|
+
const instructionsPath = copilotCliInstructionsPath(opts);
|
|
2962
|
+
if (stripCopilotInstructionsBlock(instructionsPath)) {
|
|
2963
|
+
removedAny = true;
|
|
2964
|
+
}
|
|
2965
|
+
removeCreatedIfEmpty(instructionsPath);
|
|
2966
|
+
if (opts.local !== true && uninstallCopilotMcpServer()) {
|
|
2967
|
+
removedAny = true;
|
|
2968
|
+
}
|
|
2969
|
+
removeCreatedIfEmpty(path7.dirname(instructionsPath));
|
|
2970
|
+
return removedAny;
|
|
2971
|
+
}
|
|
2972
|
+
function uninstallCopilotCli(opts = {}) {
|
|
2973
|
+
if (opts.local === true) {
|
|
2974
|
+
return uninstallCopilotCliScope({ local: true });
|
|
2975
|
+
}
|
|
2976
|
+
const userRemoved = uninstallCopilotCliScope({ local: false });
|
|
2977
|
+
const localRemoved = uninstallCopilotCliScope({ local: true });
|
|
2978
|
+
return userRemoved || localRemoved;
|
|
2979
|
+
}
|
|
2980
|
+
function isCopilotCliInstalled(opts = {}) {
|
|
2981
|
+
const scriptPresent = fs7.existsSync(copilotCliScriptPath(opts)) || fs7.existsSync(path7.join(copilotCliHooksDir(opts), LEGACY_HOOKS_SCRIPT_FILE));
|
|
2982
|
+
if (!fs7.existsSync(copilotCliConfigPath(opts)) || !scriptPresent) {
|
|
2983
|
+
return false;
|
|
2984
|
+
}
|
|
2985
|
+
if (!readCopilotHooksOwners(copilotCliHooksDir(opts)).has("copilot")) return false;
|
|
2986
|
+
let instructions;
|
|
2987
|
+
try {
|
|
2988
|
+
instructions = fs7.readFileSync(copilotCliInstructionsPath(opts), "utf8");
|
|
2989
|
+
} catch {
|
|
2990
|
+
return false;
|
|
2991
|
+
}
|
|
2992
|
+
return instructions.includes(COPILOT_INSTRUCTIONS_BEGIN) && instructions.includes(COPILOT_INSTRUCTIONS_END);
|
|
2993
|
+
}
|
|
2994
|
+
|
|
2995
|
+
export {
|
|
2996
|
+
SHIM_TRY_SERVER,
|
|
2997
|
+
SHIM_FILE,
|
|
2998
|
+
LEGACY_SHIM_FILE,
|
|
2999
|
+
legacyShimForwarder,
|
|
3000
|
+
SHIM_REQUIRES,
|
|
3001
|
+
SHIM_VALID_HOOK_EVENTS,
|
|
3002
|
+
SHIM_TRY_IN_PROCESS,
|
|
3003
|
+
SHIM_SPAWN_LADDER,
|
|
3004
|
+
SHIM_MAX_BUFFER_CONST,
|
|
3005
|
+
CLAUDECODE_HOOK_SCRIPT,
|
|
3006
|
+
buildGuidanceBody,
|
|
3007
|
+
skillDescriptionLine,
|
|
3008
|
+
buildGuidanceBlock,
|
|
3009
|
+
packagedNativeBinary,
|
|
3010
|
+
nativeCopyPath,
|
|
3011
|
+
nativeCopyCurrent,
|
|
3012
|
+
nativeSelftest,
|
|
3013
|
+
nativeHookBinary,
|
|
3014
|
+
nativeHookCommandLine,
|
|
3015
|
+
splitHookCommand,
|
|
3016
|
+
HookCommandRewriteError,
|
|
3017
|
+
hookCommandRewrittenSpan,
|
|
3018
|
+
parseNativeInvocation,
|
|
3019
|
+
anchoredMarkerPattern,
|
|
3020
|
+
claudeHookScriptPath,
|
|
3021
|
+
settingsPath,
|
|
3022
|
+
wiredClaudeHookWords,
|
|
3023
|
+
installHooks,
|
|
3024
|
+
uninstallHooks,
|
|
3025
|
+
finishHookUninstall,
|
|
3026
|
+
isInstalled,
|
|
3027
|
+
hookEventGaps,
|
|
3028
|
+
claudeMdPath,
|
|
3029
|
+
installedClaudeMdBlock,
|
|
3030
|
+
installClaudeMd,
|
|
3031
|
+
uninstallClaudeMd,
|
|
3032
|
+
findStrayClaudeMdBlocks,
|
|
3033
|
+
skillPath,
|
|
3034
|
+
installedSkillDescription,
|
|
3035
|
+
installSkill,
|
|
3036
|
+
uninstallSkill,
|
|
3037
|
+
CODEX_HOOK_SCRIPT,
|
|
3038
|
+
groupHasTokenGoat2 as groupHasTokenGoat,
|
|
3039
|
+
codexConfigPath,
|
|
3040
|
+
codexAgentsPath,
|
|
3041
|
+
codexHookScriptPath,
|
|
3042
|
+
installCodex,
|
|
3043
|
+
uninstallCodex,
|
|
3044
|
+
wiredCodexHookWords,
|
|
3045
|
+
isCodexInstalled,
|
|
3046
|
+
bundledCliPath,
|
|
3047
|
+
managedServer,
|
|
3048
|
+
isManagedServer,
|
|
3049
|
+
readServersJson,
|
|
3050
|
+
serversOf,
|
|
3051
|
+
editAt,
|
|
3052
|
+
setTokenGoatServer,
|
|
3053
|
+
isResidueServersJson,
|
|
3054
|
+
noteRootKeyCreation,
|
|
3055
|
+
dropEmptyServers,
|
|
3056
|
+
managedServerEntry,
|
|
3057
|
+
hasManagedServer,
|
|
3058
|
+
MATERIALIZE_SHRUNK_IMAGE_JS,
|
|
3059
|
+
COPILOT_CLI_HOOK_SCRIPT,
|
|
3060
|
+
copilotMcpConfigPath,
|
|
3061
|
+
visualStudioUserMcpPath,
|
|
3062
|
+
visualStudioProjectMcpPath,
|
|
3063
|
+
visualStudioOtherScopeHasManagedServer,
|
|
3064
|
+
isVisualStudioInstalled,
|
|
3065
|
+
visualStudioSolutionVscodeMcpPath,
|
|
3066
|
+
visualStudioDuplicateNote,
|
|
3067
|
+
visualStudioMcpStatus,
|
|
3068
|
+
visualStudioManagedEntry,
|
|
3069
|
+
syncVisualStudioProjectGuidance,
|
|
3070
|
+
installVisualStudio,
|
|
3071
|
+
uninstallVisualStudio,
|
|
3072
|
+
canonicalProjectRoot,
|
|
3073
|
+
copilotCliHooksDir,
|
|
3074
|
+
copilotCliConfigPath,
|
|
3075
|
+
copilotCliScriptPath,
|
|
3076
|
+
copilotCliInstructionsPath,
|
|
3077
|
+
writeCopilotInstructionsBlock,
|
|
3078
|
+
wiredCopilotHookWords,
|
|
3079
|
+
HOOKS_SCRIPT_FILE,
|
|
3080
|
+
LEGACY_HOOKS_SCRIPT_FILE,
|
|
3081
|
+
copilotHooksFilePaths,
|
|
3082
|
+
installCopilotHooksFile,
|
|
3083
|
+
releaseCopilotHooksFile,
|
|
3084
|
+
installCopilotCli,
|
|
3085
|
+
uninstallCopilotCli,
|
|
3086
|
+
isCopilotCliInstalled
|
|
3087
|
+
};
|