token-goat 2.9.28 → 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.
Files changed (134) hide show
  1. package/README.md +36 -40
  2. package/SECURITY.md +28 -10
  3. package/THIRD_PARTY_NOTICES.md +40 -3
  4. package/dist/native/linux-arm64/tg-hook +0 -0
  5. package/dist/native/linux-x64/tg-hook +0 -0
  6. package/dist/ort-wasm-simd-threaded.mjs +59 -0
  7. package/dist/token-goat-chunk-3CHUNJ2O.mjs +53 -0
  8. package/dist/token-goat-chunk-3Z5S4KGM.mjs +918 -0
  9. package/dist/token-goat-chunk-4FVIAHSI.mjs +211 -0
  10. package/dist/{token-goat-chunk-66LODAUT.mjs → token-goat-chunk-4JJS54TR.mjs} +4 -3
  11. package/dist/token-goat-chunk-4LCCNRTG.mjs +313 -0
  12. package/dist/token-goat-chunk-54K3EUV3.mjs +35 -0
  13. package/dist/token-goat-chunk-56EIMS3E.mjs +159 -0
  14. package/dist/token-goat-chunk-5BCIJXMO.mjs +609 -0
  15. package/dist/token-goat-chunk-5KDMCMF2.mjs +362 -0
  16. package/dist/token-goat-chunk-5RG5SBL6.mjs +221 -0
  17. package/dist/{token-goat-chunk-RRNZMM3A.mjs → token-goat-chunk-5Y6ZYL6U.mjs} +21 -2
  18. package/dist/{token-goat-chunk-NILVK7XM.mjs → token-goat-chunk-64FBPDTK.mjs} +12 -6
  19. package/dist/{token-goat-chunk-LEG3JNJ6.mjs → token-goat-chunk-664RTTUV.mjs} +31 -15
  20. package/dist/token-goat-chunk-67TQJ76B.mjs +57 -0
  21. package/dist/token-goat-chunk-6QMAS7AB.mjs +42 -0
  22. package/dist/token-goat-chunk-7BXSNBY5.mjs +253 -0
  23. package/dist/{token-goat-chunk-F7QZRIWM.mjs → token-goat-chunk-7F2UBPD3.mjs} +42 -35
  24. package/dist/{token-goat-chunk-CC2PYJM7.mjs → token-goat-chunk-7IN2MKDS.mjs} +718 -595
  25. package/dist/token-goat-chunk-7NADEDKJ.mjs +124 -0
  26. package/dist/{token-goat-chunk-6SGLIPQB.mjs → token-goat-chunk-A3CK6N5Z.mjs} +621 -72
  27. package/dist/{token-goat-chunk-HXNAC4ZF.mjs → token-goat-chunk-AFLYLHDH.mjs} +48 -33
  28. package/dist/token-goat-chunk-AM5V6GSX.mjs +367 -0
  29. package/dist/{token-goat-chunk-I7CB3X4K.mjs → token-goat-chunk-APGZXSPS.mjs} +44 -148
  30. package/dist/{token-goat-chunk-BJBRGPBX.mjs → token-goat-chunk-ARDNEC2U.mjs} +11 -7
  31. package/dist/token-goat-chunk-ATCPY7EQ.mjs +134 -0
  32. package/dist/token-goat-chunk-B2RZZCSS.mjs +354 -0
  33. package/dist/{token-goat-chunk-QM76S6YS.mjs → token-goat-chunk-B45VMIIH.mjs} +6 -5
  34. package/dist/token-goat-chunk-BPGCUMR7.mjs +30 -0
  35. package/dist/{token-goat-chunk-GGLEE35R.mjs → token-goat-chunk-C63JQV5K.mjs} +49 -10
  36. package/dist/{token-goat-chunk-RJH64KQH.mjs → token-goat-chunk-COBQGL5S.mjs} +2661 -2440
  37. package/dist/token-goat-chunk-COTXZHTS.mjs +39 -0
  38. package/dist/token-goat-chunk-CYCEYAEO.mjs +265 -0
  39. package/dist/token-goat-chunk-CZ3LUXYZ.mjs +4115 -0
  40. package/dist/token-goat-chunk-DZX2YDPT.mjs +15 -0
  41. package/dist/token-goat-chunk-E3OQX2XT.mjs +824 -0
  42. package/dist/token-goat-chunk-EFHMMIGP.mjs +68 -0
  43. package/dist/token-goat-chunk-ETBHVDB6.mjs +328 -0
  44. package/dist/token-goat-chunk-EVMZJ27Z.mjs +147 -0
  45. package/dist/token-goat-chunk-EXKGNHEG.mjs +2096 -0
  46. package/dist/{token-goat-chunk-6Z5ULNE5.mjs → token-goat-chunk-FBNQNSJK.mjs} +2490 -4957
  47. package/dist/{token-goat-chunk-NMTKNYGF.mjs → token-goat-chunk-FNFBKLRD.mjs} +74 -9
  48. package/dist/{token-goat-chunk-XI2VFAV6.mjs → token-goat-chunk-FZ3NEW5O.mjs} +33 -19
  49. package/dist/token-goat-chunk-G5PJ7AGM.mjs +36 -0
  50. package/dist/{token-goat-chunk-VE27HPIF.mjs → token-goat-chunk-GFBSN7BD.mjs} +30 -398
  51. package/dist/{token-goat-chunk-L45ZQRT7.mjs → token-goat-chunk-GOLEOXZP.mjs} +780 -786
  52. package/dist/token-goat-chunk-H2K3QP6H.mjs +24 -0
  53. package/dist/token-goat-chunk-H2PHHGM5.mjs +188 -0
  54. package/dist/token-goat-chunk-HAVAOB3S.mjs +87 -0
  55. package/dist/token-goat-chunk-HG45AF2B.mjs +2228 -0
  56. package/dist/{token-goat-chunk-CBMY2FGI.mjs → token-goat-chunk-HOJLCGDP.mjs} +17113 -15554
  57. package/dist/{token-goat-chunk-HUDC5GS5.mjs → token-goat-chunk-HYBFA5X3.mjs} +120 -19
  58. package/dist/token-goat-chunk-IVALLT3S.mjs +48 -0
  59. package/dist/token-goat-chunk-IVE6U7KV.mjs +53 -0
  60. package/dist/{token-goat-chunk-UBUKHVYW.mjs → token-goat-chunk-IVKIZWAB.mjs} +3 -3
  61. package/dist/{token-goat-chunk-4JMWPWCS.mjs → token-goat-chunk-JB6QN6VF.mjs} +6 -4
  62. package/dist/{token-goat-chunk-Q4S3UQGO.mjs → token-goat-chunk-JDHE26RP.mjs} +10 -3
  63. package/dist/{token-goat-chunk-7R2XYKC5.mjs → token-goat-chunk-JDU3EXSU.mjs} +14 -10
  64. package/dist/token-goat-chunk-JDWCRD6M.mjs +253 -0
  65. package/dist/{token-goat-chunk-XBESNWEX.mjs → token-goat-chunk-JN4XMLSD.mjs} +7 -4
  66. package/dist/token-goat-chunk-JTQQGXZH.mjs +733 -0
  67. package/dist/token-goat-chunk-KKUFXAPD.mjs +25 -0
  68. package/dist/token-goat-chunk-KQNZDCBD.mjs +47 -0
  69. package/dist/{token-goat-chunk-4RN64ZND.mjs → token-goat-chunk-KWPNJBDH.mjs} +28 -3
  70. package/dist/token-goat-chunk-LOBGHXPB.mjs +242 -0
  71. package/dist/token-goat-chunk-MKPF4CL5.mjs +37 -0
  72. package/dist/token-goat-chunk-MNWKPRAL.mjs +13 -0
  73. package/dist/{token-goat-chunk-YWSP6IU7.mjs → token-goat-chunk-N2NMER56.mjs} +25 -15
  74. package/dist/token-goat-chunk-NYKZLXMK.mjs +218 -0
  75. package/dist/token-goat-chunk-OJBNYTJP.mjs +3087 -0
  76. package/dist/token-goat-chunk-P4QMM4WK.mjs +295 -0
  77. package/dist/token-goat-chunk-PD5VKH46.mjs +184 -0
  78. package/dist/token-goat-chunk-PEPTHRFF.mjs +129 -0
  79. package/dist/{token-goat-chunk-VWZKZPSR.mjs → token-goat-chunk-PU7V3FD6.mjs} +8752 -11098
  80. package/dist/token-goat-chunk-PY533T7F.mjs +46 -0
  81. package/dist/token-goat-chunk-Q5VTGRH7.mjs +761 -0
  82. package/dist/{token-goat-chunk-IHKZ3QNA.mjs → token-goat-chunk-QCLDAQTS.mjs} +33 -19
  83. package/dist/{token-goat-chunk-LKSXAMJB.mjs → token-goat-chunk-QSBRTGM2.mjs} +9 -2
  84. package/dist/{token-goat-chunk-4STDIGYC.mjs → token-goat-chunk-RC35RBUL.mjs} +7 -5
  85. package/dist/{token-goat-chunk-D5ICEPSB.mjs → token-goat-chunk-RHXKCZX3.mjs} +887 -507
  86. package/dist/{token-goat-chunk-RSS3TLXU.mjs → token-goat-chunk-RZRTDST7.mjs} +17 -7
  87. package/dist/{token-goat-chunk-MAMQPC43.mjs → token-goat-chunk-SJHWVNDQ.mjs} +15 -21
  88. package/dist/token-goat-chunk-SMVRN2HU.mjs +188 -0
  89. package/dist/{token-goat-chunk-EL7M26WP.mjs → token-goat-chunk-SQSSNQPE.mjs} +2100 -1442
  90. package/dist/{token-goat-chunk-OZRSREKR.mjs → token-goat-chunk-T4FK7VOV.mjs} +3 -3
  91. package/dist/token-goat-chunk-U4N3BN2W.mjs +92 -0
  92. package/dist/token-goat-chunk-UA5V6P3P.mjs +122 -0
  93. package/dist/{token-goat-chunk-XKY4VKJ4.mjs → token-goat-chunk-UQ5UK2T7.mjs} +15 -4
  94. package/dist/token-goat-chunk-USILZ3T3.mjs +53 -0
  95. package/dist/token-goat-chunk-VES7EL7O.mjs +205 -0
  96. package/dist/{token-goat-chunk-M56BWPBN.mjs → token-goat-chunk-VL3YIFHZ.mjs} +550 -49
  97. package/dist/{token-goat-chunk-IZXKVT4A.mjs → token-goat-chunk-VPBBTSJR.mjs} +362 -128
  98. package/dist/{token-goat-chunk-F2ARFHLJ.mjs → token-goat-chunk-W3QCJS6G.mjs} +10 -2
  99. package/dist/{token-goat-chunk-FSTWAOW6.mjs → token-goat-chunk-WY3L4DVT.mjs} +11 -5
  100. package/dist/{token-goat-chunk-OSUFN2FV.mjs → token-goat-chunk-XB5KKOCG.mjs} +5 -25
  101. package/dist/token-goat-chunk-XKI4SEMX.mjs +66 -0
  102. package/dist/token-goat-chunk-XU4P6Z24.mjs +133 -0
  103. package/dist/{token-goat-chunk-6CCQDAYY.mjs → token-goat-chunk-Y776AENC.mjs} +138 -33
  104. package/dist/token-goat-chunk-YARZFCZS.mjs +359 -0
  105. package/dist/{token-goat-chunk-EEIDFMEM.mjs → token-goat-chunk-YZAAZU2S.mjs} +12 -3
  106. package/dist/{token-goat-chunk-E3K3BTEQ.mjs → token-goat-chunk-Z44YO3QZ.mjs} +12 -6
  107. package/dist/token-goat-chunk-Z57YODA2.mjs +35 -0
  108. package/dist/{token-goat-chunk-DA43OE7L.mjs → token-goat-chunk-ZCDTCVIS.mjs} +49 -30
  109. package/dist/token-goat-chunk-ZEJVMUQH.mjs +48 -0
  110. package/dist/{token-goat-chunk-BGHSSJUA.mjs → token-goat-chunk-ZFOBKUWH.mjs} +1 -1
  111. package/dist/token-goat-chunk-ZMBL6UVV.mjs +110 -0
  112. package/dist/{token-goat-chunk-SJEKA7Y2.mjs → token-goat-chunk-ZQSJMO2R.mjs} +381 -201
  113. package/dist/token-goat-hook-client.cjs +539 -0
  114. package/dist/token-goat-hook-client.mjs +26 -0
  115. package/dist/token-goat-hook.mjs +48 -28
  116. package/dist/token-goat.core.mjs +10 -45
  117. package/docs/C4_RUNTIME_ARCHITECTURE.md +3 -3
  118. package/docs/cli.md +82 -47
  119. package/docs/install.md +58 -23
  120. package/docs/security.md +7 -7
  121. package/package.json +17 -7
  122. package/scripts/verify-native-dist.mjs +386 -0
  123. package/dist/token-goat-chunk-4JJBFT7V.mjs +0 -20
  124. package/dist/token-goat-chunk-5NNYIUGV.mjs +0 -143
  125. package/dist/token-goat-chunk-6DQNNFJ6.mjs +0 -294
  126. package/dist/token-goat-chunk-7MAFDRVR.mjs +0 -47
  127. package/dist/token-goat-chunk-BCN2YQC6.mjs +0 -32
  128. package/dist/token-goat-chunk-D7GHQKQD.mjs +0 -30
  129. package/dist/token-goat-chunk-GMOUBOX4.mjs +0 -386
  130. package/dist/token-goat-chunk-IFORDBGC.mjs +0 -192
  131. package/dist/token-goat-chunk-JXK2HQXS.mjs +0 -318
  132. package/dist/token-goat-chunk-L7SDVGBT.mjs +0 -430
  133. package/dist/token-goat-chunk-MMLMALWK.mjs +0 -1381
  134. package/dist/token-goat-chunk-MVSWBNMD.mjs +0 -1985
