token-goat 2.9.19 → 2.9.21

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