@wraith-ai/core 0.1.0 → 0.1.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 (153) hide show
  1. package/README.md +1 -1
  2. package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
  3. package/dist/attempt-HgararU3.d.mts.map +1 -0
  4. package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
  5. package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
  6. package/dist/index.d.mts +6 -5
  7. package/dist/index.d.mts.map +1 -0
  8. package/dist/index.mjs +11 -9
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
  11. package/dist/methods-7Ryz6zbd.mjs.map +1 -0
  12. package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
  13. package/dist/model-C16NUwXW.mjs.map +1 -0
  14. package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
  15. package/dist/model-_wqePNTL.d.mts.map +1 -0
  16. package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
  17. package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
  18. package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
  19. package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
  20. package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
  21. package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
  22. package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
  23. package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
  24. package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
  25. package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
  26. package/dist/providers/openai-codex.d.mts +4 -3
  27. package/dist/providers/openai-codex.d.mts.map +1 -0
  28. package/dist/providers/openai-codex.mjs +1 -1
  29. package/dist/providers/openai-compatible.d.mts +3 -2
  30. package/dist/providers/openai-compatible.d.mts.map +1 -0
  31. package/dist/providers/openai-compatible.mjs +1 -1
  32. package/dist/providers/openrouter.d.mts +3 -2
  33. package/dist/providers/openrouter.d.mts.map +1 -0
  34. package/dist/providers/openrouter.mjs +1 -1
  35. package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
  36. package/dist/shared-BIJaPhMm.mjs.map +1 -0
  37. package/dist/snapshot.d.mts +3 -2
  38. package/dist/snapshot.d.mts.map +1 -0
  39. package/dist/snapshot.mjs +4999 -4977
  40. package/dist/snapshot.mjs.map +1 -0
  41. package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
  42. package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
  43. package/package.json +3 -2
  44. package/src/agent/agent.ts +90 -0
  45. package/src/agent/attachments.ts +195 -0
  46. package/src/agent/classifier.ts +525 -0
  47. package/src/agent/compact.ts +384 -0
  48. package/src/agent/conversation.ts +300 -0
  49. package/src/agent/cost.ts +164 -0
  50. package/src/agent/inbox.ts +80 -0
  51. package/src/agent/instructions.ts +62 -0
  52. package/src/agent/loop.ts +675 -0
  53. package/src/agent/messages.ts +252 -0
  54. package/src/agent/on-demand.ts +58 -0
  55. package/src/agent/prompts.ts +35 -0
  56. package/src/agent/request-images.ts +94 -0
  57. package/src/agent/stop.ts +37 -0
  58. package/src/agent/title.ts +122 -0
  59. package/src/agent/tool-groups.ts +186 -0
  60. package/src/agent/tools.ts +106 -0
  61. package/src/app.ts +67 -0
  62. package/src/config/credential-file-store.ts +66 -0
  63. package/src/config/environment.ts +105 -0
  64. package/src/config/instructions.ts +157 -0
  65. package/src/config/load.ts +667 -0
  66. package/src/config/locked-file.ts +85 -0
  67. package/src/config/paths.ts +368 -0
  68. package/src/config/schema.ts +363 -0
  69. package/src/config/subagents.ts +156 -0
  70. package/src/config/trust.ts +53 -0
  71. package/src/config/write.ts +241 -0
  72. package/src/errors.ts +85 -0
  73. package/src/events/types.ts +258 -0
  74. package/src/glob.ts +161 -0
  75. package/src/index.ts +681 -0
  76. package/src/logger.ts +47 -0
  77. package/src/paths.ts +143 -0
  78. package/src/permissions/chain.ts +42 -0
  79. package/src/permissions/command.ts +233 -0
  80. package/src/permissions/layered.ts +77 -0
  81. package/src/permissions/match.ts +80 -0
  82. package/src/permissions/modes.ts +48 -0
  83. package/src/permissions/policy.ts +160 -0
  84. package/src/permissions/types.ts +159 -0
  85. package/src/providers/cache.ts +107 -0
  86. package/src/providers/capabilities.ts +77 -0
  87. package/src/providers/catalog-view.ts +91 -0
  88. package/src/providers/catalog.ts +65 -0
  89. package/src/providers/errors.ts +108 -0
  90. package/src/providers/factories/index.ts +15 -0
  91. package/src/providers/factories/openai-codex.ts +382 -0
  92. package/src/providers/factories/openai-compatible.ts +81 -0
  93. package/src/providers/factories/openrouter.ts +165 -0
  94. package/src/providers/factories/shared.ts +22 -0
  95. package/src/providers/model.ts +197 -0
  96. package/src/providers/models-dev.ts +355 -0
  97. package/src/providers/oauth/methods.ts +10 -0
  98. package/src/providers/oauth/openai-codex.ts +228 -0
  99. package/src/providers/oauth.ts +177 -0
  100. package/src/providers/openai-codex.ts +7 -0
  101. package/src/providers/openai-compatible.ts +2 -0
  102. package/src/providers/openrouter.ts +2 -0
  103. package/src/providers/registry.ts +464 -0
  104. package/src/providers/turn-effort.ts +156 -0
  105. package/src/providers/types.ts +83 -0
  106. package/src/session/backend.ts +44 -0
  107. package/src/session/file-store.ts +278 -0
  108. package/src/session/format.ts +1037 -0
  109. package/src/session/memory-store.ts +73 -0
  110. package/src/session/session.ts +153 -0
  111. package/src/session/store.ts +219 -0
  112. package/src/sign-in/attempt.ts +166 -0
  113. package/src/sign-in/loopback.ts +74 -0
  114. package/src/snapshot/data.json +8936 -0
  115. package/src/snapshot/index.ts +37 -0
  116. package/src/tools/bin.ts +364 -0
  117. package/src/tools/builtin.ts +48 -0
  118. package/src/tools/change.ts +88 -0
  119. package/src/tools/define.ts +267 -0
  120. package/src/tools/describe.ts +96 -0
  121. package/src/tools/fs/edit-file.ts +129 -0
  122. package/src/tools/fs/glob.ts +75 -0
  123. package/src/tools/fs/grep.ts +212 -0
  124. package/src/tools/fs/line-endings.ts +17 -0
  125. package/src/tools/fs/list-dir.ts +85 -0
  126. package/src/tools/fs/read-file.ts +230 -0
  127. package/src/tools/fs/ripgrep.ts +211 -0
  128. package/src/tools/fs/write-file.ts +97 -0
  129. package/src/tools/job.ts +252 -0
  130. package/src/tools/mcp/auth-store.ts +127 -0
  131. package/src/tools/mcp/command.ts +151 -0
  132. package/src/tools/mcp/config.ts +168 -0
  133. package/src/tools/mcp/servers.ts +463 -0
  134. package/src/tools/mcp/sign-in.ts +226 -0
  135. package/src/tools/mcp/stdio.ts +204 -0
  136. package/src/tools/mcp/tools.ts +173 -0
  137. package/src/tools/on-demand.ts +184 -0
  138. package/src/tools/registry.ts +935 -0
  139. package/src/tools/shell/bash.ts +217 -0
  140. package/src/tools/shell/find-bash.ts +162 -0
  141. package/src/tools/source.ts +35 -0
  142. package/src/tools/spill.ts +127 -0
  143. package/src/tools/subagents.ts +597 -0
  144. package/src/tools/tasks.ts +603 -0
  145. package/src/tools/to-model.ts +33 -0
  146. package/src/tools/web/address.ts +95 -0
  147. package/src/tools/web/exa.ts +163 -0
  148. package/src/tools/web/fetch.ts +373 -0
  149. package/src/tools/web/html.ts +173 -0
  150. package/src/tools/web/search.ts +111 -0
  151. package/src/tools/web/source.ts +51 -0
  152. package/src/units.ts +18 -0
  153. package/src/version.ts +23 -0
