dsh-context-mode 0.1.3 → 0.2.1

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 (58) hide show
  1. package/LICENSING.md +37 -0
  2. package/README.md +39 -13
  3. package/lib/types/cjk.d.ts +54 -0
  4. package/lib/types/cjk.d.ts.map +1 -0
  5. package/lib/types/cjk.js +64 -0
  6. package/lib/types/index.d.ts.map +1 -1
  7. package/lib/types/index.js +65 -21
  8. package/lib/types/output-containment.d.ts +35 -0
  9. package/lib/types/output-containment.d.ts.map +1 -0
  10. package/lib/types/output-containment.js +103 -0
  11. package/lib/types/routing.d.ts +3 -1
  12. package/lib/types/routing.d.ts.map +1 -1
  13. package/lib/types/routing.js +81 -6
  14. package/package.json +9 -5
  15. package/skills/context-mode/SKILL.md +104 -11
  16. package/vendor/context-mode/LICENSE +94 -0
  17. package/vendor/context-mode/server.bundle.mjs +1127 -0
  18. package/vendor/context-mode/src/cli.ts +2040 -0
  19. package/vendor/context-mode/src/db-base.ts +617 -0
  20. package/vendor/context-mode/src/executor.ts +785 -0
  21. package/vendor/context-mode/src/exit-classify.ts +33 -0
  22. package/vendor/context-mode/src/fetch-cache.ts +15 -0
  23. package/vendor/context-mode/src/lifecycle.ts +305 -0
  24. package/vendor/context-mode/src/platform/client-map.ts +45 -0
  25. package/vendor/context-mode/src/platform/detect.ts +645 -0
  26. package/vendor/context-mode/src/platform/dsh.ts +206 -0
  27. package/vendor/context-mode/src/platform/types.ts +503 -0
  28. package/vendor/context-mode/src/runPool.ts +81 -0
  29. package/vendor/context-mode/src/runtime.ts +765 -0
  30. package/vendor/context-mode/src/search/auto-memory.ts +200 -0
  31. package/vendor/context-mode/src/search/ctx-search-schema.ts +143 -0
  32. package/vendor/context-mode/src/search/flood-guard.ts +111 -0
  33. package/vendor/context-mode/src/search/unified.ts +176 -0
  34. package/vendor/context-mode/src/security.ts +889 -0
  35. package/vendor/context-mode/src/server.ts +5052 -0
  36. package/vendor/context-mode/src/session/analytics.ts +3085 -0
  37. package/vendor/context-mode/src/session/db.ts +1726 -0
  38. package/vendor/context-mode/src/session/error-classifier.ts +392 -0
  39. package/vendor/context-mode/src/session/event-emit.ts +132 -0
  40. package/vendor/context-mode/src/session/extract.ts +2958 -0
  41. package/vendor/context-mode/src/session/index.ts +130 -0
  42. package/vendor/context-mode/src/session/model-prices.json +429 -0
  43. package/vendor/context-mode/src/session/persist-tool-calls.ts +128 -0
  44. package/vendor/context-mode/src/session/pricing.ts +191 -0
  45. package/vendor/context-mode/src/session/project-attribution.ts +309 -0
  46. package/vendor/context-mode/src/session/purge.ts +338 -0
  47. package/vendor/context-mode/src/session/retrieval-marker.ts +65 -0
  48. package/vendor/context-mode/src/session/snapshot.ts +577 -0
  49. package/vendor/context-mode/src/store-directory.ts +290 -0
  50. package/vendor/context-mode/src/store.ts +2071 -0
  51. package/vendor/context-mode/src/truncate.ts +154 -0
  52. package/vendor/context-mode/src/types.ts +147 -0
  53. package/vendor/context-mode/src/util/claude-config.ts +95 -0
  54. package/vendor/context-mode/src/util/hook-config.ts +78 -0
  55. package/vendor/context-mode/src/util/jsonc.ts +70 -0
  56. package/vendor/context-mode/src/util/plugin-cache-integrity.ts +167 -0
  57. package/vendor/context-mode/src/util/project-dir.ts +347 -0
  58. package/vendor/context-mode/src/util/sibling-mcp.ts +228 -0
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Classify non-zero exit codes for ctx_execute / ctx_execute_file.
3
+ *
4
+ * Shell commands like `grep` exit 1 for "no matches" — not a real error.
5
+ * We treat exit code 1 as a soft failure when:
6
+ * - language is "shell"
7
+ * - exit code is exactly 1
8
+ * - stdout has non-whitespace content
9
+ */
10
+ export interface ExitClassification {
11
+ isError: boolean;
12
+ output: string;
13
+ }
14
+
15
+ export function classifyNonZeroExit(params: {
16
+ language: string;
17
+ exitCode: number;
18
+ stdout: string;
19
+ stderr: string;
20
+ }): ExitClassification {
21
+ const { language, exitCode, stdout, stderr } = params;
22
+ const isSoftFail =
23
+ language === "shell" &&
24
+ exitCode === 1 &&
25
+ stdout.trim().length > 0;
26
+
27
+ return {
28
+ isError: !isSoftFail,
29
+ output: isSoftFail
30
+ ? stdout
31
+ : `Exit code: ${exitCode}\n\nstdout:\n${stdout}\n\nstderr:\n${stderr}`,
32
+ };
33
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Cache-key / storage-label composition for ctx_fetch_and_index.
3
+ *
4
+ * Two distinct URLs that share a user-supplied `source` label MUST NOT collide
5
+ * in the cache (or in FTS5 storage, since indexing dedups by label). Compose
6
+ * `${source}::${url}` whenever a `source` is explicitly provided so cache
7
+ * lookup, dedup, and re-indexing are all per-(source,url). When no `source`
8
+ * is provided the URL itself is the unique key — no composition needed.
9
+ *
10
+ * `ctx_search(source: "Docs")` continues to work because LIKE-mode source
11
+ * filtering matches on the substring "Docs" inside "Docs::https://…".
12
+ */
13
+ export function composeFetchCacheKey(source: string | undefined, url: string): string {
14
+ return source === undefined ? url : `${source}::${url}`;
15
+ }
@@ -0,0 +1,305 @@
1
+ /**
2
+ * lifecycle — Process lifecycle guard for MCP server.
3
+ *
4
+ * Detects parent process death (ppid polling) and OS signals to prevent
5
+ * orphaned MCP server processes consuming 100% CPU (issue #103).
6
+ *
7
+ * Stdin close is NOT used as a *standalone* shutdown signal — the MCP stdio
8
+ * transport owns stdin and transient pipe events cause spurious -32000
9
+ * errors (#236). We do, however, treat stdin EOF as a hint to re-run the
10
+ * parent-liveness probe immediately (instead of waiting up to 30 s for the
11
+ * next poll tick), which closes the multi-day CPU-spin window seen in
12
+ * #311/#388 without reintroducing the false-positive shutdowns of #236.
13
+ *
14
+ * Additionally, for MCP BRIDGE CHILDREN only (CONTEXT_MODE_BRIDGE_DEPTH>0), a
15
+ * request-idle self-shutdown reaps a child that a pi/omp sub-context abandoned
16
+ * while its long-lived parent keeps running (#854) — gated so the depth-0
17
+ * keep-alive servers #602 restored are never reaped, never via stdin EOF, and
18
+ * never while a tool call is in flight (#643).
19
+ *
20
+ * Cross-platform: macOS, Linux, Windows.
21
+ */
22
+
23
+ import { execFileSync } from "node:child_process";
24
+
25
+ export interface LifecycleGuardOptions {
26
+ /** Interval in ms to check parent liveness. Default: 30_000 */
27
+ checkIntervalMs?: number;
28
+ /** Called when parent death or OS signal is detected. */
29
+ onShutdown: () => void;
30
+ /** Injectable parent-alive check (for testing). Default: ppid-based check. */
31
+ isParentAlive?: () => boolean;
32
+ /**
33
+ * #854: request-idle shutdown timeout (ms) for MCP bridge children. Default:
34
+ * {@link bridgeChildIdleTimeoutMs}() — 0 (disabled) unless CONTEXT_MODE_BRIDGE_DEPTH>0.
35
+ * Exposed for testing.
36
+ */
37
+ bridgeIdleMs?: number;
38
+ }
39
+
40
+ /** Read grandparent PID via `ps -o ppid= -p $PPID`. Returns NaN on failure or Windows. */
41
+ function readGrandparentPpidImpl(): number {
42
+ if (process.platform === "win32") return NaN;
43
+ const ppid = process.ppid;
44
+ if (!ppid || ppid <= 1) return NaN;
45
+ try {
46
+ const out = execFileSync("ps", ["-o", "ppid=", "-p", String(ppid)], {
47
+ encoding: "utf-8",
48
+ timeout: 2000,
49
+ stdio: ["ignore", "pipe", "ignore"],
50
+ }).trim();
51
+ const n = parseInt(out, 10);
52
+ return Number.isFinite(n) ? n : NaN;
53
+ } catch {
54
+ return NaN;
55
+ }
56
+ }
57
+
58
+ /** Injectable dependencies for {@link makeDefaultIsParentAlive}. */
59
+ export interface IsParentAliveDeps {
60
+ /** Read the current ppid. Default: `() => process.ppid`. */
61
+ getPpid?: () => number;
62
+ /** Read the grandparent ppid. Default: ps-based POSIX probe, NaN on Windows. */
63
+ readGrandparentPpid?: () => number;
64
+ }
65
+
66
+ /**
67
+ * Build a parent-liveness check that handles the npm-exec wrapper case (#311).
68
+ *
69
+ * A plain ppid comparison misses Claude Code sessions launched via
70
+ * `start.mjs → npm exec → context-mode server`: when Claude Code dies,
71
+ * `start.mjs` reparents to init but `npm exec` stays alive, so the server's
72
+ * direct ppid never changes. We additionally check whether the grandparent
73
+ * process has been reparented to init (PID 1). When the original grandparent
74
+ * was already 1 (daemonized startup) the check is skipped, and on Windows
75
+ * where there's no cheap `ps` equivalent we also skip — so this change is
76
+ * strictly additive to the previous behavior.
77
+ *
78
+ * Exported for unit-testing with injected readers. Production code uses
79
+ * {@link defaultIsParentAlive} (captured once at module load).
80
+ */
81
+ export function makeDefaultIsParentAlive(deps: IsParentAliveDeps = {}): () => boolean {
82
+ const getPpid = deps.getPpid ?? (() => process.ppid);
83
+ const readGp = deps.readGrandparentPpid ?? readGrandparentPpidImpl;
84
+ const originalPpid = getPpid();
85
+ const originalGrandparentPpid = readGp();
86
+
87
+ return () => {
88
+ const ppid = getPpid();
89
+ if (ppid !== originalPpid) return false;
90
+ if (ppid === 0 || ppid === 1) return false;
91
+
92
+ // Grandparent orphan check (#311): npm-exec wrappers stay alive past the
93
+ // session owner. If our grandparent is now PID 1 but wasn't at startup,
94
+ // the wrapping chain is orphaned and we should shut down.
95
+ if (!Number.isNaN(originalGrandparentPpid) && originalGrandparentPpid > 1) {
96
+ if (readGp() === 1) return false;
97
+ }
98
+
99
+ return true;
100
+ };
101
+ }
102
+
103
+ const defaultIsParentAlive = makeDefaultIsParentAlive();
104
+
105
+ /**
106
+ * Resolve the parent-liveness poll interval based on context (#534).
107
+ *
108
+ * When this process is the MCP bridge child spawned by the Pi adapter
109
+ * (`bootstrapMCPTools` in `src/adapters/pi/mcp-bridge.ts` sets
110
+ * `CONTEXT_MODE_BRIDGE_DEPTH=1` in the child env), we tighten the poll to
111
+ * 1 s. The Pi parent can disappear in under 50 ms (`pi --help` prints
112
+ * usage and returns), so the default 30 s window leaves a long-lived
113
+ * CPU-spinning orphan. For top-level MCP servers (depth 0 / absent) we
114
+ * keep the original 30 s cadence — the existing #311/#388 ppid + stdin
115
+ * recovery paths already cover Claude Code style hosts.
116
+ *
117
+ * Exported for unit-testing.
118
+ */
119
+ export function lifecycleGuardIntervalForEnv(
120
+ env: NodeJS.ProcessEnv = process.env,
121
+ ): number {
122
+ const raw = env.CONTEXT_MODE_BRIDGE_DEPTH;
123
+ if (raw === undefined) return 30_000;
124
+ const depth = Number.parseInt(raw, 10);
125
+ if (!Number.isFinite(depth) || depth <= 0) return 30_000;
126
+ return 1000;
127
+ }
128
+
129
+ /**
130
+ * #854: idle-shutdown timeout (ms) for an MCP BRIDGE CHILD. Returns 0 (disabled)
131
+ * unless this process is a bridge child (CONTEXT_MODE_BRIDGE_DEPTH>0). depth-0 /
132
+ * absent always returns 0, so the long-lived keep-alive servers that #602
133
+ * restored are NEVER reaped on idle. Default for bridge children is 3 min;
134
+ * override with CONTEXT_MODE_BRIDGE_IDLE_MS (a non-positive value disables it).
135
+ * The reaper additionally never fires while a tool call is in flight (see
136
+ * {@link noteRequestStart}), so the window only bounds how fast *abandoned*
137
+ * children drain — it does not cap legitimate long-running calls.
138
+ *
139
+ * Exported for unit-testing.
140
+ */
141
+ export function bridgeChildIdleTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {
142
+ const depth = Number.parseInt(env.CONTEXT_MODE_BRIDGE_DEPTH ?? "", 10);
143
+ if (!Number.isFinite(depth) || depth <= 0) return 0;
144
+ const raw = env.CONTEXT_MODE_BRIDGE_IDLE_MS;
145
+ if (raw !== undefined) {
146
+ const v = Number.parseInt(raw, 10);
147
+ return Number.isFinite(v) && v > 0 ? v : 0;
148
+ }
149
+ return 180_000;
150
+ }
151
+
152
+ /**
153
+ * #854 / #868: human-readable notice emitted when an idle bridge child is
154
+ * released. DX-tuned — human units (seconds, not raw ms), reassures that the
155
+ * helper reconnects automatically (it respawns on the next ctx_* call, #583),
156
+ * and drops the alarming "self-shutdown" jargon. Pure + exported so the wording
157
+ * is pinned by a test and stays grep-friendly via the #854 tag. Note: after the
158
+ * #868 fix this fires ONLY for sub-context / non-interactive children — the
159
+ * foreground interactive session's child runs with the reaper disabled.
160
+ */
161
+ export function idleReapMessage(idleMs: number): string {
162
+ const seconds = Math.round(idleMs / 1000);
163
+ return `[context-mode] Released an idle MCP helper after ${seconds}s of inactivity to free memory; it reconnects automatically on next use. (#854)`;
164
+ }
165
+
166
+ // #854 idle-reaper state, module-level by design: an MCP server is exactly one
167
+ // process (one StdioServerTransport + one lifecycle guard), so these are never
168
+ // shared across concurrent servers in production. Multiple startLifecycleGuard()
169
+ // instances arise only in tests, which pair/reset these explicitly.
170
+ /** Last MCP activity timestamp (inbound message, tool-call start/end, or response). */
171
+ let _lastMcpActivity = Date.now();
172
+ /** In-flight tool-call count — the reaper never fires while this is > 0. */
173
+ let _inFlight = 0;
174
+
175
+ /**
176
+ * #854: record MCP activity (inbound message or response). The server calls this
177
+ * so the bridge-child idle reaper in {@link startLifecycleGuard} can distinguish
178
+ * an actively-used child from an abandoned one. Cheap; safe on the hot path.
179
+ */
180
+ export function noteMcpActivity(): void {
181
+ _lastMcpActivity = Date.now();
182
+ }
183
+
184
+ /**
185
+ * #854: mark a tool call as started. Suppresses the bridge-child idle reaper so a
186
+ * single long-running ctx_execute / ctx_batch_execute (which sends one inbound
187
+ * frame then runs unbounded, #643) is never reaped mid-execution.
188
+ */
189
+ export function noteRequestStart(): void {
190
+ _inFlight++;
191
+ _lastMcpActivity = Date.now();
192
+ }
193
+
194
+ /** #854: mark a tool call as finished (success or error). */
195
+ export function noteRequestEnd(): void {
196
+ if (_inFlight > 0) _inFlight--;
197
+ _lastMcpActivity = Date.now();
198
+ }
199
+
200
+ /**
201
+ * #854: wrap an MCP stdio transport's `onmessage` so each inbound message
202
+ * refreshes the idle clock. Best-effort: call after `connect()` (onmessage set);
203
+ * a no-op if it isn't a function, and a throw in noteMcpActivity never breaks
204
+ * dispatch. No stdin touch (preserves the #236 contract). Exported for testing.
205
+ */
206
+ export function attachMcpActivityTap(
207
+ transport: { onmessage?: (message: unknown, extra?: unknown) => unknown } | null | undefined,
208
+ ): void {
209
+ if (!transport) return;
210
+ const prev = typeof transport.onmessage === "function" ? transport.onmessage.bind(transport) : null;
211
+ if (!prev) return;
212
+ transport.onmessage = (message: unknown, extra?: unknown) => {
213
+ try { noteMcpActivity(); } catch { /* never break message dispatch */ }
214
+ return prev(message, extra);
215
+ };
216
+ }
217
+
218
+ /**
219
+ * Start the lifecycle guard. Returns a cleanup function.
220
+ * Skipped automatically when stdin is a TTY (e.g. OpenCode ts-plugin).
221
+ */
222
+ export function startLifecycleGuard(opts: LifecycleGuardOptions): () => void {
223
+ const interval = opts.checkIntervalMs ?? lifecycleGuardIntervalForEnv();
224
+ const check = opts.isParentAlive ?? defaultIsParentAlive;
225
+ let stopped = false;
226
+
227
+ const shutdown = () => {
228
+ if (stopped) return;
229
+ stopped = true;
230
+ opts.onShutdown();
231
+ };
232
+
233
+ // P0: Periodic parent liveness check
234
+ const timer = setInterval(() => {
235
+ if (!check()) shutdown();
236
+ }, interval);
237
+ timer.unref();
238
+
239
+ // P0: OS signals — terminal close, kill, ctrl+c
240
+ const signals: NodeJS.Signals[] = ["SIGTERM", "SIGINT"];
241
+ if (process.platform !== "win32") signals.push("SIGHUP");
242
+ for (const sig of signals) process.on(sig, shutdown);
243
+
244
+ // P0: Stdin-EOF assist (#311/#388). The vendored MCP SDK's
245
+ // StdioServerTransport only registers 'data' / 'error' listeners — not
246
+ // 'end' — so when the parent (e.g. Claude Code) dies abruptly without
247
+ // sending SIGTERM, the server keeps reading from a half-closed pipe and
248
+ // CPU-spins until the 30 s ppid poll catches up. Observed in #388 with
249
+ // single processes accumulating ~80 h of CPU time before SIGKILL.
250
+ //
251
+ // We deliberately DO NOT call shutdown() unconditionally on 'end' — that
252
+ // is exactly the false-positive behavior #236 tore out. Instead we run
253
+ // the same isParentAlive() check the periodic timer uses, just earlier.
254
+ // If the parent is alive, this is a no-op and the existing #236
255
+ // regression test still passes; if the parent is gone, we collapse the
256
+ // 30 s detection window to ~0.
257
+ //
258
+ // Skipped on TTY (OpenCode ts-plugin) where stdin is not the MCP channel.
259
+ const onStdinEnd = () => {
260
+ if (!check()) shutdown();
261
+ };
262
+ if (!process.stdin.isTTY) {
263
+ process.stdin.on("end", onStdinEnd);
264
+ }
265
+
266
+ // #854: request-idle self-shutdown for MCP BRIDGE CHILDREN only
267
+ // (CONTEXT_MODE_BRIDGE_DEPTH>0). Pi/omp loads the extension once per
268
+ // sub-context and spawns one bridge child each, tearing them down only at
269
+ // session_shutdown — which never fires for sub-contexts while the long-lived
270
+ // parent stays alive, so idle children accumulate (#854, same class as #565).
271
+ // A bridge child that receives no inbound MCP message for `idleMs` exits
272
+ // itself; the extension's single-flight path respawns one on the next call.
273
+ //
274
+ // Scoped strictly to depth>0 so the depth-0 keep-alive servers that #602
275
+ // restored are never reaped on idle. The trigger is idle TIME via
276
+ // noteMcpActivity() (NOT stdin EOF), so the #236 contract — and lifecycle's
277
+ // hands-off-stdin invariant — are untouched.
278
+ const idleMs = opts.bridgeIdleMs ?? bridgeChildIdleTimeoutMs();
279
+ let idleTimer: ReturnType<typeof setInterval> | undefined;
280
+ if (idleMs > 0) {
281
+ _lastMcpActivity = Date.now();
282
+ idleTimer = setInterval(() => {
283
+ // Reap only when truly quiescent: NO tool call in flight AND no MCP
284
+ // activity for `idleMs`. The in-flight guard prevents reaping a child
285
+ // mid-execution during a long single ctx_execute/batch that sends no
286
+ // further messages (#643 unbounded calls) — the false-reap regression the
287
+ // adversarial review flagged.
288
+ if (_inFlight === 0 && Date.now() - _lastMcpActivity >= idleMs) {
289
+ // Child's own stderr — the pi bridge forwards it to pi.logger, never the
290
+ // TUI terminal (#868). DX-tuned wording via idleReapMessage.
291
+ process.stderr.write(idleReapMessage(idleMs) + "\n");
292
+ shutdown();
293
+ }
294
+ }, Math.max(1000, Math.min(Math.floor(idleMs / 4), 30_000)));
295
+ idleTimer.unref();
296
+ }
297
+
298
+ return () => {
299
+ stopped = true;
300
+ clearInterval(timer);
301
+ if (idleTimer) clearInterval(idleTimer);
302
+ for (const sig of signals) process.removeListener(sig, shutdown);
303
+ process.stdin.removeListener("end", onStdinEnd);
304
+ };
305
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * adapters/client-map — MCP clientInfo.name → PlatformId mapping.
3
+ *
4
+ * Source: Apify MCP Client Capabilities Registry
5
+ * https://github.com/apify/mcp-client-capabilities
6
+ *
7
+ * Only includes platforms we have adapters for.
8
+ */
9
+
10
+ import type { PlatformId } from "./types.js";
11
+
12
+ export const CLIENT_NAME_TO_PLATFORM: Record<string, PlatformId> = {
13
+ "claude-code": "claude-code",
14
+ "gemini-cli-mcp-client": "gemini-cli",
15
+ "antigravity-client": "antigravity",
16
+ "antigravity-cli": "antigravity-cli",
17
+ "agy": "antigravity-cli",
18
+ "cursor-vscode": "cursor",
19
+ "Visual-Studio-Code": "vscode-copilot",
20
+ "copilot-cli": "copilot-cli",
21
+ "GitHub Copilot CLI": "copilot-cli",
22
+ "github-copilot-cli": "copilot-cli",
23
+ "JetBrains Client": "jetbrains-copilot",
24
+ "IntelliJ IDEA": "jetbrains-copilot",
25
+ "PyCharm": "jetbrains-copilot",
26
+ "Codex": "codex",
27
+ "codex-mcp-client": "codex",
28
+ "Kilo Code": "kilo",
29
+ "Kiro CLI": "kiro",
30
+ "Pi CLI": "pi",
31
+ "Pi Coding Agent": "pi",
32
+ // Issue #542 — Pi rebranded to OMP. Upstream
33
+ // refs/platforms/oh-my-pi/packages/coding-agent/src/mcp/client.ts:46-49
34
+ // ships clientInfo.name = "omp-coding-agent". Resolved to the OMP
35
+ // adapter (~/.omp/, PI_CODING_AGENT_DIR). Legacy "Pi CLI" /
36
+ // "Pi Coding Agent" entries above still resolve to the pi adapter.
37
+ "omp-coding-agent": "omp",
38
+ "Zed": "zed",
39
+ "zed": "zed",
40
+ "qwen-code": "qwen-code",
41
+ "qwen-cli-mcp-client": "qwen-code",
42
+ "kimi-code": "kimi",
43
+ "kimi": "kimi",
44
+ "Kimi Code": "kimi",
45
+ };