@@ -1,1381 +0,0 @@
1
- import { createRequire as __cjsRequire } from 'node:module';
2
- const require = __cjsRequire(import.meta.url);
3
- import {
4
- estimateTokensFromLength
5
- } from "./token-goat-chunk-4JMWPWCS.mjs";
6
- import {
7
- loadConfig
8
- } from "./token-goat-chunk-CC2PYJM7.mjs";
9
- import {
10
- atomicWriteText,
11
- backupFile,
12
- ensureDirSync,
13
- hookCommandFor,
14
- hookPowershellCommand,
15
- projectScopeRoot,
16
- recordCreatedConfig,
17
- removeCreatedBackups,
18
- removeFileInScope,
19
- stripDelimitedBlock,
20
- takeCreatedConfig,
21
- upsertDelimitedBlock,
22
- withInstallScope,
23
- writeIfDifferent
24
- } from "./token-goat-chunk-L45ZQRT7.mjs";
25
- import {
26
- init_define_import_meta_env
27
- } from "./token-goat-chunk-A37V4PBF.mjs";
28
-
29
- // src/bridges/visualstudio_install.ts
30
- init_define_import_meta_env();
31
- import * as fs2 from "node:fs";
32
- import * as os from "node:os";
33
- import * as path2 from "node:path";
34
-
35
- // src/bridges/guidance_block.ts
36
- init_define_import_meta_env();
37
- function buildGuidanceBody(fallbackToolClause, opts = {}) {
38
- const gdrive = opts.gdrive !== false;
39
- return [
40
- "## token-goat",
41
- "",
42
- "**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.",
43
- "",
44
- `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.`,
45
- "",
46
- "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.",
47
- "",
48
- "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).",
49
- "",
50
- "Failure shapes to catch yourself in, and the command that replaces each:",
51
- '- 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',
52
- '- a shell text search with context flags to find a function body \u2192 `read "file::symbol"`',
53
- '- paging one function with view/view_range \u2192 `read "file::symbol"`',
54
- "- a read refused by a `[tg]` deny, retried with a shifted range or a different read tool \u2192 the command the deny names",
55
- '- reading a symbol plus chasing its callers and containing doc section as separate reads \u2192 `brief "file::symbol"`',
56
- '- reading one heading of a large doc \u2192 `section "file::Heading"`',
57
- "- searching for a symbol's callers \u2192 `refs file::symbol --callers`",
58
- '- searching for a *concept* rather than a literal string \u2192 `semantic "description"`',
59
- "- re-reading output you already captured \u2192 `bash-output`/`web-output`/`mcp-output` by ID",
60
- "- a directory listing or recursive wildcard walk to orient in an unfamiliar repo \u2192 `map --compact`",
61
- "- 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'`",
62
- "- opening an image to check its dimensions, format, or size \u2192 `image-meta file`",
63
- "- opening a screenshot, diagram, or scan to read the text in it \u2192 `image-text file`",
64
- "- 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`",
65
- "",
66
- 'Commands: `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`.",
67
- "",
68
- "Sub-agent briefs must carry this gate verbatim: a sub-agent inherits none of this context and its reads spend the same token budget.",
69
- "",
70
- "`token-goat stats` \u2014 self-check. Flat counts during code work mean the gate is being skipped."
71
- ].join("\n");
72
- }
73
- function skillDescriptionLine(gdrive) {
74
- 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.`;
75
- }
76
- function buildGuidanceBlock(h) {
77
- return [h.beginMarker, buildGuidanceBody(h.fallbackToolClause, h.gdrive === void 0 ? {} : { gdrive: h.gdrive }), h.endMarker].join("\n");
78
- }
79
-
80
- // src/bridges/mcp_servers_json.ts
81
- init_define_import_meta_env();
82
- import * as fs from "node:fs";
83
- import * as path from "node:path";
84
- import { createRequire } from "node:module";
85
- import { fileURLToPath } from "node:url";
86
- var jsoncParser;
87
- function jsonc() {
88
- jsoncParser ??= createRequire(import.meta.url)("jsonc-parser");
89
- return jsoncParser;
90
- }
91
- function bundledCliPath() {
92
- const here = path.dirname(fileURLToPath(import.meta.url));
93
- const bundled = path.join(here, "token-goat.mjs");
94
- if (fs.existsSync(bundled)) return bundled;
95
- return path.resolve(here, "..", "..", "dist", "token-goat.mjs");
96
- }
97
- function managedServer() {
98
- return {
99
- type: "stdio",
100
- command: process.execPath,
101
- args: [bundledCliPath(), "mcp-serve"]
102
- };
103
- }
104
- function isManagedServer(value) {
105
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
106
- const entry = value;
107
- const args = entry["args"];
108
- return entry["type"] === "stdio" && Array.isArray(args) && args.length === 2 && typeof args[0] === "string" && path.basename(args[0]).toLowerCase() === "token-goat.mjs" && args[1] === "mcp-serve";
109
- }
110
- function readServersJson(filePath, label) {
111
- const text = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8") : "{}\n";
112
- const errors = [];
113
- const parsed = jsonc().parse(text, errors, { allowTrailingComma: true, disallowComments: false });
114
- if (errors.length > 0) {
115
- throw new Error(`malformed ${label} MCP JSON at ${filePath}`);
116
- }
117
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
118
- throw new Error(`malformed ${label} MCP JSON at ${filePath}: expected a JSON object`);
119
- }
120
- return { text, value: parsed };
121
- }
122
- function serversOf(config, filePath, label, rootKey = "servers") {
123
- const servers = config.value[rootKey];
124
- if (servers === void 0) return {};
125
- if (servers === null || typeof servers !== "object" || Array.isArray(servers)) {
126
- throw new Error(`malformed ${label} MCP JSON at ${filePath}: ${rootKey} must be an object`);
127
- }
128
- return servers;
129
- }
130
- var FORMAT = { insertSpaces: true, tabSize: 2, eol: "\n" };
131
- function editAt(text, jsonPath, value) {
132
- let out = text;
133
- for (const e of [...jsonc().modify(text, jsonPath, value, {})].sort((a, b) => b.offset - a.offset)) {
134
- out = out.slice(0, e.offset) + e.content + out.slice(e.offset + e.length);
135
- if (e.content.length > 0) out = jsonc().applyEdits(out, jsonc().format(out, { offset: e.offset, length: e.content.length }, FORMAT));
136
- }
137
- return out;
138
- }
139
- function setTokenGoatServer(text, value, rootKey = "servers") {
140
- if (value !== void 0 && /^\s*\{\s*\}\s*$/.test(text)) return `${JSON.stringify({ [rootKey]: { "token-goat": value } }, null, 2)}
141
- `;
142
- return editAt(text, [rootKey, "token-goat"], value);
143
- }
144
- function holdsOnlyManagedServer(value) {
145
- const keys = Object.keys(value);
146
- if (keys.length !== 1) return false;
147
- const root = keys[0];
148
- if (root !== "servers" && root !== "mcpServers") return false;
149
- const servers = value[root];
150
- if (servers === null || typeof servers !== "object" || Array.isArray(servers)) return false;
151
- const names = Object.keys(servers);
152
- return names.length === 1 && names[0] === "token-goat" && isManagedServer(servers["token-goat"]);
153
- }
154
- function isResidueServersJson(text, rootKey = "servers") {
155
- const trimmed = text.trim();
156
- if (trimmed === "") return true;
157
- const parsed = parseObject(trimmed);
158
- if (parsed === null) return false;
159
- const keys = Object.keys(parsed);
160
- if (keys.length !== 1 || keys[0] !== rootKey) return false;
161
- const servers = parsed[rootKey];
162
- return servers !== null && typeof servers === "object" && !Array.isArray(servers) && Object.keys(servers).length === 0;
163
- }
164
- function dropEmptyServers(text, rootKey = "servers") {
165
- const parsed = parseObject(text);
166
- if (parsed === null) return text;
167
- const servers = parsed[rootKey];
168
- if (servers === null || typeof servers !== "object" || Array.isArray(servers) || Object.keys(servers).length > 0) return text;
169
- return editAt(text, [rootKey], void 0);
170
- }
171
- function parseObject(text) {
172
- const parsed = jsonc().parse(text, [], { allowTrailingComma: true, disallowComments: false });
173
- return parsed === null || typeof parsed !== "object" || Array.isArray(parsed) ? null : parsed;
174
- }
175
- function ensureMcpServersKey(text) {
176
- const parsed = parseObject(text);
177
- if (parsed === null || "mcpServers" in parsed) return text;
178
- return editAt(text, ["mcpServers"], {});
179
- }
180
- function dropLoneEmptyMcpServers(text) {
181
- const parsed = parseObject(text);
182
- if (parsed === null || Object.keys(parsed).length !== 1) return text;
183
- const mcpServers = parsed["mcpServers"];
184
- if (mcpServers === null || typeof mcpServers !== "object" || Array.isArray(mcpServers) || Object.keys(mcpServers).length > 0) return text;
185
- return editAt(text, ["mcpServers"], void 0);
186
- }
187
- function hasManagedServer(filePath, label, rootKey = "servers", isManaged = isManagedServer) {
188
- if (!fs.existsSync(filePath)) return false;
189
- try {
190
- const config = readServersJson(filePath, label);
191
- return isManaged(serversOf(config, filePath, label, rootKey)["token-goat"]);
192
- } catch {
193
- return false;
194
- }
195
- }
196
-
197
- // src/bridges/visualstudio_install.ts
198
- var LABEL = "Visual Studio";
199
- var VISUALSTUDIO_GUIDANCE_BEGIN = "<!-- token-goat-visualstudio-begin -->";
200
- var VISUALSTUDIO_GUIDANCE_END = "<!-- token-goat-visualstudio-end -->";
201
- var SIBLING_GATE_MARKERS = [
202
- ["<!-- token-goat-vscode-begin -->", "<!-- token-goat-vscode-end -->"],
203
- ["<!-- token-goat-begin -->", "<!-- token-goat-end -->"]
204
- ];
205
- function visualStudioUserMcpPath() {
206
- return path2.join(os.homedir(), ".mcp.json");
207
- }
208
- function visualStudioProjectMcpPath(projectRoot = process.cwd()) {
209
- return path2.join(path2.resolve(projectRoot), ".mcp.json");
210
- }
211
- function visualStudioMcpPath(opts = {}) {
212
- return opts.project === true ? visualStudioProjectMcpPath(opts.projectRoot) : visualStudioUserMcpPath();
213
- }
214
- function otherScopeMcpPath(opts) {
215
- return opts.project === true ? visualStudioUserMcpPath() : visualStudioProjectMcpPath(opts.projectRoot);
216
- }
217
- function visualStudioInstructionsPath(opts = {}) {
218
- return opts.project === true ? path2.join(path2.resolve(opts.projectRoot ?? process.cwd()), ".github", "copilot-instructions.md") : path2.join(os.homedir(), "copilot-instructions.md");
219
- }
220
- function visualStudioOtherScopeHasManagedServer(opts = {}) {
221
- return hasManagedServer(otherScopeMcpPath(opts), LABEL);
222
- }
223
- function isVisualStudioInstalled(opts = {}) {
224
- return hasManagedServer(visualStudioMcpPath(opts), LABEL);
225
- }
226
- function visualStudioSolutionVscodeMcpPath(projectRoot = process.cwd()) {
227
- return path2.join(path2.resolve(projectRoot), ".vscode", "mcp.json");
228
- }
229
- function visualStudioManagedRegistrations(projectRoot = process.cwd()) {
230
- return [visualStudioUserMcpPath(), visualStudioProjectMcpPath(projectRoot), visualStudioSolutionVscodeMcpPath(projectRoot)].filter((p) => hasManagedServer(p, LABEL));
231
- }
232
- function visualStudioDuplicateNote(projectRoot = process.cwd()) {
233
- const found = visualStudioManagedRegistrations(projectRoot);
234
- if (found.length < 2) return null;
235
- 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.`;
236
- if (!found.includes(visualStudioSolutionVscodeMcpPath(projectRoot))) return `${lead} Keep one: run "token-goat uninstall --visualstudio" or "token-goat uninstall --visualstudio -p".`;
237
- 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"}".`;
238
- }
239
- function visualStudioMcpStatus(opts = {}) {
240
- const checkedPaths = [visualStudioUserMcpPath()];
241
- if (opts.projectRoot !== void 0) checkedPaths.push(visualStudioProjectMcpPath(opts.projectRoot));
242
- return { configured: checkedPaths.some((p) => hasManagedServer(p, LABEL)), checkedPaths };
243
- }
244
- function visualStudioManagedEntry(filePath) {
245
- if (!fs2.existsSync(filePath)) return null;
246
- try {
247
- const entry = serversOf(readServersJson(filePath, LABEL), filePath, LABEL)["token-goat"];
248
- if (!isManagedServer(entry)) return null;
249
- const { command, args } = entry;
250
- return { command: typeof command === "string" ? command : "", bundlePath: args[0] ?? "" };
251
- } catch {
252
- return null;
253
- }
254
- }
255
- var FALLBACK_TOOL_CLAUSE = "Visual Studio\u2019s built-in readfile, code_search, and find_references tools";
256
- 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.";
257
- 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.";
258
- function buildVisualStudioGuidanceBlock(sharesFileWithGate) {
259
- 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 })];
260
- return [VISUALSTUDIO_GUIDANCE_BEGIN, ...lead, "", RETRIEVE_NOTE, "", SUPPORT_NOTE, VISUALSTUDIO_GUIDANCE_END].join("\n");
261
- }
262
- function hasBlock(text, begin, end) {
263
- const b = text.indexOf(begin);
264
- const e = text.indexOf(end);
265
- return b !== -1 && e > b;
266
- }
267
- function readText(filePath) {
268
- try {
269
- return fs2.readFileSync(filePath, "utf8");
270
- } catch {
271
- return "";
272
- }
273
- }
274
- function writeGuidance(filePath) {
275
- const text = readText(filePath);
276
- const shares = SIBLING_GATE_MARKERS.some(([begin, end]) => hasBlock(text, begin, end));
277
- return upsertDelimitedBlock(filePath, VISUALSTUDIO_GUIDANCE_BEGIN, VISUALSTUDIO_GUIDANCE_END, buildVisualStudioGuidanceBlock(shares));
278
- }
279
- function syncVisualStudioProjectGuidance(filePath) {
280
- if (!hasBlock(readText(filePath), VISUALSTUDIO_GUIDANCE_BEGIN, VISUALSTUDIO_GUIDANCE_END)) return false;
281
- return writeGuidance(filePath);
282
- }
283
- function installVisualStudio(opts = {}) {
284
- return withInstallScope(projectScopeRoot(opts), () => installVisualStudioScoped(opts));
285
- }
286
- function installVisualStudioScoped(opts) {
287
- const scope = opts.project === true ? "project" : "user";
288
- const mcpPath = visualStudioMcpPath(opts);
289
- const instructionsPath = visualStudioInstructionsPath(opts);
290
- if (visualStudioOtherScopeHasManagedServer(opts)) {
291
- const otherScope = scope === "project" ? "user" : "project";
292
- throw new Error(
293
- `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.`
294
- );
295
- }
296
- const mcpExisted = fs2.existsSync(mcpPath);
297
- const config = readServersJson(mcpPath, LABEL);
298
- const ownedAlready = mcpExisted && holdsOnlyManagedServer(config.value);
299
- const current = serversOf(config, mcpPath, LABEL)["token-goat"];
300
- if (current !== void 0 && !isManagedServer(current)) {
301
- throw new Error(`Visual Studio MCP JSON at ${mcpPath} already has a non-token-goat-managed server named "token-goat"`);
302
- }
303
- const next = ensureMcpServersKey(setTokenGoatServer(config.text, managedServer()));
304
- if (config.text !== next) {
305
- ensureDirSync(path2.dirname(mcpPath));
306
- backupFile(mcpPath);
307
- atomicWriteText(mcpPath, next);
308
- if (!mcpExisted || ownedAlready) recordCreatedConfig(mcpPath);
309
- }
310
- const guidanceChanged = writeGuidance(instructionsPath);
311
- return { mcpPath, instructionsPath, alreadyInstalled: config.text === next && !guidanceChanged, scope };
312
- }
313
- function uninstallVisualStudio(opts = {}) {
314
- return withInstallScope(projectScopeRoot(opts), () => uninstallVisualStudioScoped(opts));
315
- }
316
- function uninstallVisualStudioScoped(opts) {
317
- const mcpPath = visualStudioMcpPath(opts);
318
- let removed = false;
319
- if (fs2.existsSync(mcpPath)) {
320
- const config = readServersJson(mcpPath, LABEL);
321
- if (isManagedServer(serversOf(config, mcpPath, LABEL)["token-goat"])) {
322
- const next = dropEmptyServers(setTokenGoatServer(config.text, void 0));
323
- if (/^\s*\{\s*\}\s*$/.test(dropLoneEmptyMcpServers(next)) && takeCreatedConfig(mcpPath)) removeFileInScope(mcpPath);
324
- else {
325
- backupFile(mcpPath);
326
- atomicWriteText(mcpPath, ensureMcpServersKey(next));
327
- }
328
- removeCreatedBackups(mcpPath);
329
- removed = true;
330
- }
331
- }
332
- const instructionsPath = visualStudioInstructionsPath(opts);
333
- if (stripDelimitedBlock(instructionsPath, VISUALSTUDIO_GUIDANCE_BEGIN, VISUALSTUDIO_GUIDANCE_END)) {
334
- removed = true;
335
- if (readText(instructionsPath).trim() === "") removeFileInScope(instructionsPath);
336
- }
337
- return removed;
338
- }
339
-
340
- // src/bridges/copilot_cli_install.ts
341
- init_define_import_meta_env();
342
- import * as fs3 from "node:fs";
343
- import * as os2 from "node:os";
344
- import * as path3 from "node:path";
345
-
346
- // src/bridges/copilot_cli.ts
347
- init_define_import_meta_env();
348
-
349
- // src/copilot_tool_names.ts
350
- init_define_import_meta_env();
351
- var COPILOT_CLI_TOOL_NAME_MAP = {
352
- bash: "Bash",
353
- powershell: "Bash",
354
- read_bash: "BashOutput",
355
- read_powershell: "BashOutput",
356
- view: "Read",
357
- create: "Write",
358
- edit: "Edit",
359
- web_fetch: "WebFetch",
360
- web_search: "WebSearch",
361
- grep: "Grep",
362
- glob: "Glob",
363
- skill: "Skill",
364
- exit_plan_mode: "ExitPlanMode"
365
- };
366
-
367
- // src/tool_name_fold.ts
368
- init_define_import_meta_env();
369
- function foldToolName(name) {
370
- return typeof name === "string" ? name.toLowerCase().replace(/[_-]/g, "") : "";
371
- }
372
-
373
- // src/bridges/shrink_block.ts
374
- init_define_import_meta_env();
375
- 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.
376
- const MATERIALIZED_SHRINK_MAX_AGE_MS = 60 * 60 * 1000
377
- let lastMaterializedShrinkSweepAtMs = 0
378
- function pruneMaterializedShrinks() {
379
- const now = Date.now()
380
- if (now - lastMaterializedShrinkSweepAtMs < MATERIALIZED_SHRINK_MAX_AGE_MS) return
381
- lastMaterializedShrinkSweepAtMs = now
382
- try {
383
- const dir = os.tmpdir()
384
- for (const file of fs.readdirSync(dir)) {
385
- if (!file.startsWith("token-goat-shrink-")) continue
386
- const full = path.join(dir, file)
387
- try {
388
- const st = fs.statSync(full)
389
- if (st.isFile() && now - st.mtimeMs > MATERIALIZED_SHRINK_MAX_AGE_MS) fs.unlinkSync(full)
390
- } catch {
391
- // Best-effort per-file cleanup; one bad stat/unlink must not abort the sweep.
392
- }
393
- }
394
- } catch {
395
- // Best-effort; a readdir failure must never break the materialization below.
396
- }
397
- }
398
-
399
- // 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.
400
- function materializeShrunkImage(context) {
401
- if (typeof context !== "string") return undefined
402
- const idx = context.indexOf("data:image/")
403
- if (idx === -1) return undefined
404
- const match = /^data:image\\/([a-zA-Z0-9.+-]+);base64,([A-Za-z0-9+/=]+)$/.exec(context.slice(idx).trim())
405
- if (!match) return undefined
406
- try {
407
- pruneMaterializedShrinks()
408
- const buf = Buffer.from(match[2], "base64")
409
- const name = \`token-goat-shrink-\${process.pid}-\${Date.now()}-\${globalThis.crypto.randomUUID()}.\${match[1]}\`
410
- const file = path.join(os.tmpdir(), name)
411
- // Owner-only: the copy is of a workspace image and sits in the shared temp dir.
412
- fs.writeFileSync(file, buf, { mode: 0o600 })
413
- return file
414
- } catch {
415
- return undefined
416
- }
417
- }`;
418
-
419
- // src/bridges/copilot_cli.ts
420
- var COPILOT_CLI_HOOK_SCRIPT = `#!/usr/bin/env node
421
- // token-goat Copilot CLI hook shim. Translates Copilot's hook event names and
422
- // request/response schema to/from token-goat's internal hook protocol.
423
- 'use strict'
424
- const { spawnSync } = require('node:child_process')
425
- const fs = require('node:fs')
426
- const os = require('node:os')
427
- const path = require('node:path')
428
- const { pathToFileURL } = require('node:url')
429
-
430
- // Copilot event name -> token-goat internal HookEventName (src/types.ts's
431
- // HOOK_EVENTS). Only these eight have a token-goat handler; every other real
432
- // Copilot event (sessionEnd, subagentStart, errorOccurred, notification,
433
- // permissionRequest) is left unimplemented
434
- // rather than guessed at, and falls through to the default no-op below.
435
- // postToolUseFailure is the newest of the eight and the only one whose channel
436
- // costs tokens instead of saving them: it fires instead of postToolUse when a
437
- // tool result is a failure, and accepts only additionalContext back --
438
- // modifiedResult and suppressOutput are not honored there, so a failed result
439
- // still cannot be fenced, compressed or shrunk. It is wired anyway because
440
- // additionalContext demonstrably reaches the model (see the postToolUseFailure
441
- // branch in translate() for the bundle offset), and hooks_tool_failure.ts
442
- // spends that channel only on an exact repeat failure, where staying silent
443
- // costs a whole wasted retry.
444
- // 'sessionStart' was previously a permanent no-op on the stated grounds that
445
- // token-goat has no internal session_start handler. That was simply wrong --
446
- // hooks_session_start.ts has long emitted the command-routing reminder that
447
- // every other harness receives -- and the no-op was the reason Copilot CLI
448
- // sessions alone never got told token-goat exists. It is wired now: verified
449
- // against Copilot CLI 1.0.77 that a hooks.json sessionStart entry returning
450
- // {additionalContext} does reach the model. The github/copilot-cli#2142
451
- // fire-and-forget bug that would have made this dead wiring was fixed in a
452
- // pre-release months before that version, and its companion multi-extension
453
- // hook-overwrite bug never applied here: it hit runtime *extension* hooks,
454
- // while this config-file hooks.json path goes through Copilot's own merge.
455
- const COPILOT_TO_TG_EVENT = {
456
- sessionStart: 'session_start',
457
- preToolUse: 'pre_tool_use',
458
- postToolUse: 'post_tool_use',
459
- preCompact: 'pre_compact',
460
- agentStop: 'stop',
461
- subagentStop: 'subagent_stop',
462
- userPromptSubmitted: 'user_prompt_submit',
463
- postToolUseFailure: 'post_tool_use_failure',
464
- }
465
-
466
- // Copilot built-in tool name -> token-goat internal tool name. Confirmed via
467
- // @github/copilot-sdk type definitions and multiple real GitHub issue payload
468
- // dumps -- supersedes an earlier docs-based guess (shell/read/write/url) that
469
- // didn't hold up in practice; 'write' in particular was never a real
470
- // toolName value, only a Copilot permission-pattern keyword. 'powershell'
471
- // maps to the same 'Bash' handler as 'bash' since both are shell-command
472
- // execution from token-goat's perspective (mirrors how hooks_bash.ts's own
473
- // filters already treat powershell-wrapped commands as part of the Bash
474
- // pipeline, not a separate tool). 'task', 'ask_user', 'memory', and
475
- // MCP-server tool invocations (<server-name>-<tool-name>) have no
476
- // token-goat equivalent and are passed through unmapped (safe no-op for
477
- // handlers that don't recognize the name).
478
- // 'read_bash'/'read_powershell' are the background-shell output pollers, and
479
- // they are the exact shape of Claude Code's BashOutput: Copilot's shell tool
480
- // is async, so a long-running command is started once and then re-read over
481
- // and over within one turn, each read returning the accumulated output again.
482
- // hooks_bashoutput.ts already collapses that into a delta (or a short
483
- // "unchanged" marker) for Claude Code, and now does the same here. Both the
484
- // names and the argument key were read out of the shipping 1.0.80 bundle
485
- // rather than guessed: the builtin tool-name table in
486
- // prebuilds/win32-x64/runtime.node lists read_bash/stop_bash/list_bash and
487
- // read_powershell/stop_powershell/list_powershell, and the poller's own input
488
- // schema in app.js is {shellId, delay} -- so the shell id needs the
489
- // POLL_ID_ARG_KEY remap below to reach postBashOutputHandler, which reads
490
- // 'bash_id'. read_shell/stop_shell/list_shells, which an earlier static sweep
491
- // of the same binary suggested were the real names, are internal Rust
492
- // identifiers (tool_read_shell_prepare_input, tool_list_shells_descriptor,
493
- // PreparedStopShellInput, and the serde field names of the shell config
494
- // struct), never wire tool names, so they are deliberately absent here.
495
- // stop_bash/list_bash and their powershell twins stay unmapped because
496
- // token-goat has no KillShell-equivalent handler for them to reach; a mapping
497
- // would be pure decoration.
498
- // 'bash'/'powershell' stay exactly as they were. The same sweep suggested the
499
- // executor had been renamed to write_bash/write_powershell and that this
500
- // mapping was dead, and that is not what the bundle says: app.js resolves the
501
- // executor as shellConfig?.shellToolName ?? "bash" (with "powershell" as the
502
- // Windows default of the same config), and its command lives under 'command'
503
- // exactly as hooks_bash.ts expects. write_bash/write_powershell are real tool
504
- // names, but they are a different tool -- their schema is {shellId, input,
505
- // delay} and the bundle files them under the subtype "write_shell", i.e. send
506
- // stdin to an already-running shell, not run a command. Mapping them to Bash
507
- // would label a stdin write as a shell execution, so they are left unmapped.
508
- // 'task', 'read_agent' and 'memory'-family tools are likewise left alone:
509
- // task's result is assembled in the native addon and its shape is unknown,
510
- // read_agent is an incremental poll that postAgentHandler is not written for,
511
- // and the real tool names behind memory were never confirmed. Each would put
512
- // a handler that rewrites model-visible output in front of a payload shape
513
- // nobody has seen, which is worse than leaving the compression on the table.
514
- // Own properties only, for every map in this shim -- see the event map in main() for why a
515
- // bare lookup on a plain object literal is not a gate. A tool named 'constructor' resolved to
516
- // a Function, which JSON.stringify drops, so the forwarded payload carried no tool_name and
517
- // every hook keyed on one no-opped; '__proto__' forwarded a whole prototype instead. The key
518
- // is third-party text: Copilot namespaces MCP tools as server:tool and the stripped half is
519
- // whatever that server called its tool.
520
- function ownGet(map, key) {
521
- return typeof key === 'string' && Object.prototype.hasOwnProperty.call(map, key) ? map[key] : undefined
522
- }
523
-
524
- const TOOL_TO_TG = {
525
- bash: 'Bash',
526
- powershell: 'Bash',
527
- read_bash: 'BashOutput',
528
- read_powershell: 'BashOutput',
529
- view: 'Read',
530
- create: 'Write',
531
- edit: 'Edit',
532
- web_fetch: 'WebFetch',
533
- web_search: 'WebSearch',
534
- grep: 'Grep',
535
- glob: 'Glob',
536
- skill: 'Skill',
537
- exit_plan_mode: 'ExitPlanMode',
538
- }
539
-
540
- function foldToolName(name) {
541
- return typeof name === 'string' ? name.toLowerCase().replace(/[_-]/g, '') : ''
542
- }
543
-
544
- const FOLDED_TOOL_TO_TG = {}
545
- for (const [k, v] of Object.entries(TOOL_TO_TG)) {
546
- FOLDED_TOOL_TO_TG[foldToolName(k)] = v
547
- }
548
- // Also register folded entries for canonical TG tool names directly (e.g. WebSearch -> websearch)
549
- for (const v of Object.values(TOOL_TO_TG)) {
550
- FOLDED_TOOL_TO_TG[foldToolName(v)] = v
551
- }
552
-
553
- function resolveCanonicalToolName(name) {
554
- if (!name || typeof name !== 'string') return name
555
- const direct = ownGet(TOOL_TO_TG, name)
556
- if (direct !== undefined) return direct
557
- const stripped = name.indexOf(':') !== -1 ? name.split(':').pop() : name
558
- const strippedDirect = ownGet(TOOL_TO_TG, stripped)
559
- if (strippedDirect !== undefined) return strippedDirect
560
- const folded = foldToolName(name)
561
- const foldedStripped = foldToolName(stripped)
562
- return ownGet(FOLDED_TOOL_TO_TG, folded) || ownGet(FOLDED_TOOL_TO_TG, foldedStripped) || name
563
- }
564
-
565
- // Confirmed via github/copilot-cli#3349 (open, unresolved as of writing): some
566
- // real Copilot CLI invocations send toolArgs as a JSON-*encoded string*
567
- // rather than a parsed object, contradicting the documented schema. Left
568
- // unhandled, canonical.tool_input would become a raw string and every
569
- // downstream event.toolInput[key] lookup in token-goat's handlers would
570
- // silently return undefined -- the deny/dedup mechanism would no-op with no
571
- // error surfaced. Parse it defensively; on a non-string, absent, or
572
- // unparsable value, fall back to {} rather than throwing (this shim's
573
- // convention throughout is fail-open, never crash on a malformed payload).
574
- function parseMaybeJsonObject(value) {
575
- if (value && typeof value === 'object') return value
576
- if (typeof value === 'string') {
577
- try {
578
- const parsed = JSON.parse(value)
579
- if (parsed && typeof parsed === 'object') return parsed
580
- } catch {
581
- // fall through to {}
582
- }
583
- }
584
- return {}
585
- }
586
-
587
- // view/edit/create send the file path under 'path'; every token-goat handler these
588
- // three tools reach only ever looks for 'file_path' (getFilePath in hooks_common.ts).
589
- // Keyed by the ORIGINAL Copilot tool name (before TOOL_TO_TG renames it) since that's
590
- // the name toolArgs' shape is keyed to, not token-goat's internal tool name.
591
- const FILE_PATH_ARG_KEY = {
592
- view: 'path',
593
- edit: 'path',
594
- create: 'path',
595
- }
596
-
597
- // read_bash/read_powershell send the background shell's id under 'shellId' (confirmed
598
- // against the poller's input schema in the shipping 1.0.80 app.js: {shellId, delay});
599
- // postBashOutputHandler reads 'bash_id'. Without this the tool-name mapping above would
600
- // be inert -- the handler bails on a missing bash_id and every poll would keep costing
601
- // the full accumulated output. Same keying convention as FILE_PATH_ARG_KEY: the ORIGINAL
602
- // Copilot tool name, since that is what the argument shape belongs to.
603
- const POLL_ID_ARG_KEY = {
604
- read_bash: 'shellId',
605
- read_powershell: 'shellId',
606
- }
607
-
608
- // Copilot spawns a brand-new process for every single hook invocation (no long-lived plugin
609
- // process the way OpenClaw's is -- OPENCLAW_HOOK_SCRIPT's own \`copilot-\${process.pid}-\${Date.now()}\`
610
- // fallback is safe there specifically because that process lives for the whole session, so the
611
- // pid stays constant across calls). If Copilot ever omits \`sessionId\` from a payload, falling
612
- // back to \`process.pid\` here would mint a DIFFERENT id on every single call for what's really
613
- // the same session, since process.pid varies per invocation -- breaking token-goat's
614
- // session-based dedup/state ledger, which never accumulates across calls as a result. Derive a
615
- // stable id instead from the one thing that's actually constant across calls for the same
616
- // session: the working directory Copilot reports. That field is \`workingDirectory\`, declared
617
- // required on BaseHookInput in copilot-sdk/types.d.ts since 1.0.76, so it is present on EVERY
618
- // hook event. This previously read \`payload.cwd\`, which Copilot has never sent under any name in
619
- // any version -- the key simply did not exist, so this derived every fallback id from
620
- // process.cwd() instead and \`canonical.cwd\` below was undefined on every single call. It went
621
- // unnoticed because process.cwd() happens to be the project directory Copilot spawns the hook in,
622
- // so the fallback was accidentally right; nothing about that was by design. \`cwd\` is still read
623
- // as a secondary in case a future version adds it under the shorter name.
624
- function stableFallbackSessionId(cwd) {
625
- const key = typeof cwd === 'string' && cwd ? cwd : process.cwd()
626
- const hash = require('node:crypto').createHash('sha256').update(key).digest('hex').slice(0, 16)
627
- return 'copilot-' + hash
628
- }
629
-
630
- function remapToolInput(copilotToolName, input) {
631
- if (!input || typeof input !== 'object') return input
632
- let out = input
633
- // Add the canonical key alongside the original rather than renaming it, so nothing that
634
- // might read the original 'path'/'shellId' key elsewhere (e.g. a future handler) loses it.
635
- const stripped = typeof copilotToolName === 'string' && copilotToolName.indexOf(':') !== -1
636
- ? copilotToolName.split(':').pop()
637
- : copilotToolName
638
- const folded = foldToolName(stripped)
639
- const pathKey = ownGet(FILE_PATH_ARG_KEY, copilotToolName) || ownGet(FILE_PATH_ARG_KEY, stripped) || (folded === 'view' || folded === 'edit' || folded === 'create' ? 'path' : undefined)
640
- if (pathKey !== undefined && pathKey in out) {
641
- out = Object.assign({}, out, { file_path: out[pathKey] })
642
- }
643
- const idKey = ownGet(POLL_ID_ARG_KEY, copilotToolName) || ownGet(POLL_ID_ARG_KEY, stripped) || (folded === 'readbash' || folded === 'readpowershell' ? 'shellId' : undefined)
644
- if (idKey !== undefined && idKey in out) {
645
- out = Object.assign({}, out, { bash_id: out[idKey] })
646
- }
647
- if (Array.isArray(out.view_range) && out.view_range.length >= 1) {
648
- const rawStart = Number(out.view_range[0])
649
- if (Number.isFinite(rawStart) && rawStart >= 1) {
650
- const mapped = { offset: Math.floor(rawStart) }
651
- if (out.view_range.length >= 2) {
652
- const rawEnd = Number(out.view_range[1])
653
- if (Number.isFinite(rawEnd) && rawEnd >= rawStart) {
654
- mapped.limit = Math.floor(rawEnd - rawStart + 1)
655
- }
656
- }
657
- out = Object.assign({}, out, mapped)
658
- }
659
- }
660
- if ('old_str' in out && !('old_string' in out)) {
661
- out = Object.assign({}, out, { old_string: out.old_str })
662
- }
663
- if ('new_str' in out && !('new_string' in out)) {
664
- out = Object.assign({}, out, { new_string: out.new_str })
665
- }
666
- return out
667
- }
668
-
669
- // Attempts the in-process hook call: import()s dist/token-goat-hook.mjs (a sibling of
670
- // the baked token-goat entry path, built with zero load-time side effects -- unlike
671
- // the CLI entry, which runs the full argv-parsing CLI as a side effect of being
672
- // loaded) and calls its exported relayInProcess() directly, avoiding a second node
673
- // process spawn entirely. Returns undefined (triggering the spawnSync fallback below)
674
- // when entryPath is absent, the sibling file doesn't exist (an older install predating
675
- // this file), or anything else goes wrong -- this must never throw.
676
- async function tryInProcess(entryPath, tgEvent, canonical, harness) {
677
- if (!entryPath) return undefined
678
- try {
679
- const hookLibPath = path.join(path.dirname(entryPath), 'token-goat-hook.mjs')
680
- if (!require('node:fs').existsSync(hookLibPath)) return undefined
681
- const mod = await import(pathToFileURL(hookLibPath).href)
682
- process.env.TOKEN_GOAT_HARNESS_OVERRIDE = harness
683
- // Which hooks directory VS Code loaded this shim from is the only thing separating a
684
- // user-scope copy from a project-scope one -- the two files are byte-identical and so are
685
- // their payloads. vscode_duplicate.ts needs it to stand the redundant copy down.
686
- if (harness === 'vscode') process.env.TOKEN_GOAT_VSCODE_HOOKS_DIR = __dirname
687
- return await mod.relayInProcess(tgEvent, canonical)
688
- } catch {
689
- return undefined
690
- }
691
- }
692
-
693
- // VS Code's built-in agent reads this same hooks file (~/.copilot/hooks and .github/hooks are both
694
- // on its hook-source list) and runs these same entries, but it sends Claude Code's payload shape:
695
- // hook_event_name, session_id, tool_name, tool_input, tool_response. Copilot CLI's payload never
696
- // carries hook_event_name and always names its tool in toolName, so that pair tells them apart.
697
- // The payload goes to token-goat as-is under the vscode harness, which does its own tool-name
698
- // mapping and writes a response VS Code reads directly, so nothing here translates it.
699
- function isVscodePayload(payload) {
700
- return payload !== null && typeof payload === 'object' && typeof payload.hook_event_name === 'string' && payload.toolName === undefined
701
- }
702
-
703
- async function relayVscode(entryPath, tgEvent, payload) {
704
- // 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.
705
- const input = typeof payload.session_id === 'string' && payload.session_id !== ''
706
- ? payload
707
- : Object.assign({}, payload, { session_id: stableFallbackSessionId(process.cwd()) })
708
- let stdout = await tryInProcess(entryPath, tgEvent, input, 'vscode')
709
- if (stdout === undefined) {
710
- // 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.
711
- const spawnOpts = {
712
- input: JSON.stringify(input),
713
- encoding: 'utf8',
714
- windowsHide: true,
715
- timeout: 3000,
716
- killSignal: 'SIGKILL',
717
- maxBuffer: 32 * 1024 * 1024,
718
- env: Object.assign({}, process.env, { TOKEN_GOAT_HARNESS_OVERRIDE: 'vscode', TOKEN_GOAT_VSCODE_HOOKS_DIR: __dirname }),
719
- }
720
- const res = entryPath
721
- ? spawnSync(process.execPath, [entryPath, 'hook', tgEvent, '--harness', 'vscode'], spawnOpts)
722
- : spawnSync('token-goat hook ' + tgEvent + ' --harness vscode', Object.assign({ shell: true }, spawnOpts))
723
- if (res.status !== 0 || !res.stdout) return '{}'
724
- stdout = res.stdout
725
- }
726
- try {
727
- const parsed = JSON.parse(stdout)
728
- return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? JSON.stringify(parsed) : '{}'
729
- } catch {
730
- return '{}'
731
- }
732
- }
733
-
734
- async function main() {
735
- const copilotEvent = process.argv[2] || ''
736
-
737
- // 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.
738
- const tgEvent = ownGet(COPILOT_TO_TG_EVENT, copilotEvent)
739
- if (!tgEvent) {
740
- process.stdout.write('{}')
741
- return
742
- }
743
-
744
- let raw = ''
745
- try {
746
- raw = require('node:fs').readFileSync(0, 'utf8')
747
- } catch {
748
- process.stdout.write('{}')
749
- return
750
- }
751
-
752
- let payload
753
- try {
754
- payload = JSON.parse(raw)
755
- } catch {
756
- process.stdout.write('{}')
757
- return
758
- }
759
-
760
- if (isVscodePayload(payload)) {
761
- process.stdout.write(await relayVscode(process.argv[3], tgEvent, payload))
762
- return
763
- }
764
-
765
- const toolName = payload && payload.toolName
766
- const canonical = {
767
- session_id:
768
- (payload && payload.sessionId) ||
769
- stableFallbackSessionId(payload && (payload.workingDirectory || payload.cwd)),
770
- cwd: payload && (payload.workingDirectory || payload.cwd),
771
- }
772
-
773
- // Subagent correlation and W3C Trace Context propagation from Copilot CLI payloads
774
- const agentId = payload && (payload.agent_id || payload.agentId)
775
- if (typeof agentId === 'string' && agentId !== '') {
776
- canonical.agent_id = agentId
777
- }
778
- const traceparent = payload && (payload.traceparent || payload.traceParent)
779
- if (typeof traceparent === 'string' && traceparent !== '') {
780
- canonical.traceparent = traceparent
781
- }
782
- const tracestate = payload && (payload.tracestate || payload.traceState)
783
- if (typeof tracestate === 'string' && tracestate !== '') {
784
- canonical.tracestate = tracestate
785
- }
786
-
787
- // userPromptSubmitted only: Copilot declares \`prompt\` required on UserPromptSubmittedHookInput.
788
- // hooks_session.ts's userPromptSubmitHandler reads it as \`event.raw['prompt']\` and gates every
789
- // branch it has on the text, so without this it saw '' on every Copilot prompt and the
790
- // embedded-skill dedup hint could never fire. Same shape as the postToolUseFailure \`error\`
791
- // drop: a required field the canonical builder simply did not list.
792
- if (typeof (payload && payload.prompt) === 'string' && payload.prompt !== '') {
793
- canonical.prompt = payload.prompt
794
- }
795
- let originalToolArgs = {}
796
- if (toolName) {
797
- originalToolArgs = parseMaybeJsonObject(payload && payload.toolArgs)
798
- canonical.tool_name = resolveCanonicalToolName(toolName)
799
- canonical.tool_input = remapToolInput(toolName, originalToolArgs)
800
- }
801
-
802
- // postToolUse only: confirmed via https://docs.github.com/en/copilot/reference/hooks-reference
803
- // that Copilot's toolResult is an object ({resultType, textResultForLlm}), not a bare string
804
- // or array. Without this, token-goat's tool_response consumers (hooks_read.ts's
805
- // extractReadOutput, hooks_bash.ts's extractBashOutput, etc. -- all of which check for a
806
- // string or an object keyed by output/content/text/body) never see any content, so
807
- // post-read/post-bash stats stay empty no matter how many tool calls happen. Extract the
808
- // LLM-facing text directly rather than forwarding the raw object, since textResultForLlm
809
- // isn't one of those recognized object keys.
810
- // postToolUseFailure only: Copilot's PostToolUseFailureHookInput (copilot-sdk/types.d.ts:1042)
811
- // carries {toolName, toolArgs, error} and no toolResult at all -- the failure text lives in
812
- // \`error\`, a plain string. Without forwarding it, hooks_tool_failure.ts's extractFailureText
813
- // finds nothing to key on and the repeat-failure brake returns pass on every single call: wired,
814
- // green, and doing nothing. Found by driving the installed shim rather than by a test, because
815
- // the handler's own tests hand it a raw payload that already has the field.
816
- if (typeof (payload && payload.error) === 'string' && payload.error !== '') {
817
- canonical.error = payload.error
818
- }
819
-
820
- const rawResult = payload && payload.toolResult
821
- if (rawResult && typeof rawResult === 'object') {
822
- const tr = rawResult
823
- // text_result_for_llm: Copilot's docs also describe a "VS Code compatible" snake_case
824
- // wire format (tool_result.text_result_for_llm) alongside the camelCase one above; try
825
- // both rather than assuming only the camelCase shape ever reaches this shim.
826
- const text = typeof tr.textResultForLlm === 'string' ? tr.textResultForLlm : tr.text_result_for_llm
827
- if (typeof text === 'string') canonical.tool_response = text
828
- }
829
-
830
- // process.argv[3], when present, is the absolute path to the token-goat CLI entry that ran
831
- // \`token-goat install --copilot\` (baked in by hookCommandFor in copilot_cli_install.ts).
832
- // Invoking it directly via process.execPath sidesteps PATH/cmd.exe resolution for this
833
- // inner call too -- confirmed live-production root cause of an *intermittent* (not the
834
- // original, already-fixed github/copilot-cli#4001) "(hook errored)" deny-all: even once the
835
- // outer command launches via its own baked process.execPath, this inner call still shelled
836
- // out to a bare \`token-goat\`, which depends on the npm global bin being on whatever PATH
837
- // Copilot spawns this hook subprocess with. Falls back to the old PATH-based shell:true
838
- // invocation when argv[3] is absent (an older cached hook config still pointing at a
839
- // freshly-reinstalled shim, or a direct dev/test invocation), so this is a pure hardening,
840
- // never a behavior break for configs installed before this fix. An args array (not a
841
- // template string) is safe here specifically because entryPath and tgEvent never touch a
842
- // shell -- no DEP0190 concern, unlike the shell:true fallback below.
843
- const entryPath = process.argv[3]
844
- // Try the in-process hook lib first (tryInProcess above), which avoids spawning a
845
- // second node process altogether. If that's unavailable, invoking the entry directly
846
- // via process.execPath sidesteps PATH/cmd.exe resolution for this inner call, per the
847
- // note above this function's original single-spawn form documented. A 3000ms
848
- // timeout/killSignal on both spawnSync fallbacks keeps them well under Copilot CLI's
849
- // own hook timeout budget (~30000ms), so token-goat degrades to its own fail-open
850
- // '{}' rather than being force-killed by Copilot first.
851
- let stdout = await tryInProcess(entryPath, tgEvent, canonical, 'copilot_cli')
852
- if (stdout === undefined) {
853
- const res = entryPath
854
- ? spawnSync(process.execPath, [entryPath, 'hook', tgEvent], {
855
- input: JSON.stringify(canonical),
856
- encoding: 'utf8',
857
- windowsHide: true,
858
- timeout: 3000,
859
- killSignal: 'SIGKILL',
860
- maxBuffer: 32 * 1024 * 1024,
861
- env: Object.assign({}, process.env, { TOKEN_GOAT_HARNESS_OVERRIDE: 'copilot_cli' }),
862
- })
863
- : spawnSync('token-goat hook ' + tgEvent, {
864
- input: JSON.stringify(canonical),
865
- encoding: 'utf8',
866
- shell: true,
867
- windowsHide: true,
868
- timeout: 3000,
869
- killSignal: 'SIGKILL',
870
- maxBuffer: 32 * 1024 * 1024,
871
- env: Object.assign({}, process.env, { TOKEN_GOAT_HARNESS_OVERRIDE: 'copilot_cli' }),
872
- })
873
- if (res.status !== 0 || !res.stdout) {
874
- process.stdout.write('{}')
875
- return
876
- }
877
- stdout = res.stdout
878
- }
879
-
880
- let resp
881
- try {
882
- resp = JSON.parse(stdout)
883
- } catch {
884
- process.stdout.write('{}')
885
- return
886
- }
887
-
888
- process.stdout.write(JSON.stringify(translate(copilotEvent, resp, toolName, originalToolArgs, payload)))
889
- }
890
-
891
- ${MATERIALIZE_SHRUNK_IMAGE_JS}
892
-
893
- function translate(copilotEvent, resp, toolName, originalToolArgs, payload) {
894
- if (copilotEvent === 'preToolUse') {
895
- const hso = resp && resp.hookSpecificOutput
896
- const denied = resp && (resp.decision === 'block' || (hso && hso.permissionDecision === 'deny'))
897
- if (denied) {
898
- const reason =
899
- (resp && resp.reason) || (hso && hso.permissionDecisionReason) || 'blocked by token-goat'
900
- return { permissionDecision: 'deny', permissionDecisionReason: reason }
901
- }
902
- const context = extractContext(resp)
903
- // 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.
904
- const shrinkPayload = typeof context === 'string' && context.indexOf('data:image/') !== -1
905
- const out = {}
906
- const updated = hso && hso.updatedInput
907
- if (updated && typeof updated === 'object') {
908
- out.modifiedArgs = updated
909
- } else if (shrinkPayload && (toolName === 'view' || foldToolName(toolName) === 'view')) {
910
- // 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.
911
- const shrunkPath = materializeShrunkImage(context)
912
- if (shrunkPath) out.modifiedArgs = Object.assign({}, originalToolArgs, { path: shrunkPath })
913
- }
914
- // 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.
915
- if (context && !shrinkPayload) out.additionalContext = context
916
- return out
917
- }
918
-
919
- if (copilotEvent === 'postToolUse') {
920
- // modifiedResult is honored on success: rewriteOutput (compression, fencing, image shrink) reaches LLM.
921
- // additionalContext is dropped on Copilot CLI JS path, so the ONLY channel that reaches the model here is
922
- // modifiedResult.textResultForLlm, and the body that goes into it is chosen before the fold rather than
923
- // instead of it. The two used to be alternatives -- a rewritten output took the first branch and skipped the
924
- // fold entirely -- so any response carrying both a compressed body and a hint delivered the body and dropped
925
- // the hint on the floor, silently, on the one harness this whole fold exists for. Pick the body (rewritten if
926
- // there is one, else the original), then append the hint to whichever it was.
927
- const hso = resp && resp.hookSpecificOutput
928
- const updatedToolOutput = hso && hso.updatedToolOutput
929
- const context = extractContext(resp)
930
- const out = {}
931
- const rawResult = payload && payload.toolResult
932
- // Copilot's own ToolResult type is a union of a bare string and ToolResultObject (copilot-sdk/types.d.ts), so a string is a shape the harness itself admits even though PostToolUseHookInput narrows this field to the object form. Reading it as a body costs one typeof and removes the only route by which body could come back undefined on a well-formed payload: in every version this bridge has been checked against (1.0.80, 1.0.82, 1.0.86, 1.0.87, 1.0.88) ToolResultObject declares textResultForLlm as a required string rather than an optional one, so the object form always carries a body and the hint always has something to be folded into.
933
- const originalText =
934
- typeof rawResult === 'string'
935
- ? rawResult
936
- : rawResult && (typeof rawResult.textResultForLlm === 'string' ? rawResult.textResultForLlm : typeof rawResult.text_result_for_llm === 'string' ? rawResult.text_result_for_llm : undefined)
937
- const rewritten = typeof updatedToolOutput === 'string'
938
- const body = rewritten ? updatedToolOutput : typeof originalText === 'string' ? originalText : undefined
939
- // Never claim a modification we did not make: with no rewrite and no hint, the body would be the tool's own
940
- // text handed back verbatim, and a pass-through modifiedResult is a lie about authorship on every call.
941
- if (typeof body === 'string' && (rewritten || context)) {
942
- out.modifiedResult = { resultType: 'success', textResultForLlm: context ? body + '\\n\\n[token-goat: ' + context + ']' : body }
943
- }
944
- // Still set alongside the fold rather than instead of it: the field is dropped on the JS path read at 1.0.80,
945
- // but it is the documented channel and costs nothing if a later release starts honoring it. The fold above is
946
- // what the delivery guarantee rests on.
947
- if (context) out.additionalContext = context
948
- return out
949
- }
950
-
951
- if (copilotEvent === 'postToolUseFailure') {
952
- // The failed-tool twin of postToolUse, and the only response field it accepts is
953
- // additionalContext: the shipped copilot-sdk/types.d.ts says "modifiedResult or suppressOutput
954
- // are not honored for failure hooks", so nothing here can fence, compress or shrink the failed
955
- // output -- that gap is real and stays open. What is NOT open, and was the reason this event
956
- // went unwired for so long, is whether additionalContext reaches the model at all. It does:
957
- // app.js 1.0.80 at offset 2043380 either folds it into textResultForLlm (when
958
- // appendFailureContextToToolResult is set) or has the native
959
- // hookAppendPostToolUseFailureContext push {content, source:'system'} onto
960
- // toolResult.newMessages. That is the exact opposite of postToolUse, whose additionalContext
961
- // the JS side drops on the floor, so neither event's behaviour generalises to the other.
962
- //
963
- // Because this channel spends tokens rather than saving them, the handler behind it
964
- // (hooks_tool_failure.ts) is silent on a first failure and speaks only on an exact repeat.
965
- const context = extractContext(resp)
966
- if (context) return { additionalContext: context }
967
- return {}
968
- }
969
-
970
- if (copilotEvent === 'sessionStart') {
971
- // sessionStart has no tool result to modify -- only additionalContext applies, and it's the
972
- // one channel that reaches the model before it picks its first read tool, so this is where
973
- // the routing reminder has to land.
974
- const context = extractContext(resp)
975
- if (context) return { additionalContext: context }
976
- return {}
977
- }
978
-
979
- if (copilotEvent === 'agentStop' || copilotEvent === 'subagentStop') {
980
- // Confirmed against the hooks reference doc: the only accepted response
981
- // shape for these two events is {decision, reason} -- additionalContext
982
- // is not part of their schema and Copilot silently ignores it there.
983
- // token-goat's internal 'stop'/'subagent_stop' handlers never return a
984
- // real deny today (subagentStopHandler only ever logs and passes), but a
985
- // future deny is mapped through here rather than silently dropped.
986
- if (resp && resp.decision === 'block') {
987
- const reason = (resp && resp.reason) || 'blocked by token-goat'
988
- return { decision: 'block', reason: reason }
989
- }
990
- return { decision: 'allow' }
991
- }
992
-
993
- if (copilotEvent === 'userPromptSubmitted') {
994
- // Copilot's own hooks reference says command-hook output here "is dropped, including
995
- // modifiedPrompt", and this branch used to believe it and return nothing. That is wrong for
996
- // additionalContext on 1.0.80, established by experiment rather than by reading: a config-file
997
- // command hook (at <cwd>/.github/hooks/, the project scope -- the user scope ~/.copilot/hooks/
998
- // was never exercised) returned {"additionalContext":"<marker>"} and the marker turned up
999
- // verbatim inside the session's user.message.transformedContent, wrapped in a
1000
- // <system_reminder> block. What settles that it reached the model rather than only the on-disk
1001
- // record is the billing: the provider's returned usage charged ~140 input tokens for a turn
1002
- // whose raw content field is 35 bytes, so the marker's bytes were paid for whichever field
1003
- // carried them. (The weaker argument first offered for this -- that transformedContent carries
1004
- // an envelope the content field lacks, 29 B vs 195 B -- was measured on the control turn that
1005
- // had no marker in it, and proves nothing about the marker.) That the model sees it is the
1006
- // whole point: hook.start/hook.end records also persist and reach nothing.
1007
- //
1008
- // Scope of the finding, stated honestly: demonstrated ONCE on 1.0.80, not shown to be
1009
- // reliable. Of two turns in that experiment, one delivered the marker and one fired a
1010
- // userPromptSubmitted hook that produced no output and never ran the script; no explanation
1011
- // was established and the rate is unknown. A hint that silently fails to arrive costs nothing
1012
- // and breaks nothing here, which is why the direct return is still the right default.
1013
- //
1014
- // modifiedPrompt is NOT claimed to work and is not wanted: rewriting a user's prompt is far
1015
- // more invasive than anything token-goat does, so only additionalContext is forwarded.
1016
- //
1017
- // This is also the write end of any post-compaction channel. Copilot has no postCompact hook.
1018
- // Whether the summary is recoverable from events.jsonl is NOT settled -- the emit()/
1019
- // emitEphemeral() distinction does not gate the writer, and the real decision is in native
1020
- // code; see COPILOT_NO_POST_COMPACT_REASON in ../bridges_status.ts for what was and was not
1021
- // established. The read end that IS confirmed is preCompact, which fires as a notification, so
1022
- // a manifest can be built there and drained here without reading the event log at all.
1023
- const context = extractContext(resp)
1024
- if (context) return { additionalContext: context }
1025
- return {}
1026
- }
1027
-
1028
- // preCompact is the genuine notification-only case, and the contrast with userPromptSubmitted
1029
- // above is why this fallthrough is worth a comment at all. The hooks reference marks it
1030
- // "No -- notification only" for output processing, and unlike the additionalContext claim that
1031
- // turned out to be false, this one is confirmed in the shipping bundle: both preCompact call
1032
- // sites in app.js (1.0.79 and re-checked in 1.0.80) await the hook and never assign its result.
1033
- // There is no field to aim at here, so nothing to reconsider on the next version bump.
1034
- return {}
1035
- }
1036
-
1037
- function extractContext(resp) {
1038
- const hso = resp && resp.hookSpecificOutput
1039
- if (hso && typeof hso.additionalContext === 'string') return hso.additionalContext
1040
- if (resp && typeof resp.systemMessage === 'string') return resp.systemMessage
1041
- return undefined
1042
- }
1043
-
1044
- // Hard outer safety net, on top of main()'s own per-step try/catch fallbacks
1045
- // (JSON.parse, readFileSync, spawnSync): a hook error must never itself cause
1046
- // Copilot's fail-closed "(hook errored)" behavior, which denies EVERY tool
1047
- // call unconditionally (the exact live-production failure mode behind
1048
- // github/copilot-cli#4001). Any uncaught exception anywhere in this script --
1049
- // including one a future code path adds that the existing per-step guards
1050
- // don't anticipate -- still guarantees stdout gets valid JSON and the
1051
- // process exits 0. process.exitCode is set explicitly and unconditionally at
1052
- // the very end of every path so nothing upstream (e.g. an unhandled-rejection
1053
- // warning in some Node versions nudging exit-code inference) can flip it.
1054
- main()
1055
- .catch(() => {
1056
- try {
1057
- process.stdout.write('{}')
1058
- } catch {
1059
- // stdout itself is broken; nothing more can be done here.
1060
- }
1061
- })
1062
- .finally(() => {
1063
- process.exitCode = 0
1064
- })
1065
- `;
1066
- var TOOL_TO_TG_MAPPING = COPILOT_CLI_TOOL_NAME_MAP;
1067
- var FOLDED_MAPPING = {};
1068
- for (const [k, v] of Object.entries(TOOL_TO_TG_MAPPING)) {
1069
- FOLDED_MAPPING[foldToolName(k)] = v;
1070
- FOLDED_MAPPING[foldToolName(v)] = v;
1071
- }
1072
-
1073
- // src/bridges/copilot_cli_install.ts
1074
- var COPILOT_CLI_HOOK_EVENTS = [
1075
- "sessionStart",
1076
- "preToolUse",
1077
- "postToolUse",
1078
- "preCompact",
1079
- "agentStop",
1080
- "subagentStop",
1081
- "userPromptSubmitted",
1082
- "postToolUseFailure"
1083
- ];
1084
- function copilotCliUserRoot() {
1085
- const override = process.env["COPILOT_HOME"];
1086
- if (override !== void 0 && override.trim() !== "") return path3.resolve(override);
1087
- return path3.join(os2.homedir(), ".copilot");
1088
- }
1089
- function copilotCliUserHooksDir() {
1090
- return path3.join(copilotCliUserRoot(), "hooks");
1091
- }
1092
- function copilotCliProjectHooksDir() {
1093
- return path3.join(process.cwd(), ".github", "hooks");
1094
- }
1095
- function copilotCliCacheRoot() {
1096
- const override = process.env["COPILOT_CACHE_HOME"];
1097
- if (override !== void 0 && override.trim() !== "") return path3.resolve(override);
1098
- const home = os2.homedir();
1099
- if (process.platform === "darwin") return path3.join(home, "Library", "Caches", "copilot");
1100
- if (process.platform === "win32") {
1101
- const local = process.env["LOCALAPPDATA"];
1102
- const base2 = local !== void 0 && local.trim() !== "" ? local : path3.join(home, ".cache");
1103
- return path3.join(base2, "copilot");
1104
- }
1105
- const xdg = process.env["XDG_CACHE_HOME"];
1106
- const base = xdg !== void 0 && xdg.trim() !== "" ? xdg : path3.join(home, ".cache");
1107
- return path3.join(base, "copilot");
1108
- }
1109
- function copilotCliMcpToolsDir() {
1110
- return path3.join(copilotCliCacheRoot(), "mcp-tools");
1111
- }
1112
- function copilotCliHooksDir(opts = {}) {
1113
- return opts.local === true ? copilotCliProjectHooksDir() : copilotCliUserHooksDir();
1114
- }
1115
- function copilotCliConfigPath(opts = {}) {
1116
- return path3.join(copilotCliHooksDir(opts), HOOKS_CONFIG_FILE);
1117
- }
1118
- function copilotCliScriptPath(opts = {}) {
1119
- return path3.join(copilotCliHooksDir(opts), HOOKS_SCRIPT_FILE);
1120
- }
1121
- function copilotCliInstructionsPath(opts = {}) {
1122
- return path3.join(path3.dirname(copilotCliHooksDir(opts)), "copilot-instructions.md");
1123
- }
1124
- var COPILOT_INSTRUCTIONS_BEGIN = "<!-- token-goat-begin -->";
1125
- var COPILOT_INSTRUCTIONS_END = "<!-- token-goat-end -->";
1126
- function buildCopilotInstructionsBlock() {
1127
- return stripInlineCodeSpans(
1128
- buildGuidanceBlock({
1129
- beginMarker: COPILOT_INSTRUCTIONS_BEGIN,
1130
- endMarker: COPILOT_INSTRUCTIONS_END,
1131
- fallbackToolClause: "Copilot CLI's native `view`, `grep`, and `glob` tools (with PowerShell commands `Get-Content`/`Select-String` as search fallbacks)",
1132
- gdrive: loadConfig().gdrive.enabled
1133
- })
1134
- );
1135
- }
1136
- function stripInlineCodeSpans(text) {
1137
- return text.replace(/`([^`]+)`/g, "$1");
1138
- }
1139
- function writeCopilotInstructionsBlock(p) {
1140
- const changed = upsertDelimitedBlock(p, COPILOT_INSTRUCTIONS_BEGIN, COPILOT_INSTRUCTIONS_END, buildCopilotInstructionsBlock());
1141
- const visualStudioChanged = syncVisualStudioProjectGuidance(p);
1142
- return changed || visualStudioChanged;
1143
- }
1144
- function stripCopilotInstructionsBlock(p) {
1145
- const removed = stripDelimitedBlock(p, COPILOT_INSTRUCTIONS_BEGIN, COPILOT_INSTRUCTIONS_END);
1146
- if (removed) syncVisualStudioProjectGuidance(p);
1147
- return removed;
1148
- }
1149
- function hookPowershellCommandFor(scriptPath, event) {
1150
- return `& ${hookPowershellCommand(scriptPath, event)}`;
1151
- }
1152
- var HOOK_TIMEOUT_SEC = 60;
1153
- var ALLOWED_ENV_VARS = [
1154
- "TRACEPARENT",
1155
- "TRACESTATE",
1156
- "COPILOT_HOME",
1157
- "COPILOT_CACHE_HOME",
1158
- "TOKEN_GOAT_LOG"
1159
- ];
1160
- function buildConfig(scriptPath) {
1161
- const hooks = {};
1162
- for (const event of COPILOT_CLI_HOOK_EVENTS) {
1163
- hooks[event] = [
1164
- {
1165
- type: "command",
1166
- command: hookCommandFor(scriptPath, event),
1167
- bash: hookCommandFor(scriptPath, event),
1168
- powershell: hookPowershellCommandFor(scriptPath, event),
1169
- timeoutSec: HOOK_TIMEOUT_SEC,
1170
- allowedEnvVars: [...ALLOWED_ENV_VARS]
1171
- }
1172
- ];
1173
- }
1174
- return { version: 1, hooks };
1175
- }
1176
- var HOOKS_CONFIG_FILE = "token-goat.json";
1177
- var HOOKS_SCRIPT_FILE = "token-goat-shim.js";
1178
- var HOOKS_OWNERS_FILE = "token-goat.owners";
1179
- function copilotHooksOwnersPath(hooksDir) {
1180
- return path3.join(hooksDir, HOOKS_OWNERS_FILE);
1181
- }
1182
- function copilotHooksFilePaths(hooksDir) {
1183
- return [path3.join(hooksDir, HOOKS_CONFIG_FILE), path3.join(hooksDir, HOOKS_SCRIPT_FILE), copilotHooksOwnersPath(hooksDir)];
1184
- }
1185
- function readCopilotHooksOwners(hooksDir) {
1186
- const owners = /* @__PURE__ */ new Set();
1187
- let text;
1188
- try {
1189
- text = fs3.readFileSync(copilotHooksOwnersPath(hooksDir), "utf8");
1190
- } catch {
1191
- if (fs3.existsSync(path3.join(hooksDir, HOOKS_CONFIG_FILE))) owners.add("copilot");
1192
- return owners;
1193
- }
1194
- for (const line of text.split(/\r?\n/)) {
1195
- const name = line.trim();
1196
- if (name === "copilot" || name === "vscode") owners.add(name);
1197
- }
1198
- return owners;
1199
- }
1200
- function installCopilotHooksFile(hooksDir, owner) {
1201
- const configPath = path3.join(hooksDir, HOOKS_CONFIG_FILE);
1202
- const scriptPath = path3.join(hooksDir, HOOKS_SCRIPT_FILE);
1203
- const owners = readCopilotHooksOwners(hooksDir);
1204
- const scriptChanged = writeIfDifferent(scriptPath, COPILOT_CLI_HOOK_SCRIPT);
1205
- const desiredText = JSON.stringify(buildConfig(scriptPath), null, 2) + "\n";
1206
- const configChanged = writeIfDifferent(configPath, desiredText, true);
1207
- recordCreatedConfig(configPath);
1208
- owners.add(owner);
1209
- const ownersChanged = writeIfDifferent(copilotHooksOwnersPath(hooksDir), [...owners].sort().join("\n") + "\n");
1210
- return { configPath, scriptPath, changed: scriptChanged || configChanged || ownersChanged };
1211
- }
1212
- function releaseCopilotHooksFile(hooksDir, owner, keepBackups = false) {
1213
- const ownersPath = copilotHooksOwnersPath(hooksDir);
1214
- const hadSidecar = fs3.existsSync(ownersPath);
1215
- const owners = readCopilotHooksOwners(hooksDir);
1216
- if (!owners.has(owner) && (hadSidecar || owner !== "copilot")) return false;
1217
- owners.delete(owner);
1218
- if (owners.size > 0) {
1219
- writeIfDifferent(ownersPath, [...owners].sort().join("\n") + "\n");
1220
- return true;
1221
- }
1222
- const configRemoved = removeFileInScope(path3.join(hooksDir, HOOKS_CONFIG_FILE));
1223
- if (!keepBackups) removeCreatedBackups(path3.join(hooksDir, HOOKS_CONFIG_FILE));
1224
- takeCreatedConfig(path3.join(hooksDir, HOOKS_CONFIG_FILE));
1225
- const scriptRemoved = removeFileInScope(path3.join(hooksDir, HOOKS_SCRIPT_FILE));
1226
- const ownersRemoved = removeFileInScope(ownersPath);
1227
- return configRemoved || scriptRemoved || ownersRemoved;
1228
- }
1229
- function installCopilotCli(opts = {}) {
1230
- return withInstallScope(projectScopeRoot(opts), () => installCopilotCliScoped(opts));
1231
- }
1232
- function installCopilotCliScoped(opts) {
1233
- const instructionsPath = copilotCliInstructionsPath(opts);
1234
- const hooks = installCopilotHooksFile(copilotCliHooksDir(opts), "copilot");
1235
- const instructionsChanged = writeCopilotInstructionsBlock(instructionsPath);
1236
- return {
1237
- configPath: hooks.configPath,
1238
- scriptPath: hooks.scriptPath,
1239
- instructionsPath,
1240
- alreadyInstalled: !hooks.changed && !instructionsChanged
1241
- };
1242
- }
1243
- function uninstallCopilotCliScope(opts) {
1244
- return withInstallScope(projectScopeRoot(opts), () => uninstallCopilotCliScopeInner(opts));
1245
- }
1246
- function uninstallCopilotCliScopeInner(opts) {
1247
- let removedAny = releaseCopilotHooksFile(copilotCliHooksDir(opts), "copilot");
1248
- if (stripCopilotInstructionsBlock(copilotCliInstructionsPath(opts))) {
1249
- removedAny = true;
1250
- }
1251
- return removedAny;
1252
- }
1253
- function uninstallCopilotCli(opts = {}) {
1254
- if (opts.local === true) {
1255
- return uninstallCopilotCliScope({ local: true });
1256
- }
1257
- const userRemoved = uninstallCopilotCliScope({ local: false });
1258
- const localRemoved = uninstallCopilotCliScope({ local: true });
1259
- return userRemoved || localRemoved;
1260
- }
1261
- function isCopilotCliInstalled(opts = {}) {
1262
- if (!fs3.existsSync(copilotCliConfigPath(opts)) || !fs3.existsSync(copilotCliScriptPath(opts))) {
1263
- return false;
1264
- }
1265
- if (!readCopilotHooksOwners(copilotCliHooksDir(opts)).has("copilot")) return false;
1266
- let instructions;
1267
- try {
1268
- instructions = fs3.readFileSync(copilotCliInstructionsPath(opts), "utf8");
1269
- } catch {
1270
- return false;
1271
- }
1272
- return instructions.includes(COPILOT_INSTRUCTIONS_BEGIN) && instructions.includes(COPILOT_INSTRUCTIONS_END);
1273
- }
1274
-
1275
- // src/copilot_mcp_tools.ts
1276
- init_define_import_meta_env();
1277
- import fs4 from "node:fs";
1278
- import path4 from "node:path";
1279
- function wireShapeLength(tools) {
1280
- const wire = tools.map((tool) => {
1281
- const out = {};
1282
- if (typeof tool.name === "string") out["name"] = tool.name;
1283
- if (typeof tool.description === "string") out["description"] = tool.description;
1284
- if (tool.inputSchema !== void 0) out["inputSchema"] = tool.inputSchema;
1285
- return out;
1286
- });
1287
- return JSON.stringify(wire).length;
1288
- }
1289
- function readCopilotMcpTools(dir = copilotCliMcpToolsDir()) {
1290
- let entries;
1291
- try {
1292
- entries = fs4.readdirSync(dir);
1293
- } catch {
1294
- return { cacheFound: false, servers: [], unreadable: 0 };
1295
- }
1296
- const newest = /* @__PURE__ */ new Map();
1297
- let unreadable = 0;
1298
- for (const entry of entries) {
1299
- if (!entry.toLowerCase().endsWith(".json")) continue;
1300
- let parsed;
1301
- try {
1302
- parsed = JSON.parse(fs4.readFileSync(path4.join(dir, entry), "utf8"));
1303
- } catch {
1304
- unreadable += 1;
1305
- continue;
1306
- }
1307
- if (typeof parsed !== "object" || parsed === null) {
1308
- unreadable += 1;
1309
- continue;
1310
- }
1311
- const record = parsed;
1312
- const serverName = typeof record.serverName === "string" ? record.serverName.trim() : "";
1313
- if (serverName === "") {
1314
- unreadable += 1;
1315
- continue;
1316
- }
1317
- const tools = Array.isArray(record.tools) ? record.tools : [];
1318
- const updatedAt = typeof record.updatedAt === "string" ? record.updatedAt : "";
1319
- const definitionBytes = wireShapeLength(tools);
1320
- const candidate = {
1321
- serverName,
1322
- toolCount: tools.length,
1323
- definitionBytes,
1324
- estimatedTokens: estimateTokensFromLength(definitionBytes),
1325
- updatedAt,
1326
- // `tools` is an unchecked cast off a JSON array, so every element is
1327
- // treated as untrusted here rather than trusted to match CachedTool.
1328
- toolNames: tools.map((t) => t?.name).filter((n) => typeof n === "string" && n !== "")
1329
- };
1330
- const existing = newest.get(serverName);
1331
- if (existing === void 0 || candidate.updatedAt > existing.updatedAt) newest.set(serverName, candidate);
1332
- }
1333
- const servers = [...newest.values()].sort(
1334
- (a, b) => b.definitionBytes - a.definitionBytes || a.serverName.localeCompare(b.serverName)
1335
- );
1336
- return { cacheFound: true, servers, unreadable };
1337
- }
1338
-
1339
- export {
1340
- foldToolName,
1341
- COPILOT_CLI_TOOL_NAME_MAP,
1342
- MATERIALIZE_SHRUNK_IMAGE_JS,
1343
- COPILOT_CLI_HOOK_SCRIPT,
1344
- buildGuidanceBody,
1345
- skillDescriptionLine,
1346
- buildGuidanceBlock,
1347
- jsonc,
1348
- bundledCliPath,
1349
- managedServer,
1350
- isManagedServer,
1351
- readServersJson,
1352
- serversOf,
1353
- setTokenGoatServer,
1354
- isResidueServersJson,
1355
- dropEmptyServers,
1356
- hasManagedServer,
1357
- visualStudioUserMcpPath,
1358
- visualStudioProjectMcpPath,
1359
- visualStudioOtherScopeHasManagedServer,
1360
- isVisualStudioInstalled,
1361
- visualStudioSolutionVscodeMcpPath,
1362
- visualStudioDuplicateNote,
1363
- visualStudioMcpStatus,
1364
- visualStudioManagedEntry,
1365
- syncVisualStudioProjectGuidance,
1366
- installVisualStudio,
1367
- uninstallVisualStudio,
1368
- copilotCliUserRoot,
1369
- copilotCliMcpToolsDir,
1370
- copilotCliConfigPath,
1371
- copilotCliScriptPath,
1372
- HOOKS_SCRIPT_FILE,
1373
- copilotHooksFilePaths,
1374
- readCopilotHooksOwners,
1375
- installCopilotHooksFile,
1376
- releaseCopilotHooksFile,
1377
- installCopilotCli,
1378
- uninstallCopilotCli,
1379
- isCopilotCliInstalled,
1380
- readCopilotMcpTools
1381
- };