@@ -0,0 +1,211 @@
1
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { runProcess } from "../bin";
4
+
5
+ /**
6
+ * The bundled copy of `rg` is unpacked to disk first, since `spawn` cannot run
7
+ * a path inside the binary. Failures are silent, so four things go with it:
8
+ *
9
+ * 1. a fallback to `rg` on PATH when unpacking fails,
10
+ * 2. `tools.ripgrepPath`, which wins over everything,
11
+ * 3. a retry on EAGAIN/ETXTBSY, for an executable that is still held,
12
+ * 4. one status type, readable without a search, which `doctor` prints.
13
+ */
14
+
15
+ /**
16
+ * A ripgrep we intend to run. Resolution cannot produce `missing`: whether PATH
17
+ * has one is known only once something is spawned.
18
+ */
19
+ export type RipgrepLocation =
20
+ | { mode: "bundled"; path: string; version: string }
21
+ | { mode: "path"; path: string }
22
+ | { mode: "configured"; path: string };
23
+
24
+ export type RipgrepStatus = RipgrepLocation | { mode: "missing"; tried: string[] };
25
+
26
+ /** The name we spawn when PATH is expected to resolve it. */
27
+ export const RIPGREP_COMMAND = "rg";
28
+
29
+ export interface BundledRipgrep {
30
+ /** Path handed over by the asset import — inside the binary, not on disk. */
31
+ path: string;
32
+ /** Names the unpacked file, so a new release never overwrites a running one. */
33
+ version: string;
34
+ }
35
+
36
+ export interface RipgrepOptions {
37
+ /** `tools.ripgrepPath`. Wins over everything, like `bashPath`. */
38
+ configured?: string;
39
+ /** The copy compiled in, when there is one. */
40
+ bundled?: BundledRipgrep;
41
+ /** `~/.wraith/cache`; the unpacked copy lands in `bin/` beneath it. */
42
+ cacheDir?: string;
43
+ }
44
+
45
+ export interface RipgrepDeps {
46
+ platform: string;
47
+ /** True when the path holds a usable, non-empty file. */
48
+ exists: (path: string) => Promise<boolean>;
49
+ /** Copies the bundled file onto a real disk and makes it executable. */
50
+ unpack: (from: string, to: string) => Promise<void>;
51
+ /** Runs `<path> --version`; false when it cannot be executed at all. */
52
+ probe: (path: string) => Promise<boolean>;
53
+ }
54
+
55
+ /** Where an unpacked copy lives, given the user's cache directory. */
56
+ export function unpackedRipgrepPath(
57
+ cacheDir: string,
58
+ version: string,
59
+ platform: string,
60
+ ): string {
61
+ const suffix = platform === "win32" ? ".exe" : "";
62
+ // The version is in the name: replacing a file that another process may
63
+ // have open fails on Windows and is worse than harmless on POSIX.
64
+ return join(cacheDir, "bin", `rg-${version}${suffix}`);
65
+ }
66
+
67
+ async function unpackDefault(from: string, to: string): Promise<void> {
68
+ await mkdir(dirname(to), { recursive: true });
69
+
70
+ // Written aside and moved into place: two agents starting at once must not
71
+ // leave a third one spawning a half-copied executable.
72
+ const temporary = `${to}.${String(process.pid)}.tmp`;
73
+ try {
74
+ // Read and write, not `copyFile`: the source is usually inside a compiled
75
+ // binary's virtual filesystem, where `copyFile` fails with ENOENT.
76
+ await writeFile(temporary, await readFile(from));
77
+ // 755, not 644: the unpacked copy has to be executable.
78
+ await chmod(temporary, 0o755).catch(() => undefined);
79
+ await rename(temporary, to);
80
+ } catch (error) {
81
+ await rm(temporary, { force: true }).catch(() => undefined);
82
+ // Lost a race rather than failed: the file is there, which is all we wanted.
83
+ if (!(await fileExists(to))) throw error;
84
+ }
85
+ }
86
+
87
+ async function fileExists(path: string): Promise<boolean> {
88
+ try {
89
+ return (await stat(path)).size > 0;
90
+ } catch {
91
+ return false;
92
+ }
93
+ }
94
+
95
+ export const defaultRipgrepDeps: RipgrepDeps = {
96
+ platform: process.platform,
97
+ exists: fileExists,
98
+ unpack: unpackDefault,
99
+ probe: async (path) => {
100
+ try {
101
+ const result = await runProcess({
102
+ command: path,
103
+ args: ["--version"],
104
+ cwd: ".",
105
+ timeoutMs: 5_000,
106
+ maxOutputBytes: 4_096,
107
+ });
108
+ return result.code === 0;
109
+ } catch {
110
+ return false;
111
+ }
112
+ },
113
+ };
114
+
115
+ /**
116
+ * Which ripgrep this process will use, without proving it runs. It spawns
117
+ * nothing; `checkRipgrep` adds the proof.
118
+ *
119
+ * Never returns `missing`: a copy that will not unpack falls through to PATH,
120
+ * and only a spawn shows whether PATH has one.
121
+ */
122
+ export async function resolveRipgrep(
123
+ options: RipgrepOptions = {},
124
+ deps: RipgrepDeps = defaultRipgrepDeps,
125
+ ): Promise<RipgrepLocation> {
126
+ if (options.configured !== undefined) {
127
+ return { mode: "configured", path: options.configured };
128
+ }
129
+
130
+ const { bundled, cacheDir } = options;
131
+ if (bundled !== undefined && cacheDir !== undefined) {
132
+ const target = unpackedRipgrepPath(cacheDir, bundled.version, deps.platform);
133
+ try {
134
+ if (!(await deps.exists(target))) await deps.unpack(bundled.path, target);
135
+ return { mode: "bundled", path: target, version: bundled.version };
136
+ } catch {
137
+ // A copy that will not unpack falls through to `rg` on PATH.
138
+ }
139
+ }
140
+
141
+ return { mode: "path", path: RIPGREP_COMMAND };
142
+ }
143
+
144
+ /**
145
+ * The same resolution, then a probe of each candidate, for `doctor`.
146
+ * `tools.ripgrepPath` is still first. A candidate that fails to run is recorded
147
+ * and the next one tried; `missing` lists them in `tried`. A configured path is
148
+ * reported, never replaced by PATH, here or in the tool.
149
+ */
150
+ export async function checkRipgrep(
151
+ options: RipgrepOptions = {},
152
+ deps: RipgrepDeps = defaultRipgrepDeps,
153
+ ): Promise<RipgrepStatus> {
154
+ const tried: string[] = [];
155
+
156
+ const planned = await resolveRipgrep(options, deps);
157
+ if (await deps.probe(planned.path)) return planned;
158
+ tried.push(planned.path);
159
+
160
+ // Only the bundled copy has somewhere left to fall; a configured path is the
161
+ // user's explicit answer and PATH was already the last resort.
162
+ if (planned.mode === "bundled" && (await deps.probe(RIPGREP_COMMAND))) {
163
+ return { mode: "path", path: RIPGREP_COMMAND };
164
+ }
165
+ if (planned.mode === "bundled") tried.push(RIPGREP_COMMAND);
166
+
167
+ return { mode: "missing", tried };
168
+ }
169
+
170
+ /**
171
+ * Spawn errors that clear on their own, so they are retried. A freshly written
172
+ * executable is sometimes still held, by an antivirus or the descriptor that
173
+ * wrote it; without the retry, the first search after an upgrade can fail.
174
+ * A missing binary or a permission problem is a real answer and is not retried.
175
+ */
176
+ const TRANSIENT_SPAWN_CODES = new Set(["EAGAIN", "ETXTBSY", "EBUSY"]);
177
+ const SPAWN_ATTEMPTS = 3;
178
+ const RETRY_DELAY_MS = 50;
179
+
180
+ const sleep = (ms: number): Promise<void> => new Promise((done) => setTimeout(done, ms));
181
+
182
+ export async function withSpawnRetry<T>(
183
+ run: () => Promise<T>,
184
+ delayMs: number = RETRY_DELAY_MS,
185
+ ): Promise<T> {
186
+ for (let attempt = 1; ; attempt += 1) {
187
+ try {
188
+ return await run();
189
+ } catch (error) {
190
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
191
+ if (attempt >= SPAWN_ATTEMPTS || code === undefined || !TRANSIENT_SPAWN_CODES.has(code)) {
192
+ throw error;
193
+ }
194
+ await sleep(delayMs * attempt);
195
+ }
196
+ }
197
+ }
198
+
199
+ /** Human-readable one-liner, shared by `doctor` and any other front end. */
200
+ export function describeRipgrep(status: RipgrepStatus): string {
201
+ switch (status.mode) {
202
+ case "bundled":
203
+ return `bundled ${status.version} · ${status.path}`;
204
+ case "configured":
205
+ return `${status.path} (tools.ripgrepPath)`;
206
+ case "path":
207
+ return `${status.path} (from PATH)`;
208
+ default:
209
+ return `not found — tried ${status.tried.join(", ")}`;
210
+ }
211
+ }
@@ -0,0 +1,97 @@
1
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import { z } from "zod";
4
+ import { AgentError } from "../../errors";
5
+ import { defineTool } from "../define";
6
+ import { displayPath, resolveInWorkspace } from "../../paths";
7
+ import { lineEndingOf, withLineEnding } from "./line-endings";
8
+
9
+ /** Above this the old file is not read just to draw a diff of it. */
10
+ const DIFF_SOURCE_LIMIT = 1024 * 1024;
11
+
12
+ export const writeFileTool = defineTool({
13
+ name: "write_file",
14
+ description:
15
+ "Write a UTF-8 text file, replacing it if it exists and creating parent " +
16
+ "directories as needed. To change part of an existing file prefer " +
17
+ "edit_file, which cannot lose content you have not read.",
18
+ danger: "write",
19
+ inputSchema: z.object({
20
+ path: z.string().min(1).describe("Path to the file, relative to the workspace root."),
21
+ content: z.string().describe("Full contents of the file."),
22
+ }),
23
+ resources: (input) => ({ paths: [input.path] }),
24
+ // The path, never the content: this line goes to the screen and to the
25
+ // event stream.
26
+ describe: (input) => input.path,
27
+ preview: async (input, context) => {
28
+ const absolute = resolveInWorkspace(context, input.path, "write");
29
+ const previous = await previousOf(absolute);
30
+ if (previous.text === undefined) return undefined;
31
+ return {
32
+ path: displayPath(context.cwd, absolute),
33
+ before: previous.text,
34
+ after: contentFor(input.content, previous),
35
+ };
36
+ },
37
+ execute: async (input, context) => {
38
+ const absolute = resolveInWorkspace(context, input.path, "write");
39
+ const previous = await previousOf(absolute);
40
+ const content = contentFor(input.content, previous);
41
+
42
+ await mkdir(dirname(absolute), { recursive: true });
43
+ await writeFile(absolute, content, "utf8").catch((cause: unknown) => {
44
+ throw new AgentError("tool/failed", `Cannot write "${input.path}": ${reason(cause)}`, {
45
+ cause,
46
+ details: { path: input.path },
47
+ });
48
+ });
49
+
50
+ const path = displayPath(context.cwd, absolute);
51
+ if (previous.text !== undefined) {
52
+ context.showChange({ path, before: previous.text, after: content });
53
+ }
54
+ return { path, lines: countLines(content), created: !previous.existed };
55
+ },
56
+ describeResult: (output) => {
57
+ // Logs written before lines were counted carry `bytes`, and reading a field
58
+ // that is not there would print "undefined lines".
59
+ const size =
60
+ "lines" in output
61
+ ? `${String(output.lines)} ${output.lines === 1 ? "line" : "lines"}`
62
+ : `${String((output as { bytes?: unknown }).bytes)} bytes`;
63
+ return `${output.created ? "created" : "written"}, ${size}`;
64
+ },
65
+ });
66
+
67
+ /** The file as it was: absent, too big to be worth a diff, or its text. */
68
+ async function previousOf(path: string): Promise<{ existed: boolean; text?: string }> {
69
+ try {
70
+ const info = await stat(path);
71
+ if (!info.isFile() || info.size > DIFF_SOURCE_LIMIT) return { existed: true };
72
+ return { existed: true, text: await readFile(path, "utf8") };
73
+ } catch {
74
+ return { existed: false, text: "" };
75
+ }
76
+ }
77
+
78
+ /**
79
+ * A CRLF file stays CRLF when replaced: in LF every line would show up as
80
+ * changed. A new file is written as the model wrote it.
81
+ */
82
+ function contentFor(content: string, previous: { text?: string }): string {
83
+ return previous.text === undefined || previous.text === ""
84
+ ? content
85
+ : withLineEnding(content, lineEndingOf(previous.text));
86
+ }
87
+
88
+ /** The rule `read_file` counts by: a trailing newline ends a line, it does not start one. */
89
+ function countLines(text: string): number {
90
+ if (text === "") return 0;
91
+ const lines = text.split("\n").length;
92
+ return text.endsWith("\n") ? lines - 1 : lines;
93
+ }
94
+
95
+ function reason(cause: unknown): string {
96
+ return cause instanceof Error ? cause.message : String(cause);
97
+ }
@@ -0,0 +1,252 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+
7
+ /**
8
+ * A process tree that dies with one kill, on Windows. `taskkill /t` follows
9
+ * parent PIDs, and Git Bash's fork-and-exec breaks that chain, so `npm run dev`
10
+ * outlived its stop. A job object holds every descendant; Node cannot make one,
11
+ * so a C# helper does, compiled once by the compiler Windows ships with.
12
+ */
13
+
14
+ export type JobRunnerStatus = { mode: "on"; path: string } | { mode: "off"; reason: string };
15
+
16
+ /**
17
+ * What the helper says when the command never started, with exit code 127.
18
+ * Not an exit code alone: a runtime may keep only its low 8 bits.
19
+ */
20
+ export const JOB_CANNOT_START = /^job-run: cannot start: error (\d+)\n?$/;
21
+
22
+ // Takes the host's PID and the quoted command line. Leaving closes the job, so
23
+ // whatever the command left running dies with it, and so does all of it when the host does.
24
+ const SOURCE = String.raw`using System;
25
+ using System.Runtime.InteropServices;
26
+ using System.Text;
27
+
28
+ static class JobRun {
29
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
30
+ struct STARTUPINFO {
31
+ public int cb; public string lpReserved, lpDesktop, lpTitle;
32
+ public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;
33
+ public short wShowWindow, cbReserved2; public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
34
+ }
35
+ [StructLayout(LayoutKind.Sequential)]
36
+ struct PROCESS_INFORMATION { public IntPtr hProcess, hThread; public int dwProcessId, dwThreadId; }
37
+ [StructLayout(LayoutKind.Sequential)]
38
+ struct BASIC_LIMITS {
39
+ public long PerProcessUserTimeLimit, PerJobUserTimeLimit; public uint LimitFlags;
40
+ public UIntPtr MinimumWorkingSetSize, MaximumWorkingSetSize; public uint ActiveProcessLimit;
41
+ public UIntPtr Affinity; public uint PriorityClass, SchedulingClass;
42
+ }
43
+ [StructLayout(LayoutKind.Sequential)]
44
+ struct IO_COUNTERS { public ulong a, b, c, d, e, f; }
45
+ [StructLayout(LayoutKind.Sequential)]
46
+ struct EXTENDED_LIMITS {
47
+ public BASIC_LIMITS Basic; public IO_COUNTERS Io;
48
+ public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed;
49
+ }
50
+
51
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
52
+ static extern IntPtr CreateJobObject(IntPtr attributes, string name);
53
+ [DllImport("kernel32.dll", SetLastError = true)]
54
+ static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref EXTENDED_LIMITS info, int length);
55
+ [DllImport("kernel32.dll", SetLastError = true)]
56
+ static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
57
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
58
+ static extern bool CreateProcess(string app, StringBuilder commandLine, IntPtr pa, IntPtr ta, bool inherit,
59
+ uint flags, IntPtr env, string cwd, ref STARTUPINFO si, out PROCESS_INFORMATION pi);
60
+ [DllImport("kernel32.dll")] static extern uint ResumeThread(IntPtr thread);
61
+ [DllImport("kernel32.dll")] static extern bool TerminateProcess(IntPtr process, uint code);
62
+ [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
63
+ [DllImport("kernel32.dll")] static extern uint WaitForMultipleObjects(uint count, IntPtr[] handles, bool all, uint ms);
64
+ [DllImport("kernel32.dll")] static extern bool GetExitCodeProcess(IntPtr process, out uint code);
65
+ [DllImport("kernel32.dll")] static extern IntPtr GetStdHandle(int which);
66
+
67
+ const uint KILL_ON_JOB_CLOSE = 0x2000, CREATE_SUSPENDED = 0x4, CREATE_BREAKAWAY_FROM_JOB = 0x01000000;
68
+ const uint SYNCHRONIZE = 0x00100000, INFINITE = 0xFFFFFFFF;
69
+
70
+ static bool Start(string line, uint flags, ref STARTUPINFO si, out PROCESS_INFORMATION pi) {
71
+ return CreateProcess(null, new StringBuilder(line), IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, null, ref si, out pi);
72
+ }
73
+
74
+ static int CannotStart(int error) {
75
+ Console.Error.Write("job-run: cannot start: error " + error + "\n");
76
+ return 127;
77
+ }
78
+
79
+ static int Main(string[] args) {
80
+ if (args.Length != 2) return CannotStart(87);
81
+ IntPtr job = CreateJobObject(IntPtr.Zero, null);
82
+ EXTENDED_LIMITS limits = new EXTENDED_LIMITS();
83
+ limits.Basic.LimitFlags = KILL_ON_JOB_CLOSE;
84
+ if (job == IntPtr.Zero || !SetInformationJobObject(job, 9, ref limits, Marshal.SizeOf(limits))) {
85
+ return CannotStart(Marshal.GetLastWin32Error());
86
+ }
87
+
88
+ STARTUPINFO si = new STARTUPINFO();
89
+ si.cb = Marshal.SizeOf(si);
90
+ si.dwFlags = 0x100;
91
+ si.hStdInput = GetStdHandle(-10); si.hStdOutput = GetStdHandle(-11); si.hStdError = GetStdHandle(-12);
92
+ PROCESS_INFORMATION pi;
93
+ // Out of the runtime's own job where it allows that; nested inside it where it does not.
94
+ if (!Start(args[1], CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB, ref si, out pi)
95
+ && (Marshal.GetLastWin32Error() != 5 || !Start(args[1], CREATE_SUSPENDED, ref si, out pi))) {
96
+ return CannotStart(Marshal.GetLastWin32Error());
97
+ }
98
+ if (!AssignProcessToJobObject(job, pi.hProcess)) {
99
+ int error = Marshal.GetLastWin32Error();
100
+ TerminateProcess(pi.hProcess, 1);
101
+ return CannotStart(error);
102
+ }
103
+ ResumeThread(pi.hThread);
104
+
105
+ IntPtr host = OpenProcess(SYNCHRONIZE, false, int.Parse(args[0]));
106
+ IntPtr[] waits = host == IntPtr.Zero ? new IntPtr[] { pi.hProcess } : new IntPtr[] { pi.hProcess, host };
107
+ if (WaitForMultipleObjects((uint)waits.Length, waits, false, INFINITE) != 0) return 1;
108
+ uint code;
109
+ GetExitCodeProcess(pi.hProcess, out code);
110
+ return (int)code;
111
+ }
112
+ }
113
+ `;
114
+
115
+ const NAME = `job-run-${createHash("sha256").update(SOURCE).digest("hex").slice(0, 12)}`;
116
+
117
+ /** Quoted the way libuv quotes, so a command arrives exactly as it would without the helper. */
118
+ export function quoteWindowsArg(arg: string): string {
119
+ if (arg === "") return '""';
120
+ if (!/[ \t"]/.test(arg)) return arg;
121
+ let quoted = '"';
122
+ let slashes = 0;
123
+ for (const char of arg) {
124
+ if (char === "\\") {
125
+ slashes += 1;
126
+ continue;
127
+ }
128
+ // Backslashes count only in front of a quote: doubled there, the quote escaped.
129
+ quoted += char === '"' ? `${"\\".repeat(slashes * 2 + 1)}"` : `${"\\".repeat(slashes)}${char}`;
130
+ slashes = 0;
131
+ }
132
+ return `${quoted}${"\\".repeat(slashes * 2)}"`;
133
+ }
134
+
135
+ export function windowsCommandLine(command: string, args: readonly string[]): string {
136
+ return [command, ...args].map(quoteWindowsArg).join(" ");
137
+ }
138
+
139
+ export interface JobRunnerDeps {
140
+ platform: string;
141
+ /** The C# compiler that ships with Windows, or nothing where there is none. */
142
+ findCompiler: () => Promise<string | undefined>;
143
+ /** Compiles `source` into `out`; the compiler's complaint when it fails. */
144
+ compile: (compiler: string, source: string, out: string) => Promise<string | undefined>;
145
+ /** Runs one command through the helper; false when it cannot run at all. */
146
+ probe: (helper: string) => Promise<boolean>;
147
+ }
148
+
149
+ function exec(command: string, args: readonly string[]): Promise<{ code: number | null; output: string }> {
150
+ return new Promise((resolve) => {
151
+ const child = spawn(command, [...args], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
152
+ let output = "";
153
+ child.stdout?.on("data", (chunk: Buffer) => (output += chunk.toString()));
154
+ child.stderr?.on("data", (chunk: Buffer) => (output += chunk.toString()));
155
+ child.on("error", () => resolve({ code: null, output }));
156
+ child.on("close", (code) => resolve({ code, output }));
157
+ });
158
+ }
159
+
160
+ const NET_FRAMEWORK_KEY = "HKLM\\SOFTWARE\\Microsoft\\.NETFramework";
161
+
162
+ /** Asked of the registry rather than of `SystemRoot`: the core reads no environment. */
163
+ async function findCompiler(): Promise<string | undefined> {
164
+ const { output } = await exec("reg", ["query", NET_FRAMEWORK_KEY, "/v", "InstallRoot"]);
165
+ const root = /InstallRoot\s+REG_SZ\s+(.+)/.exec(output)?.[1]?.trim();
166
+ if (root === undefined) return undefined;
167
+ const compiler = join(root, "v4.0.30319", "csc.exe");
168
+ return existsSync(compiler) ? compiler : undefined;
169
+ }
170
+
171
+ async function compile(compiler: string, source: string, out: string): Promise<string | undefined> {
172
+ const file = `${out}.cs`;
173
+ writeFileSync(file, source);
174
+ try {
175
+ const { code, output } = await exec(compiler, ["/nologo", "/optimize", `/out:${out}`, file]);
176
+ return code === 0 ? undefined : output.trim().split("\n")[0] ?? `exit ${String(code)}`;
177
+ } finally {
178
+ rmSync(file, { force: true });
179
+ }
180
+ }
181
+
182
+ /** One run through the helper: a file a policy or a scanner blocks fails here, not in a tool call. */
183
+ async function probe(helper: string): Promise<boolean> {
184
+ const line = windowsCommandLine("reg", ["query", NET_FRAMEWORK_KEY, "/v", "InstallRoot"]);
185
+ const { code } = await exec(helper, [String(process.pid), line]);
186
+ return code === 0;
187
+ }
188
+
189
+ const defaultDeps: JobRunnerDeps = { platform: process.platform, findCompiler, compile, probe };
190
+
191
+ const runners = new Map<string, Promise<JobRunnerStatus>>();
192
+
193
+ /**
194
+ * The helper, or why there is none. Compiled into `bin/` under `cacheDir` once,
195
+ * then looked up once per process; absent `cacheDir`, a directory in temp.
196
+ */
197
+ export function jobRunner(cacheDir?: string, deps: JobRunnerDeps = defaultDeps): Promise<JobRunnerStatus> {
198
+ const dir = cacheDir === undefined ? join(tmpdir(), "job-run") : join(cacheDir, "bin");
199
+ if (deps !== defaultDeps) return prepare(dir, deps).catch(asOff);
200
+ let runner = runners.get(dir);
201
+ if (runner === undefined) {
202
+ runner = prepare(dir, deps).catch(asOff);
203
+ runners.set(dir, runner);
204
+ }
205
+ return runner;
206
+ }
207
+
208
+ function asOff(error: unknown): JobRunnerStatus {
209
+ return { mode: "off", reason: error instanceof Error ? error.message : String(error) };
210
+ }
211
+
212
+ async function prepare(dir: string, deps: JobRunnerDeps): Promise<JobRunnerStatus> {
213
+ if (deps.platform !== "win32") return { mode: "off", reason: "only Windows needs it" };
214
+
215
+ const helper = join(dir, `${NAME}.exe`);
216
+ if (!existsSync(helper)) {
217
+ const compiler = await deps.findCompiler();
218
+ if (compiler === undefined) return { mode: "off", reason: "no C# compiler (.NET Framework 4) on this machine" };
219
+
220
+ mkdirSync(dir, { recursive: true });
221
+ // Built aside and moved into place: a second process must not run a half-written file.
222
+ const aside = join(dir, `${NAME}-${String(process.pid)}.exe`);
223
+ const failed = await deps.compile(compiler, SOURCE, aside);
224
+ if (failed !== undefined) return { mode: "off", reason: `the C# compiler failed: ${failed}` };
225
+ try {
226
+ renameSync(aside, helper);
227
+ } catch {
228
+ // Another process got there first, with the same source.
229
+ rmSync(aside, { force: true });
230
+ }
231
+ for (const old of readdirSync(dir)) {
232
+ // Other versions only: a name with ours in it may be another process's build in progress.
233
+ if (!old.startsWith("job-run-") || old.startsWith(NAME)) continue;
234
+ try {
235
+ rmSync(join(dir, old));
236
+ } catch {
237
+ // Still running somewhere; the next version's build tries again.
238
+ }
239
+ }
240
+ }
241
+
242
+ if (!(await deps.probe(helper))) {
243
+ return { mode: "off", reason: `${helper} does not run here (blocked by a policy or a scanner?)` };
244
+ }
245
+ return { mode: "on", path: helper };
246
+ }
247
+
248
+ export function describeJobRunner(status: JobRunnerStatus): string {
249
+ return status.mode === "on"
250
+ ? `job object (${status.path})`
251
+ : `taskkill only — ${status.reason}; a stopped command may leave processes behind`;
252
+ }
@@ -0,0 +1,127 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, rm } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import type { StoredOAuthClientInformation, StoredOAuthTokens } from "@modelcontextprotocol/client";
5
+ import { readTextFile, withFileLock, writeFileAtomically } from "../../config/locked-file";
6
+ import { AgentError } from "../../errors";
7
+
8
+ /**
9
+ * Where MCP sign-ins live, supplied by the host and keyed by the server's name
10
+ * and URL: two names for one URL are two accounts, and a URL that changed is
11
+ * another server.
12
+ */
13
+
14
+ export interface McpAuthEntry {
15
+ /** The client the server registered for us; absent when the config names one. */
16
+ client?: StoredOAuthClientInformation;
17
+ tokens?: StoredOAuthTokens;
18
+ }
19
+
20
+ /**
21
+ * `modify` is the only write path and runs one at a time per server, across
22
+ * processes too where the store can manage it: a refresh token works once, and
23
+ * two refreshes of the same one can cost the sign-in.
24
+ */
25
+ export interface McpAuthStore {
26
+ read(server: string, url: string): Promise<McpAuthEntry | undefined>;
27
+ /** `fn` sees what is stored once the lock is held; returning undefined writes nothing. */
28
+ modify(
29
+ server: string,
30
+ url: string,
31
+ fn: (current: McpAuthEntry | undefined) => Promise<McpAuthEntry | undefined>,
32
+ ): Promise<McpAuthEntry | undefined>;
33
+ delete(server: string, url: string): Promise<void>;
34
+ }
35
+
36
+ /** For tests and for a host with one process and nowhere to keep files. */
37
+ export function memoryMcpAuthStore(): McpAuthStore {
38
+ const entries = new Map<string, McpAuthEntry>();
39
+ const queues = new Map<string, Promise<unknown>>();
40
+ const keyOf = (server: string, url: string): string => `${server}\n${url}`;
41
+
42
+ function queued<T>(key: string, task: () => Promise<T>): Promise<T> {
43
+ const run = (queues.get(key) ?? Promise.resolve()).then(task);
44
+ queues.set(
45
+ key,
46
+ run.catch(() => undefined),
47
+ );
48
+ return run;
49
+ }
50
+
51
+ return {
52
+ read: async (server, url) => entries.get(keyOf(server, url)),
53
+ modify: (server, url, fn) =>
54
+ queued(keyOf(server, url), async () => {
55
+ const current = entries.get(keyOf(server, url));
56
+ const next = await fn(current);
57
+ if (next === undefined) return current;
58
+ entries.set(keyOf(server, url), next);
59
+ return next;
60
+ }),
61
+ delete: (server, url) =>
62
+ queued(keyOf(server, url), async () => {
63
+ entries.delete(keyOf(server, url));
64
+ }),
65
+ };
66
+ }
67
+
68
+ interface StoredFile extends McpAuthEntry {
69
+ url: string;
70
+ }
71
+
72
+ function parseEntry(text: string | undefined, url: string): McpAuthEntry | undefined {
73
+ if (text === undefined) return undefined;
74
+ try {
75
+ const value = JSON.parse(text) as Partial<StoredFile> | null;
76
+ // Another URL under the same name and hash is not this server's sign-in.
77
+ if (value === null || typeof value !== "object" || value.url !== url) return undefined;
78
+ return {
79
+ ...(value.client === undefined ? {} : { client: value.client }),
80
+ ...(value.tokens === undefined ? {} : { tokens: value.tokens }),
81
+ };
82
+ } catch {
83
+ // Unreadable is the same as absent: the answer is to sign in again.
84
+ return undefined;
85
+ }
86
+ }
87
+
88
+ /** One file per server, `<name>-<hash of the URL>.json`, written under a lock file. */
89
+ export function fileMcpAuthStore(dir: string): McpAuthStore {
90
+ const fileFor = (server: string, url: string): string => {
91
+ // Names come from config; one with a separator must not pick its own path.
92
+ if (!/^[A-Za-z0-9_-]+$/.test(server)) {
93
+ throw new AgentError("config/invalid", `"${server}" cannot be used as a file name.`, { details: { server } });
94
+ }
95
+ const hash = createHash("sha256").update(url).digest("hex").slice(0, 12);
96
+ return join(dir, `${server}-${hash}.json`);
97
+ };
98
+ const locked = async <T>(server: string, url: string, work: (file: string) => Promise<T>): Promise<T> => {
99
+ const file = fileFor(server, url);
100
+ await mkdir(dir, { recursive: true, mode: 0o700 });
101
+ return withFileLock(
102
+ `${file}.lock`,
103
+ () => work(file),
104
+ () =>
105
+ new AgentError("mcp/sign-in-failed", `Timed out waiting for ${file}.lock. Delete it if no other process is running.`, {
106
+ details: { server },
107
+ }),
108
+ );
109
+ };
110
+
111
+ return {
112
+ read: async (server, url) => parseEntry(await readTextFile(fileFor(server, url)), url),
113
+
114
+ modify: (server, url, fn) =>
115
+ locked(server, url, async (file) => {
116
+ // Read under the lock: the copy from before waiting may already be spent.
117
+ const current = parseEntry(await readTextFile(file), url);
118
+ const next = await fn(current);
119
+ if (next === undefined) return current;
120
+ const stored: StoredFile = { url, ...next };
121
+ await writeFileAtomically(file, `${JSON.stringify(stored, null, 2)}\n`);
122
+ return next;
123
+ }),
124
+
125
+ delete: (server, url) => locked(server, url, (file) => rm(file, { force: true })),
126
+ };
127
+ }