context-doctor 0.35.1 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -14
- package/dist/ab.d.ts +188 -0
- package/dist/ab.js +857 -0
- package/dist/abtasks.d.ts +49 -0
- package/dist/abtasks.js +287 -0
- package/dist/cli.js +83 -8
- package/dist/compact.d.ts +36 -0
- package/dist/compact.js +144 -0
- package/dist/copilot.d.ts +63 -0
- package/dist/copilot.js +96 -0
- package/dist/doctor.js +114 -1
- package/dist/extract.d.ts +23 -0
- package/dist/extract.js +121 -4
- package/dist/fileparams.d.ts +61 -0
- package/dist/fileparams.js +308 -0
- package/dist/handoff.d.ts +143 -0
- package/dist/handoff.js +529 -0
- package/dist/hook.d.ts +1 -1
- package/dist/hook.js +25 -3
- package/dist/httpguard.d.ts +56 -0
- package/dist/httpguard.js +141 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/install.d.ts +16 -0
- package/dist/install.js +176 -3
- package/dist/ledger.d.ts +6 -1
- package/dist/ledger.js +45 -7
- package/dist/mcp.d.ts +2 -0
- package/dist/mcp.js +72 -56
- package/dist/pack.d.ts +20 -0
- package/dist/pack.js +29 -1
- package/dist/preferences.d.ts +3 -1
- package/dist/preferences.js +8 -6
- package/dist/pricing.d.ts +7 -0
- package/dist/pricing.js +29 -5
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/rules.d.ts +19 -0
- package/dist/rules.js +34 -0
- package/dist/sketch.d.ts +5 -1
- package/dist/sketch.js +23 -7
- package/package.json +1 -1
- package/skills/context-doctor/SKILL.md +2 -0
package/dist/compact.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compact tool results: a short text, the detail as `structuredContent`, and
|
|
3
|
+
* presentation-only data in `_meta`.
|
|
4
|
+
*
|
|
5
|
+
* Why: every byte of a tool result is re-read on every later turn of the chat.
|
|
6
|
+
* profile_context's full report (bars, message previews) and pack_context's
|
|
7
|
+
* outline (one line per chunk, the heading path repeated on each) are mostly
|
|
8
|
+
* presentation. ChatGPT surfaces `content` and `structuredContent` to the
|
|
9
|
+
* model and keeps `_meta` for the widget only (developers.openai.com/plugins/reference,
|
|
10
|
+
* "Tool results"), so the compact form puts one line of text and
|
|
11
|
+
* the decision-relevant fields in front of the model, and the rest where only
|
|
12
|
+
* a widget would read it.
|
|
13
|
+
*
|
|
14
|
+
* Not the default: a client that ignores `structuredContent` would lose the
|
|
15
|
+
* detail. The server sends this form to ChatGPT (recognised by the
|
|
16
|
+
* `openai/session` or `openai/subject` request metadata, the anonymized
|
|
17
|
+
* conversation and user ids it attaches to tool calls) or when
|
|
18
|
+
* CONTEXT_DOCTOR_RESULTS=compact; everything else gets the full text, as
|
|
19
|
+
* before. Measured sizes are in ROADMAP.md ("Desktop chat apps").
|
|
20
|
+
*/
|
|
21
|
+
import { formatTokens } from "./tokens.js";
|
|
22
|
+
/**
|
|
23
|
+
* Which form a tool call gets. `requestMeta` is the request's `_meta`.
|
|
24
|
+
* ChatGPT's identification keys mark ChatGPT itself, the client documented to
|
|
25
|
+
* show structuredContent to the model; any `openai/*` key would also catch
|
|
26
|
+
* other OpenAI clients (locale, user agent) that may not. An explicit
|
|
27
|
+
* CONTEXT_DOCTOR_RESULTS (full or compact) wins.
|
|
28
|
+
*/
|
|
29
|
+
const CHATGPT_KEYS = ["openai/session", "openai/subject"];
|
|
30
|
+
export function resultMode(requestMeta, env = process.env) {
|
|
31
|
+
const forced = env.CONTEXT_DOCTOR_RESULTS?.trim().toLowerCase();
|
|
32
|
+
if (forced === "full" || forced === "compact")
|
|
33
|
+
return forced;
|
|
34
|
+
if (requestMeta && typeof requestMeta === "object" && CHATGPT_KEYS.some((k) => typeof requestMeta[k] === "string"))
|
|
35
|
+
return "compact";
|
|
36
|
+
return "full";
|
|
37
|
+
}
|
|
38
|
+
const round = (n) => Math.round(n);
|
|
39
|
+
/** profile_context on a conversation. */
|
|
40
|
+
export function compactProfile(p, fullText) {
|
|
41
|
+
const top = p.findings[0];
|
|
42
|
+
const pct = p.totalTokens > 0 ? Math.round((p.totalEstSavings / p.totalTokens) * 100) : 0;
|
|
43
|
+
const lines = [
|
|
44
|
+
`~${formatTokens(p.totalTokens)} tokens in ${p.messageCount} messages (${p.sourceFormat})${p.usagePct !== undefined ? `, ${p.usagePct.toFixed(0)}% of the window` : ""}; ~${formatTokens(p.totalEstSavings)} recoverable (${pct}%).`,
|
|
45
|
+
];
|
|
46
|
+
if (p.parseWarning)
|
|
47
|
+
lines.unshift(`⚠ ${p.parseWarning}`);
|
|
48
|
+
lines.push(top ? `Act on #1 (first in structuredContent.findings).` : "No findings.");
|
|
49
|
+
const categories = Object.fromEntries(Object.entries(p.categories).filter(([, t]) => t > 0).sort((a, b) => b[1] - a[1]).map(([k, t]) => [k, round(t)]));
|
|
50
|
+
const structured = {
|
|
51
|
+
total_tokens: round(p.totalTokens),
|
|
52
|
+
messages: p.messageCount,
|
|
53
|
+
recoverable_tokens: round(p.totalEstSavings),
|
|
54
|
+
by_category: categories,
|
|
55
|
+
// One string per finding: JSON keys repeated per object cost more than they say.
|
|
56
|
+
findings: p.findings.slice(0, 6).map((f) => `${f.severity}${f.estSavings > 0 ? ` ~${formatTokens(f.estSavings)}` : ""}: ${f.message} → ${f.suggestion}`),
|
|
57
|
+
};
|
|
58
|
+
if (p.findings.length > 6)
|
|
59
|
+
structured.more_findings = p.findings.length - 6;
|
|
60
|
+
if (p.model)
|
|
61
|
+
structured.model = p.model;
|
|
62
|
+
if (p.usagePct !== undefined)
|
|
63
|
+
structured.window_pct = Number(p.usagePct.toFixed(1));
|
|
64
|
+
if (p.cost)
|
|
65
|
+
structured.usd_per_call = Number(p.cost.perCallUsd.toFixed(4));
|
|
66
|
+
return {
|
|
67
|
+
text: lines.join("\n"),
|
|
68
|
+
structured,
|
|
69
|
+
// The bar chart and message previews: presentation, and raw conversation
|
|
70
|
+
// text the model already has. A widget can show them; the model need not.
|
|
71
|
+
meta: { "context-doctor/report": fullText, "context-doctor/largest": p.largestMessages.map((m) => ({ index: m.index, kind: m.kind, tokens: round(m.tokens), preview: m.preview })) },
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/** profile_context on a chat-app sketch. */
|
|
75
|
+
export function compactSketch(p, fullText) {
|
|
76
|
+
// The sketch report is short already: what makes it longer than it needs to
|
|
77
|
+
// be is every finding's action. Only #1 is acted on, so only #1 keeps its
|
|
78
|
+
// action (in the text); the rest are one line each.
|
|
79
|
+
const [top, ...rest] = p.findings;
|
|
80
|
+
const lines = [`~${formatTokens(p.totalTokens)} tokens, ${p.turns} turns${p.usagePct !== undefined ? `, ~${p.usagePct}% of the window` : ""} (estimate); ~${formatTokens(p.totalEstSavings)} recoverable, only in a new chat.`];
|
|
81
|
+
if (top) {
|
|
82
|
+
lines.push(`Act on #1 now: ${top.message} → ${top.action}`);
|
|
83
|
+
lines.push("This chat's history cannot be edited: what is already here comes back only in a new chat (save_handoff).");
|
|
84
|
+
}
|
|
85
|
+
else
|
|
86
|
+
lines.push("No findings. Keep going.");
|
|
87
|
+
const structured = {
|
|
88
|
+
total_tokens: p.totalTokens,
|
|
89
|
+
recoverable_tokens: p.totalEstSavings,
|
|
90
|
+
recoverable_by: "a new chat (handoff)",
|
|
91
|
+
};
|
|
92
|
+
if (rest.length)
|
|
93
|
+
structured.other_findings = rest.map((f) => `${f.severity}${f.estSavings > 0 ? ` ~${formatTokens(f.estSavings)}` : ""}: ${f.message}`);
|
|
94
|
+
if (p.usagePct !== undefined)
|
|
95
|
+
structured.window_pct = p.usagePct;
|
|
96
|
+
if (p.perTurnUsd !== undefined)
|
|
97
|
+
structured.usd_per_turn = Number(p.perTurnUsd.toFixed(4));
|
|
98
|
+
return { text: lines.join("\n"), structured, meta: { "context-doctor/report": fullText } };
|
|
99
|
+
}
|
|
100
|
+
/** "#2-5" for a run of consecutive chunk numbers. */
|
|
101
|
+
function idRange(first, last) {
|
|
102
|
+
const n = (id) => id.slice(id.lastIndexOf("#") + 1);
|
|
103
|
+
return first === last ? `#${n(first)}` : `#${n(first)}-${n(last)}`;
|
|
104
|
+
}
|
|
105
|
+
/** The last segment of a heading path, without the "(cont.)" a split chunk carries. */
|
|
106
|
+
function shortHeading(heading) {
|
|
107
|
+
const base = heading.replace(/\s*\(cont\.\)$/, "");
|
|
108
|
+
const parts = base.split(" > ");
|
|
109
|
+
return parts[parts.length - 1] || base;
|
|
110
|
+
}
|
|
111
|
+
/** pack_context with no query: sections instead of one line per chunk. */
|
|
112
|
+
export function compactOutline(r, fullText, maxSections = 120) {
|
|
113
|
+
// Consecutive chunks of one source under the same heading are one section.
|
|
114
|
+
const bySource = new Map();
|
|
115
|
+
for (const c of r.chunks) {
|
|
116
|
+
const list = bySource.get(c.source) ?? [];
|
|
117
|
+
const heading = shortHeading(c.heading);
|
|
118
|
+
const prev = list[list.length - 1];
|
|
119
|
+
if (prev && prev.heading === heading) {
|
|
120
|
+
prev.last = c.id;
|
|
121
|
+
prev.tokens += c.tokens;
|
|
122
|
+
}
|
|
123
|
+
else
|
|
124
|
+
list.push({ first: c.id, last: c.id, heading, tokens: c.tokens });
|
|
125
|
+
bySource.set(c.source, list);
|
|
126
|
+
}
|
|
127
|
+
let budget = maxSections;
|
|
128
|
+
let omitted = 0;
|
|
129
|
+
const sources = [...bySource.entries()].map(([name, sections]) => {
|
|
130
|
+
const shown = sections.slice(0, Math.max(0, budget));
|
|
131
|
+
budget -= shown.length;
|
|
132
|
+
omitted += sections.length - shown.length;
|
|
133
|
+
const tokens = sections.reduce((n, s) => n + s.tokens, 0);
|
|
134
|
+
return { name, tokens: round(tokens), sections: shown.map((s) => `${idRange(s.first, s.last)} ${s.heading} ~${formatTokens(s.tokens)}`) };
|
|
135
|
+
});
|
|
136
|
+
const names = r.sources.length === 1 ? r.sources[0].name : `${r.sources.length} files`;
|
|
137
|
+
const example = r.chunks[0]?.id ?? "name#1";
|
|
138
|
+
const text = `OUTLINE of ${names}: ~${formatTokens(r.totalTokens)} tokens in ${r.chunks.length} chunks, as sections in structuredContent. ` +
|
|
139
|
+
`Nothing packed: pass a query, or ids (<name>#<n>, e.g. ${example}).`;
|
|
140
|
+
const structured = { total_tokens: round(r.totalTokens), chunks: r.chunks.length, sources };
|
|
141
|
+
if (omitted > 0)
|
|
142
|
+
structured.sections_not_shown = omitted;
|
|
143
|
+
return { text, structured, meta: { "context-doctor/outline": fullText } };
|
|
144
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub Copilot: the Copilot CLI, the GitHub Copilot app, and VS Code's
|
|
3
|
+
* agent sessions, whose default harness ("Copilot") is the same runtime as
|
|
4
|
+
* the CLI. Checked 2026-10-25 against GitHub's hooks reference
|
|
5
|
+
* (docs.github.com/en/copilot/reference/hooks-reference), VS Code's hooks,
|
|
6
|
+
* harness and MCP pages (code.visualstudio.com, updated 2026-10-21) and the
|
|
7
|
+
* Copilot Chat 0.61.0 extension built into VS Code 1.133:
|
|
8
|
+
*
|
|
9
|
+
* - Hooks: `~/.copilot/hooks/*.json` (or `$COPILOT_HOME/hooks/`), each
|
|
10
|
+
* `{"version": 1, "hooks": {"<event>": [{type, command, timeoutSec}]}}`.
|
|
11
|
+
* VS Code's older "Local" harness reads the same user hook files and
|
|
12
|
+
* accepts the Copilot event names.
|
|
13
|
+
* - Of the events that can add context, none carries a transcript path:
|
|
14
|
+
* `sessionStart` (additionalContext), `postToolUse`, `postToolUseFailure`.
|
|
15
|
+
* A transcript path reaches only agentStop, subagentStart, subagentStop
|
|
16
|
+
* and preCompact, which add nothing to the main agent's context (preCompact
|
|
17
|
+
* is a notification). So the every-prompt size check has nothing to read
|
|
18
|
+
* here, and only the standing rules go in, once per new session.
|
|
19
|
+
* - The Copilot harness reads top-level `additionalContext`; VS Code's Local
|
|
20
|
+
* harness reads `hookSpecificOutput.additionalContext` for SessionStart
|
|
21
|
+
* (seen in the extension's code). The answer carries both, and each
|
|
22
|
+
* harness takes its own.
|
|
23
|
+
* - MCP: `~/.copilot/mcp-config.json` (`$COPILOT_HOME/mcp-config.json`),
|
|
24
|
+
* `{"mcpServers": {name: {type: "local", command, args, tools: ["*"]}}}`.
|
|
25
|
+
* Copilot harness sessions read it directly, in VS Code too, according to
|
|
26
|
+
* VS Code's MCP docs of 2026-10-21 (no file of the installed VS Code 1.133
|
|
27
|
+
* mentions it yet). VS Code's user-profile mcp.json is labelled deprecated
|
|
28
|
+
* there and is forwarded into the same sessions, so it is not written as
|
|
29
|
+
* well; `doctor` warns when it also starts context-doctor, since the tools
|
|
30
|
+
* could then load twice.
|
|
31
|
+
*/
|
|
32
|
+
/** Copilot's home: $COPILOT_HOME when set, else ~/.copilot. */
|
|
33
|
+
export declare function copilotHome(): string;
|
|
34
|
+
export declare function copilotMcpConfigPath(): string;
|
|
35
|
+
/** Our own hook file: install creates it, uninstall deletes it. */
|
|
36
|
+
export declare function copilotHookFilePath(): string;
|
|
37
|
+
/** Inline settings Copilot also reads; `disableAllHooks` there turns every hook off. */
|
|
38
|
+
export declare function copilotSettingsPath(): string;
|
|
39
|
+
/** The older settings file; doctor still honours a disableAllHooks there. */
|
|
40
|
+
export declare function copilotLegacyConfigPath(): string;
|
|
41
|
+
/** VS Code's user folders (stable and Insiders): VS Code ships Copilot built in. */
|
|
42
|
+
export declare function vsCodeUserDirs(): string[];
|
|
43
|
+
export declare function vsCodePresent(): boolean;
|
|
44
|
+
/** The one event install registers. */
|
|
45
|
+
export declare const COPILOT_HOOK_EVENT = "sessionStart";
|
|
46
|
+
/** Is this hook-file entry ours? Install writes `<context-doctor> hook copilot`. */
|
|
47
|
+
export declare function isOurCopilotEntry(entry: unknown): boolean;
|
|
48
|
+
/** What a new Copilot session is given: the standing rules, tagged as ours. */
|
|
49
|
+
export declare function copilotSessionContext(): string;
|
|
50
|
+
/**
|
|
51
|
+
* The hook's answer to a session start, or undefined to stay silent for an
|
|
52
|
+
* event other than a session start. A resumed session is answered too: the
|
|
53
|
+
* Copilot runtime keeps sessionStart context in memory and sends it with
|
|
54
|
+
* each turn, and does not restore it on resume (seen in VS Code's bundled
|
|
55
|
+
* runtime, 1.0.73 and 1.0.79), so a resumed session has the rules only if
|
|
56
|
+
* the hook gives them again.
|
|
57
|
+
*
|
|
58
|
+
* Input shapes: the Copilot harness sends camelCase without an event name
|
|
59
|
+
* for camelCase keys ({sessionId, timestamp, cwd, source}); VS Code's Local
|
|
60
|
+
* harness and the Copilot harness's PascalCase aliases send
|
|
61
|
+
* {hook_event_name: "SessionStart", session_id, ...}.
|
|
62
|
+
*/
|
|
63
|
+
export declare function copilotSessionStartOutput(input: unknown): string | undefined;
|
package/dist/copilot.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub Copilot: the Copilot CLI, the GitHub Copilot app, and VS Code's
|
|
3
|
+
* agent sessions, whose default harness ("Copilot") is the same runtime as
|
|
4
|
+
* the CLI. Checked 2026-10-25 against GitHub's hooks reference
|
|
5
|
+
* (docs.github.com/en/copilot/reference/hooks-reference), VS Code's hooks,
|
|
6
|
+
* harness and MCP pages (code.visualstudio.com, updated 2026-10-21) and the
|
|
7
|
+
* Copilot Chat 0.61.0 extension built into VS Code 1.133:
|
|
8
|
+
*
|
|
9
|
+
* - Hooks: `~/.copilot/hooks/*.json` (or `$COPILOT_HOME/hooks/`), each
|
|
10
|
+
* `{"version": 1, "hooks": {"<event>": [{type, command, timeoutSec}]}}`.
|
|
11
|
+
* VS Code's older "Local" harness reads the same user hook files and
|
|
12
|
+
* accepts the Copilot event names.
|
|
13
|
+
* - Of the events that can add context, none carries a transcript path:
|
|
14
|
+
* `sessionStart` (additionalContext), `postToolUse`, `postToolUseFailure`.
|
|
15
|
+
* A transcript path reaches only agentStop, subagentStart, subagentStop
|
|
16
|
+
* and preCompact, which add nothing to the main agent's context (preCompact
|
|
17
|
+
* is a notification). So the every-prompt size check has nothing to read
|
|
18
|
+
* here, and only the standing rules go in, once per new session.
|
|
19
|
+
* - The Copilot harness reads top-level `additionalContext`; VS Code's Local
|
|
20
|
+
* harness reads `hookSpecificOutput.additionalContext` for SessionStart
|
|
21
|
+
* (seen in the extension's code). The answer carries both, and each
|
|
22
|
+
* harness takes its own.
|
|
23
|
+
* - MCP: `~/.copilot/mcp-config.json` (`$COPILOT_HOME/mcp-config.json`),
|
|
24
|
+
* `{"mcpServers": {name: {type: "local", command, args, tools: ["*"]}}}`.
|
|
25
|
+
* Copilot harness sessions read it directly, in VS Code too, according to
|
|
26
|
+
* VS Code's MCP docs of 2026-10-21 (no file of the installed VS Code 1.133
|
|
27
|
+
* mentions it yet). VS Code's user-profile mcp.json is labelled deprecated
|
|
28
|
+
* there and is forwarded into the same sessions, so it is not written as
|
|
29
|
+
* well; `doctor` warns when it also starts context-doctor, since the tools
|
|
30
|
+
* could then load twice.
|
|
31
|
+
*/
|
|
32
|
+
import { existsSync } from "node:fs";
|
|
33
|
+
import { homedir, platform } from "node:os";
|
|
34
|
+
import { join } from "node:path";
|
|
35
|
+
import { SERVER_INSTRUCTIONS } from "./rules.js";
|
|
36
|
+
/** Copilot's home: $COPILOT_HOME when set, else ~/.copilot. */
|
|
37
|
+
export function copilotHome() {
|
|
38
|
+
return process.env.COPILOT_HOME || join(homedir(), ".copilot");
|
|
39
|
+
}
|
|
40
|
+
export function copilotMcpConfigPath() {
|
|
41
|
+
return join(copilotHome(), "mcp-config.json");
|
|
42
|
+
}
|
|
43
|
+
/** Our own hook file: install creates it, uninstall deletes it. */
|
|
44
|
+
export function copilotHookFilePath() {
|
|
45
|
+
return join(copilotHome(), "hooks", "context-doctor.json");
|
|
46
|
+
}
|
|
47
|
+
/** Inline settings Copilot also reads; `disableAllHooks` there turns every hook off. */
|
|
48
|
+
export function copilotSettingsPath() {
|
|
49
|
+
return join(copilotHome(), "settings.json");
|
|
50
|
+
}
|
|
51
|
+
/** The older settings file; doctor still honours a disableAllHooks there. */
|
|
52
|
+
export function copilotLegacyConfigPath() {
|
|
53
|
+
return join(copilotHome(), "config.json");
|
|
54
|
+
}
|
|
55
|
+
/** VS Code's user folders (stable and Insiders): VS Code ships Copilot built in. */
|
|
56
|
+
export function vsCodeUserDirs() {
|
|
57
|
+
const base = platform() === "darwin" ? join(homedir(), "Library", "Application Support")
|
|
58
|
+
: platform() === "win32" ? (process.env.APPDATA ?? join(homedir(), "AppData", "Roaming"))
|
|
59
|
+
: join(homedir(), ".config");
|
|
60
|
+
return ["Code", "Code - Insiders"].map((app) => join(base, app, "User"));
|
|
61
|
+
}
|
|
62
|
+
export function vsCodePresent() {
|
|
63
|
+
return vsCodeUserDirs().some((d) => existsSync(d));
|
|
64
|
+
}
|
|
65
|
+
/** The one event install registers. */
|
|
66
|
+
export const COPILOT_HOOK_EVENT = "sessionStart";
|
|
67
|
+
/** Is this hook-file entry ours? Install writes `<context-doctor> hook copilot`. */
|
|
68
|
+
export function isOurCopilotEntry(entry) {
|
|
69
|
+
const e = entry;
|
|
70
|
+
return /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s+copilot\s*$/.test(String(e?.command ?? e?.bash ?? ""));
|
|
71
|
+
}
|
|
72
|
+
/** What a new Copilot session is given: the standing rules, tagged as ours. */
|
|
73
|
+
export function copilotSessionContext() {
|
|
74
|
+
return `<context-doctor>\n${SERVER_INSTRUCTIONS}\n</context-doctor>`;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The hook's answer to a session start, or undefined to stay silent for an
|
|
78
|
+
* event other than a session start. A resumed session is answered too: the
|
|
79
|
+
* Copilot runtime keeps sessionStart context in memory and sends it with
|
|
80
|
+
* each turn, and does not restore it on resume (seen in VS Code's bundled
|
|
81
|
+
* runtime, 1.0.73 and 1.0.79), so a resumed session has the rules only if
|
|
82
|
+
* the hook gives them again.
|
|
83
|
+
*
|
|
84
|
+
* Input shapes: the Copilot harness sends camelCase without an event name
|
|
85
|
+
* for camelCase keys ({sessionId, timestamp, cwd, source}); VS Code's Local
|
|
86
|
+
* harness and the Copilot harness's PascalCase aliases send
|
|
87
|
+
* {hook_event_name: "SessionStart", session_id, ...}.
|
|
88
|
+
*/
|
|
89
|
+
export function copilotSessionStartOutput(input) {
|
|
90
|
+
const obj = input && typeof input === "object" && !Array.isArray(input) ? input : {};
|
|
91
|
+
const event = obj.hook_event_name;
|
|
92
|
+
if (event !== undefined && event !== "SessionStart" && event !== "sessionStart")
|
|
93
|
+
return undefined;
|
|
94
|
+
const context = copilotSessionContext();
|
|
95
|
+
return JSON.stringify({ additionalContext: context, hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: context } });
|
|
96
|
+
}
|
package/dist/doctor.js
CHANGED
|
@@ -16,7 +16,8 @@ import { ledgerPath, readLedger } from "./ledger.js";
|
|
|
16
16
|
import { loadConfig } from "./config.js";
|
|
17
17
|
import { codexRouting } from "./codexroute.js";
|
|
18
18
|
import { CURSOR_HOOK_EVENTS } from "./install.js";
|
|
19
|
-
import { binOnPath, claudeCodeInstallsFromEnv, claudeInstalledCopies, codexMcpEntry, geminiCliPresent, geminiSettingsPath, isEmptyStub, isOurPluginKey, launcherNamesMissingPackage } from "./install.js";
|
|
19
|
+
import { binOnPath, claudeCodeInstallsFromEnv, claudeInstalledCopies, codexMcpEntry, copilotPresent, geminiCliPresent, geminiSettingsPath, isEmptyStub, isOurPluginKey, launcherNamesMissingPackage } from "./install.js";
|
|
20
|
+
import { COPILOT_HOOK_EVENT, copilotHookFilePath, copilotLegacyConfigPath, copilotMcpConfigPath, copilotSettingsPath, isOurCopilotEntry, vsCodeUserDirs } from "./copilot.js";
|
|
20
21
|
import { describeDesktopUsage, desktopUsage } from "./desktopusage.js";
|
|
21
22
|
import { withInvocation } from "./invocation.js";
|
|
22
23
|
import { describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
|
|
@@ -209,6 +210,94 @@ export function devinCheck(home = homedir()) {
|
|
|
209
210
|
parts.push(`Devin Desktop found (${app.replace(home, "~")}): its Cascade hooks pass a transcript to one event only, after a response, too late to steer it`);
|
|
210
211
|
return { label, status: "skip", detail: `${parts.join("; ")}. Not supported yet; the MCP tools work in any MCP client` };
|
|
211
212
|
}
|
|
213
|
+
/** "~/..." for a path under the home directory. */
|
|
214
|
+
function tilde(p) {
|
|
215
|
+
const home = homedir();
|
|
216
|
+
return p.startsWith(home) ? "~" + p.slice(home.length) : p;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The Copilot session-start hook: registered, its command resolves, hooks
|
|
220
|
+
* not switched off, and when it last ran (from the ledger, when there is one).
|
|
221
|
+
* What it does not do is said too: no size checks, since Copilot passes a
|
|
222
|
+
* transcript only to hooks that cannot add context.
|
|
223
|
+
*/
|
|
224
|
+
function copilotHookCheck(mcp, missingHook) {
|
|
225
|
+
const label = "Copilot hook";
|
|
226
|
+
const path = copilotHookFilePath();
|
|
227
|
+
let config;
|
|
228
|
+
try {
|
|
229
|
+
config = readConfig(path, ["version"]);
|
|
230
|
+
}
|
|
231
|
+
catch (e) {
|
|
232
|
+
return { label, status: "fail", detail: `${tilde(path)} is not valid JSON (${e.message}); Copilot skips it` };
|
|
233
|
+
}
|
|
234
|
+
if (config !== undefined && (typeof config !== "object" || Array.isArray(config)))
|
|
235
|
+
return { label, status: "fail", detail: `${tilde(path)} is not a JSON object; Copilot skips it — delete it and re-run: context-doctor install` };
|
|
236
|
+
const entry = (Array.isArray(config?.hooks?.[COPILOT_HOOK_EVENT]) ? config.hooks[COPILOT_HOOK_EVENT] : []).find(isOurCopilotEntry);
|
|
237
|
+
if (!entry)
|
|
238
|
+
return missingHook(label, mcp);
|
|
239
|
+
// The runtime loads no hooks at all from a file whose version is not 1.
|
|
240
|
+
if (config?.version !== 1)
|
|
241
|
+
return { label, status: "fail", detail: `${tilde(path)} says "version": ${JSON.stringify(config?.version)}, and Copilot loads hooks only from version 1 files: set it to 1` };
|
|
242
|
+
const missing = hookBinaryMissing(String(entry.command ?? ""));
|
|
243
|
+
if (missing)
|
|
244
|
+
return { label, status: "fail", detail: `registered, but ${missing} no longer exists — re-run: context-doctor install` };
|
|
245
|
+
// disableAllHooks in the hook file, settings.json, or the older config.json.
|
|
246
|
+
const off = [path, copilotSettingsPath(), copilotLegacyConfigPath()].find((p) => {
|
|
247
|
+
if (p === path)
|
|
248
|
+
return config?.disableAllHooks === true;
|
|
249
|
+
try {
|
|
250
|
+
return JSON.parse(readFileSync(p, "utf8"))?.disableAllHooks === true;
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
return false; // absent or unreadable: hooks stay on
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
if (off)
|
|
257
|
+
return { label, status: "fail", detail: `registered, but disableAllHooks is true in ${tilde(off)}, so Copilot runs no hooks` };
|
|
258
|
+
// The rules name the MCP tools: without the server they point at nothing.
|
|
259
|
+
if (mcp.status !== "ok")
|
|
260
|
+
return { label, status: "warn", detail: `sessionStart in ${tilde(path)} adds the standing rules, which name context-doctor's MCP tools, but the MCP server is not wired (above): re-run context-doctor install` };
|
|
261
|
+
const last = readLedger().filter((e) => e.ev === "session_rules" && e.app === "copilot").pop();
|
|
262
|
+
const ran = last ? ` Last ran ${new Date(last.ts).toISOString().slice(0, 16).replace("T", " ")}.` : "";
|
|
263
|
+
return {
|
|
264
|
+
label,
|
|
265
|
+
status: "ok",
|
|
266
|
+
detail: `sessionStart in ${tilde(path)}: each new or resumed Copilot session gets the standing context rules.${ran} No size checks there: Copilot gives a transcript only to hooks that cannot add context`,
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* VS Code forwards the servers in its own user mcp.json into Copilot
|
|
271
|
+
* sessions, beside ~/.copilot/mcp-config.json. One that also starts
|
|
272
|
+
* context-doctor, under any name, can load the tools twice. VS Code's file
|
|
273
|
+
* may hold comments, so it is searched as text when it does not parse.
|
|
274
|
+
*/
|
|
275
|
+
function vsCodeDuplicateCheck() {
|
|
276
|
+
for (const dir of vsCodeUserDirs()) {
|
|
277
|
+
const path = join(dir, "mcp.json");
|
|
278
|
+
let raw;
|
|
279
|
+
try {
|
|
280
|
+
raw = readFileSync(path, "utf8");
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
if (!raw.includes("context-doctor"))
|
|
286
|
+
continue;
|
|
287
|
+
let names = [];
|
|
288
|
+
try {
|
|
289
|
+
const servers = JSON.parse(raw)?.servers ?? {};
|
|
290
|
+
names = Object.entries(servers).filter(([, v]) => JSON.stringify(v).includes("context-doctor")).map(([k]) => k);
|
|
291
|
+
}
|
|
292
|
+
catch { /* JSONC: the text search above is the evidence */ }
|
|
293
|
+
return {
|
|
294
|
+
label: "Copilot MCP",
|
|
295
|
+
status: "warn",
|
|
296
|
+
detail: `VS Code's ${tilde(path)} also starts context-doctor${names.length ? ` (as ${names.map((n) => `"${n}"`).join(", ")})` : ""}; VS Code forwards it into Copilot sessions beside ${tilde(copilotMcpConfigPath())}, so the tools can load twice: remove one`,
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
return undefined;
|
|
300
|
+
}
|
|
212
301
|
/** Claude Code's disableAllHooks: when true, no hook of anyone's runs. */
|
|
213
302
|
function hooksDisabled(layers) {
|
|
214
303
|
return layers.reduce((off, s) => (typeof s.disableAllHooks === "boolean" ? s.disableAllHooks : off), false);
|
|
@@ -409,6 +498,30 @@ export async function runDoctor() {
|
|
|
409
498
|
checks.push({ label: "Gemini CLI", status: "skip", detail: "not detected" });
|
|
410
499
|
}
|
|
411
500
|
checks.push(devinCheck());
|
|
501
|
+
// GitHub Copilot (CLI, app, VS Code): MCP in ~/.copilot/mcp-config.json,
|
|
502
|
+
// the sessionStart hook in a hook file of our own.
|
|
503
|
+
if (copilotPresent()) {
|
|
504
|
+
const mcpPath = copilotMcpConfigPath();
|
|
505
|
+
let copilotMcp;
|
|
506
|
+
try {
|
|
507
|
+
copilotMcp = readConfig(mcpPath) === undefined
|
|
508
|
+
? { label: "Copilot MCP", status: "skip", detail: NOT_INSTALLED }
|
|
509
|
+
: checkMcpEntry("Copilot MCP", mcpPath);
|
|
510
|
+
}
|
|
511
|
+
catch (e) {
|
|
512
|
+
copilotMcp = { label: "Copilot MCP", status: "fail", detail: `${tilde(mcpPath)} is not valid JSON (${e.message})` };
|
|
513
|
+
}
|
|
514
|
+
if (copilotMcp.status === "ok")
|
|
515
|
+
copilotMcp.detail += ` in ${tilde(mcpPath)} (Copilot CLI, the Copilot app and VS Code's Copilot sessions)`;
|
|
516
|
+
checks.push(copilotMcp);
|
|
517
|
+
const duplicate = copilotMcp.status === "ok" ? vsCodeDuplicateCheck() : undefined;
|
|
518
|
+
if (duplicate)
|
|
519
|
+
checks.push(duplicate);
|
|
520
|
+
checks.push(copilotHookCheck(copilotMcp, missingHook));
|
|
521
|
+
}
|
|
522
|
+
else {
|
|
523
|
+
checks.push({ label: "GitHub Copilot", status: "skip", detail: "not detected (Copilot CLI, the GitHub Copilot app, or VS Code)" });
|
|
524
|
+
}
|
|
412
525
|
// Cursor: its agent gets the guidance through native hooks (the Claude
|
|
413
526
|
// Code hook it also runs cannot add context there). Whether the text then
|
|
414
527
|
// reaches the model depends on the Cursor version, and Cursor logs only
|
package/dist/extract.d.ts
CHANGED
|
@@ -7,11 +7,34 @@
|
|
|
7
7
|
* `textutil` for Word/RTF/ODT on macOS, and `unzip` for the zipped XML
|
|
8
8
|
* formats (docx, pptx, odt) elsewhere. When none is available the caller
|
|
9
9
|
* gets a reason that names what to install, never a silent skip.
|
|
10
|
+
*
|
|
11
|
+
* Two safety rules, both learned from a QA pass on uploads over --http:
|
|
12
|
+
* - textutil runs with -noload -nostore. A ".doc" that is really HTML made
|
|
13
|
+
* textutil fetch its stylesheets and images, from 127.0.0.1 and from
|
|
14
|
+
* 169.254.169.254 as readily as from the web: a server-side request
|
|
15
|
+
* forgery through a document;
|
|
16
|
+
* - the MCP server extracts with extractTextAsync, which never blocks the
|
|
17
|
+
* event loop and stops at a time budget for the whole call (a slow PDF
|
|
18
|
+
* held /health for 30 s; one can take 120 s). The synchronous
|
|
19
|
+
* extractText stays for the one-shot CLI.
|
|
10
20
|
*/
|
|
11
21
|
export declare const EXTRACTABLE: Set<string>;
|
|
22
|
+
/** Never load or write a document's subsidiary resources (stylesheets, images, frames). */
|
|
23
|
+
export declare const TEXTUTIL_ARGS: string[];
|
|
12
24
|
/** The document's text, or the reason it could not be read. */
|
|
13
25
|
export declare function extractText(path: string): {
|
|
14
26
|
text: string;
|
|
15
27
|
} | {
|
|
16
28
|
error: string;
|
|
17
29
|
};
|
|
30
|
+
/** Default time budget for one extraction call in the MCP server. */
|
|
31
|
+
export declare const EXTRACT_BUDGET_MS = 20000;
|
|
32
|
+
/**
|
|
33
|
+
* extractText for a server: asynchronous, and bounded by `deadline` (ms since
|
|
34
|
+
* the epoch) across every tool it tries. Past the deadline the reason says so.
|
|
35
|
+
*/
|
|
36
|
+
export declare function extractTextAsync(path: string, deadline?: number): Promise<{
|
|
37
|
+
text: string;
|
|
38
|
+
} | {
|
|
39
|
+
error: string;
|
|
40
|
+
}>;
|
package/dist/extract.js
CHANGED
|
@@ -7,8 +7,18 @@
|
|
|
7
7
|
* `textutil` for Word/RTF/ODT on macOS, and `unzip` for the zipped XML
|
|
8
8
|
* formats (docx, pptx, odt) elsewhere. When none is available the caller
|
|
9
9
|
* gets a reason that names what to install, never a silent skip.
|
|
10
|
+
*
|
|
11
|
+
* Two safety rules, both learned from a QA pass on uploads over --http:
|
|
12
|
+
* - textutil runs with -noload -nostore. A ".doc" that is really HTML made
|
|
13
|
+
* textutil fetch its stylesheets and images, from 127.0.0.1 and from
|
|
14
|
+
* 169.254.169.254 as readily as from the web: a server-side request
|
|
15
|
+
* forgery through a document;
|
|
16
|
+
* - the MCP server extracts with extractTextAsync, which never blocks the
|
|
17
|
+
* event loop and stops at a time budget for the whole call (a slow PDF
|
|
18
|
+
* held /health for 30 s; one can take 120 s). The synchronous
|
|
19
|
+
* extractText stays for the one-shot CLI.
|
|
10
20
|
*/
|
|
11
|
-
import { spawnSync } from "node:child_process";
|
|
21
|
+
import { execFile, spawnSync } from "node:child_process";
|
|
12
22
|
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
13
23
|
import { tmpdir } from "node:os";
|
|
14
24
|
import { dirname, extname, join } from "node:path";
|
|
@@ -23,6 +33,8 @@ function run(cmd, args) {
|
|
|
23
33
|
return undefined;
|
|
24
34
|
}
|
|
25
35
|
}
|
|
36
|
+
/** Never load or write a document's subsidiary resources (stylesheets, images, frames). */
|
|
37
|
+
export const TEXTUTIL_ARGS = ["-convert", "txt", "-noload", "-nostore", "-stdout"];
|
|
26
38
|
const PDFKIT_JXA = 'ObjC.import("PDFKit"); function run(a) { const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(a[0])); return d.isNil() ? "" : d.string.js }';
|
|
27
39
|
/**
|
|
28
40
|
* pdftotext comes in two families (poppler, and Xpdf as shipped with some
|
|
@@ -49,8 +61,9 @@ function pdftotext(path) {
|
|
|
49
61
|
/** Paragraph-ish text from zipped XML: one paragraph per closing p/slide-text tag, entities decoded. */
|
|
50
62
|
function fromZippedXml(path, members) {
|
|
51
63
|
const xml = run("unzip", ["-p", path, ...members]);
|
|
52
|
-
|
|
53
|
-
|
|
64
|
+
return xml ? xmlToText(xml) : undefined;
|
|
65
|
+
}
|
|
66
|
+
function xmlToText(xml) {
|
|
54
67
|
return xml
|
|
55
68
|
.replace(/<\/(w:p|a:p|text:p|text:h)>/g, "\n\n")
|
|
56
69
|
.replace(/<(w:tab|w:br)\/>/g, " ")
|
|
@@ -75,7 +88,7 @@ export function extractText(path) {
|
|
|
75
88
|
}
|
|
76
89
|
else {
|
|
77
90
|
if (mac && ext !== ".pptx")
|
|
78
|
-
text = run("textutil", [
|
|
91
|
+
text = run("textutil", [...TEXTUTIL_ARGS, path]);
|
|
79
92
|
if (!text) {
|
|
80
93
|
const members = ext === ".docx" ? ["word/document.xml"] : ext === ".pptx" ? ["ppt/slides/*.xml"] : ext === ".odt" ? ["content.xml"] : [];
|
|
81
94
|
if (members.length)
|
|
@@ -86,3 +99,107 @@ export function extractText(path) {
|
|
|
86
99
|
}
|
|
87
100
|
return { text };
|
|
88
101
|
}
|
|
102
|
+
/** Default time budget for one extraction call in the MCP server. */
|
|
103
|
+
export const EXTRACT_BUDGET_MS = 20_000;
|
|
104
|
+
/**
|
|
105
|
+
* A command's stdout, or undefined, without blocking the event loop: killed
|
|
106
|
+
* (SIGKILL) when `deadline` passes. `timedOut` says which happened.
|
|
107
|
+
*/
|
|
108
|
+
function runAsync(cmd, args, deadline) {
|
|
109
|
+
const timeout = deadline - Date.now();
|
|
110
|
+
if (timeout <= 0)
|
|
111
|
+
return Promise.resolve({ timedOut: true });
|
|
112
|
+
return new Promise((resolve) => {
|
|
113
|
+
let settled = false;
|
|
114
|
+
const finish = (r) => {
|
|
115
|
+
if (settled)
|
|
116
|
+
return;
|
|
117
|
+
settled = true;
|
|
118
|
+
clearTimeout(timer);
|
|
119
|
+
resolve(r);
|
|
120
|
+
};
|
|
121
|
+
let child;
|
|
122
|
+
// execFile's own timeout kills the child, but its callback waits for the
|
|
123
|
+
// output pipes to close, which a grandchild can hold open: answer at the
|
|
124
|
+
// deadline whatever the pipes do.
|
|
125
|
+
const timer = setTimeout(() => {
|
|
126
|
+
child?.kill("SIGKILL");
|
|
127
|
+
finish({ timedOut: true });
|
|
128
|
+
}, timeout);
|
|
129
|
+
try {
|
|
130
|
+
child = execFile(cmd, args, { encoding: "utf8", timeout, killSignal: "SIGKILL", maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (err, stdout) => {
|
|
131
|
+
if (err)
|
|
132
|
+
return finish({ timedOut: Boolean(err.killed) || Date.now() >= deadline });
|
|
133
|
+
finish({ out: typeof stdout === "string" && stdout.trim() ? stdout : undefined, timedOut: false });
|
|
134
|
+
});
|
|
135
|
+
child.on("error", () => finish({ timedOut: false }));
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
finish({ timedOut: false });
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* extractText for a server: asynchronous, and bounded by `deadline` (ms since
|
|
144
|
+
* the epoch) across every tool it tries. Past the deadline the reason says so.
|
|
145
|
+
*/
|
|
146
|
+
export async function extractTextAsync(path, deadline = Date.now() + EXTRACT_BUDGET_MS) {
|
|
147
|
+
const ext = extname(path).toLowerCase();
|
|
148
|
+
const mac = process.platform === "darwin";
|
|
149
|
+
let text;
|
|
150
|
+
let timedOut = false;
|
|
151
|
+
const tryRun = async (cmd, args) => {
|
|
152
|
+
if (text || timedOut)
|
|
153
|
+
return;
|
|
154
|
+
const r = await runAsync(cmd, args, deadline);
|
|
155
|
+
if (r.timedOut)
|
|
156
|
+
timedOut = true;
|
|
157
|
+
else
|
|
158
|
+
text = r.out;
|
|
159
|
+
};
|
|
160
|
+
const late = () => ({ error: "not read: the time allowed for reading documents in this call ran out" });
|
|
161
|
+
if (ext === ".pdf") {
|
|
162
|
+
await tryRun("pdftotext", ["-enc", "UTF-8", path, "-"]);
|
|
163
|
+
await tryRun("pdftotext", [path, "-"]);
|
|
164
|
+
if (!text && !timedOut) {
|
|
165
|
+
const out = join(mkdtempSync(join(tmpdir(), "cd-pdf-")), "out.txt");
|
|
166
|
+
try {
|
|
167
|
+
const r = await runAsync("pdftotext", [path, out], deadline);
|
|
168
|
+
if (r.timedOut)
|
|
169
|
+
timedOut = true;
|
|
170
|
+
else if (existsSync(out))
|
|
171
|
+
text = readFileSync(out, "utf8").trim() ? readFileSync(out, "utf8") : undefined;
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
rmSync(dirname(out), { recursive: true, force: true });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
text = text?.replace(/\f/g, "\n\n");
|
|
178
|
+
if (!text && mac)
|
|
179
|
+
await tryRun("osascript", ["-l", "JavaScript", "-e", PDFKIT_JXA, path]);
|
|
180
|
+
if (!text) {
|
|
181
|
+
if (timedOut)
|
|
182
|
+
return late();
|
|
183
|
+
return { error: mac ? "no text layer (scanned PDF?) or unreadable" : "needs pdftotext (install poppler-utils), or the PDF has no text layer" };
|
|
184
|
+
}
|
|
185
|
+
return { text };
|
|
186
|
+
}
|
|
187
|
+
if (mac && ext !== ".pptx")
|
|
188
|
+
await tryRun("textutil", [...TEXTUTIL_ARGS, path]);
|
|
189
|
+
if (!text && !timedOut) {
|
|
190
|
+
const members = ext === ".docx" ? ["word/document.xml"] : ext === ".pptx" ? ["ppt/slides/*.xml"] : ext === ".odt" ? ["content.xml"] : [];
|
|
191
|
+
if (members.length) {
|
|
192
|
+
const r = await runAsync("unzip", ["-p", path, ...members], deadline);
|
|
193
|
+
if (r.timedOut)
|
|
194
|
+
timedOut = true;
|
|
195
|
+
else if (r.out)
|
|
196
|
+
text = xmlToText(r.out);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (!text) {
|
|
200
|
+
if (timedOut)
|
|
201
|
+
return late();
|
|
202
|
+
return { error: mac ? "unreadable document" : `needs unzip${ext === ".doc" || ext === ".rtf" ? " (and .doc/.rtf need macOS textutil; save as .docx)" : ""}` };
|
|
203
|
+
}
|
|
204
|
+
return { text };
|
|
205
|
+
}
|