@martinloop/mcp 0.3.8 → 0.3.9

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 (103) hide show
  1. package/README.md +148 -105
  2. package/dist/resources.js +148 -148
  3. package/dist/server.js +0 -0
  4. package/dist/tools/preflight.d.ts +0 -2
  5. package/dist/tools/preflight.js +2 -42
  6. package/dist/vendor/adapters/openai-compatible.js +6 -6
  7. package/dist/vendor/contracts/index.d.ts +0 -2
  8. package/dist/vendor/contracts/index.js +0 -2
  9. package/dist/vendor/core/index.d.ts +0 -2
  10. package/dist/vendor/core/index.js +0 -2
  11. package/package.json +86 -83
  12. package/server.json +21 -21
  13. package/LICENSE +0 -216
  14. package/dist/vendor/adapters/adapters/src/claude-cli.d.ts +0 -146
  15. package/dist/vendor/adapters/adapters/src/claude-cli.js +0 -1100
  16. package/dist/vendor/adapters/adapters/src/cli-bridge.d.ts +0 -103
  17. package/dist/vendor/adapters/adapters/src/cli-bridge.js +0 -569
  18. package/dist/vendor/adapters/adapters/src/codex-launcher.d.ts +0 -78
  19. package/dist/vendor/adapters/adapters/src/codex-launcher.js +0 -663
  20. package/dist/vendor/adapters/adapters/src/direct-provider.d.ts +0 -10
  21. package/dist/vendor/adapters/adapters/src/direct-provider.js +0 -40
  22. package/dist/vendor/adapters/adapters/src/index.d.ts +0 -8
  23. package/dist/vendor/adapters/adapters/src/index.js +0 -8
  24. package/dist/vendor/adapters/adapters/src/openai-compatible.d.ts +0 -62
  25. package/dist/vendor/adapters/adapters/src/openai-compatible.js +0 -306
  26. package/dist/vendor/adapters/adapters/src/runtime-support.d.ts +0 -17
  27. package/dist/vendor/adapters/adapters/src/runtime-support.js +0 -59
  28. package/dist/vendor/adapters/adapters/src/stub-agent-cli.d.ts +0 -8
  29. package/dist/vendor/adapters/adapters/src/stub-agent-cli.js +0 -40
  30. package/dist/vendor/adapters/adapters/src/stub-direct-provider.d.ts +0 -8
  31. package/dist/vendor/adapters/adapters/src/stub-direct-provider.js +0 -12
  32. package/dist/vendor/adapters/adapters/src/verifier-only.d.ts +0 -9
  33. package/dist/vendor/adapters/adapters/src/verifier-only.js +0 -63
  34. package/dist/vendor/adapters/contracts/src/context-graph.d.ts +0 -48
  35. package/dist/vendor/adapters/contracts/src/context-graph.js +0 -26
  36. package/dist/vendor/adapters/contracts/src/execution-policy.d.ts +0 -78
  37. package/dist/vendor/adapters/contracts/src/execution-policy.js +0 -43
  38. package/dist/vendor/adapters/contracts/src/governance.d.ts +0 -24
  39. package/dist/vendor/adapters/contracts/src/governance.js +0 -11
  40. package/dist/vendor/adapters/contracts/src/identity.d.ts +0 -29
  41. package/dist/vendor/adapters/contracts/src/identity.js +0 -30
  42. package/dist/vendor/adapters/contracts/src/index.d.ts +0 -412
  43. package/dist/vendor/adapters/contracts/src/index.js +0 -225
  44. package/dist/vendor/adapters/contracts/src/operator.d.ts +0 -19
  45. package/dist/vendor/adapters/contracts/src/operator.js +0 -11
  46. package/dist/vendor/adapters/contracts/src/trajectory.d.ts +0 -26
  47. package/dist/vendor/adapters/contracts/src/trajectory.js +0 -27
  48. package/dist/vendor/adapters/core/src/compiler.d.ts +0 -52
  49. package/dist/vendor/adapters/core/src/compiler.js +0 -52
  50. package/dist/vendor/adapters/core/src/context-graph.d.ts +0 -3
  51. package/dist/vendor/adapters/core/src/context-graph.js +0 -371
  52. package/dist/vendor/adapters/core/src/context-integrity.d.ts +0 -26
  53. package/dist/vendor/adapters/core/src/context-integrity.js +0 -80
  54. package/dist/vendor/adapters/core/src/grounding.d.ts +0 -38
  55. package/dist/vendor/adapters/core/src/grounding.js +0 -273
  56. package/dist/vendor/adapters/core/src/identity.d.ts +0 -20
  57. package/dist/vendor/adapters/core/src/identity.js +0 -86
  58. package/dist/vendor/adapters/core/src/index.d.ts +0 -186
  59. package/dist/vendor/adapters/core/src/index.js +0 -1495
  60. package/dist/vendor/adapters/core/src/leash.d.ts +0 -48
  61. package/dist/vendor/adapters/core/src/leash.js +0 -497
  62. package/dist/vendor/adapters/core/src/persistence/compiler.d.ts +0 -18
  63. package/dist/vendor/adapters/core/src/persistence/compiler.js +0 -34
  64. package/dist/vendor/adapters/core/src/persistence/index.d.ts +0 -10
  65. package/dist/vendor/adapters/core/src/persistence/index.js +0 -5
  66. package/dist/vendor/adapters/core/src/persistence/integrity.d.ts +0 -39
  67. package/dist/vendor/adapters/core/src/persistence/integrity.js +0 -252
  68. package/dist/vendor/adapters/core/src/persistence/ledger.d.ts +0 -23
  69. package/dist/vendor/adapters/core/src/persistence/ledger.js +0 -9
  70. package/dist/vendor/adapters/core/src/persistence/memory-store.d.ts +0 -63
  71. package/dist/vendor/adapters/core/src/persistence/memory-store.js +0 -115
  72. package/dist/vendor/adapters/core/src/persistence/runs-reader.d.ts +0 -66
  73. package/dist/vendor/adapters/core/src/persistence/runs-reader.js +0 -140
  74. package/dist/vendor/adapters/core/src/persistence/store.d.ts +0 -89
  75. package/dist/vendor/adapters/core/src/persistence/store.js +0 -125
  76. package/dist/vendor/adapters/core/src/persistence/trace-store.d.ts +0 -85
  77. package/dist/vendor/adapters/core/src/persistence/trace-store.js +0 -125
  78. package/dist/vendor/adapters/core/src/policy-compiler.d.ts +0 -2
  79. package/dist/vendor/adapters/core/src/policy-compiler.js +0 -195
  80. package/dist/vendor/adapters/core/src/policy.d.ts +0 -156
  81. package/dist/vendor/adapters/core/src/policy.js +0 -704
  82. package/dist/vendor/adapters/core/src/repo-analyzer.d.ts +0 -53
  83. package/dist/vendor/adapters/core/src/repo-analyzer.js +0 -263
  84. package/dist/vendor/adapters/core/src/rollback.d.ts +0 -15
  85. package/dist/vendor/adapters/core/src/rollback.js +0 -253
  86. package/dist/vendor/adapters/core/src/routing.d.ts +0 -82
  87. package/dist/vendor/adapters/core/src/routing.js +0 -336
  88. package/dist/vendor/adapters/core/src/test-integrity.d.ts +0 -64
  89. package/dist/vendor/adapters/core/src/test-integrity.js +0 -197
  90. package/dist/vendor/adapters/core/src/trajectory.d.ts +0 -18
  91. package/dist/vendor/adapters/core/src/trajectory.js +0 -295
  92. package/dist/vendor/contracts/delivery.d.ts +0 -47
  93. package/dist/vendor/contracts/delivery.js +0 -18
  94. package/dist/vendor/core/delivery/index.d.ts +0 -6
  95. package/dist/vendor/core/delivery/index.js +0 -4
  96. package/dist/vendor/core/delivery/message-client.d.ts +0 -18
  97. package/dist/vendor/core/delivery/message-client.js +0 -38
  98. package/dist/vendor/core/delivery/message-ledger.d.ts +0 -35
  99. package/dist/vendor/core/delivery/message-ledger.js +0 -97
  100. package/dist/vendor/core/delivery/message-schema.d.ts +0 -16
  101. package/dist/vendor/core/delivery/message-schema.js +0 -111
  102. package/dist/vendor/core/delivery/update-check.d.ts +0 -19
  103. package/dist/vendor/core/delivery/update-check.js +0 -107
@@ -1,663 +0,0 @@
1
- import { spawnSync } from "node:child_process";
2
- import { existsSync, readdirSync, statSync } from "node:fs";
3
- import { dirname, extname, join, resolve } from "node:path";
4
- import { resolveNpmShimScript } from "./cli-bridge.js";
5
- const codexLaunchProbeCache = new Map();
6
- export const DEFAULT_CODEX_CHATGPT_MODEL = "gpt-5.4";
7
- const CODEX_LAUNCH_PROBE_PROMPT = [
8
- "You are validating MartinLoop Codex host readiness.",
9
- "Do not edit files.",
10
- "Use the shell command executor exactly once to run: git status --short -- .",
11
- "Do not use MCP tools, Node REPL, or any fallback tool if shell execution fails.",
12
- "If the shell command succeeds, reply with READY only.",
13
- "If it fails, reply with the exact failure in one sentence."
14
- ].join("\n");
15
- function buildProbeCacheKey(input) {
16
- return JSON.stringify({
17
- workingDirectory: resolve(input.workingDirectory),
18
- platform: input.platform,
19
- candidatePaths: input.candidatePaths,
20
- model: input.model ?? DEFAULT_CODEX_CHATGPT_MODEL
21
- });
22
- }
23
- function isInsideGitRepository(workingDirectory) {
24
- let current = resolve(workingDirectory);
25
- while (true) {
26
- if (existsSync(resolve(current, ".git"))) {
27
- return true;
28
- }
29
- const parent = dirname(current);
30
- if (parent === current) {
31
- return false;
32
- }
33
- current = parent;
34
- }
35
- }
36
- function normalizeCandidates(lines) {
37
- return [...new Set(lines.map((line) => line.trim()).filter(Boolean))];
38
- }
39
- function readLocatorCandidates(command, platform, spawnSyncImpl) {
40
- const locator = platform === "win32" ? "where.exe" : "which";
41
- const result = spawnSyncImpl(locator, [command], {
42
- encoding: "utf8",
43
- stdio: ["ignore", "pipe", "pipe"]
44
- });
45
- return {
46
- locator,
47
- candidates: result.status === 0
48
- ? normalizeCandidates((result.stdout ?? "").split(/\r?\n/u))
49
- : [],
50
- foundOnPath: result.status === 0
51
- };
52
- }
53
- function discoverWindowsDesktopCodexCandidates(env) {
54
- const localAppData = env["LOCALAPPDATA"];
55
- if (!localAppData) {
56
- return [];
57
- }
58
- const baseDirectory = join(localAppData, "OpenAI", "Codex", "bin");
59
- if (!existsSync(baseDirectory)) {
60
- return [];
61
- }
62
- const candidates = [];
63
- const directCandidate = join(baseDirectory, "codex.exe");
64
- if (existsSync(directCandidate)) {
65
- candidates.push({ path: directCandidate, mtimeMs: statSync(directCandidate).mtimeMs });
66
- }
67
- for (const entry of readdirSync(baseDirectory, { withFileTypes: true })) {
68
- if (!entry.isDirectory()) {
69
- continue;
70
- }
71
- const candidate = join(baseDirectory, entry.name, "codex.exe");
72
- if (!existsSync(candidate)) {
73
- continue;
74
- }
75
- candidates.push({ path: candidate, mtimeMs: statSync(candidate).mtimeMs });
76
- }
77
- candidates.sort((left, right) => right.mtimeMs - left.mtimeMs);
78
- return normalizeCandidates(candidates.map((candidate) => candidate.path));
79
- }
80
- function codexProbePreference(diagnosis) {
81
- if (diagnosis.installKind === "native" && diagnosis.invocationMode === "direct") {
82
- return 0;
83
- }
84
- if (diagnosis.installKind === "native") {
85
- return 1;
86
- }
87
- if (diagnosis.installKind === "windows_shim") {
88
- return 2;
89
- }
90
- return 3;
91
- }
92
- function buildProbeCandidates(input) {
93
- const pathCandidates = normalizeCandidates(input.availability.candidatePaths ?? [input.availability.resolvedPath ?? input.availability.command]);
94
- const desktopCandidates = input.platform === "win32" && input.includeDesktopCandidates
95
- ? discoverWindowsDesktopCodexCandidates(input.env).filter((candidatePath) => !pathCandidates.includes(candidatePath))
96
- : [];
97
- return [...pathCandidates, ...desktopCandidates]
98
- .map((path, discoveryIndex) => {
99
- const diagnosis = diagnoseCodexHost({
100
- ...input.availability,
101
- resolvedPath: path
102
- }, {
103
- env: input.env,
104
- platform: input.platform
105
- });
106
- return {
107
- path,
108
- diagnosis,
109
- preference: input.platform === "win32" ? codexProbePreference(diagnosis) : 0,
110
- discoveryIndex
111
- };
112
- })
113
- .sort((left, right) => left.preference === right.preference
114
- ? left.discoveryIndex - right.discoveryIndex
115
- : left.preference - right.preference);
116
- }
117
- function buildProbeCommand(command, args, platform) {
118
- if (platform !== "win32") {
119
- return { command, args, invocationMode: "direct" };
120
- }
121
- const extension = extname(command).toLowerCase();
122
- switch (extension) {
123
- case ".cmd":
124
- case ".bat":
125
- case ".ps1": {
126
- // Bypass the npm shim's cmd.exe/powershell.exe wrapper hop when we can statically resolve
127
- // the real `node <script>` target it wraps — keeps the live probe's process-nesting depth
128
- // consistent with the real run's invocation (see createSpawnPlan in cli-bridge.ts).
129
- const directScript = resolveNpmShimScript(command);
130
- if (directScript !== undefined) {
131
- return { command: process.execPath, args: [directScript, ...args], invocationMode: "direct" };
132
- }
133
- if (extension === ".ps1") {
134
- return {
135
- command: "powershell.exe",
136
- args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", command, ...args],
137
- invocationMode: "powershell"
138
- };
139
- }
140
- return {
141
- command: process.env.ComSpec || "cmd.exe",
142
- args: ["/d", "/c", command, ...args],
143
- invocationMode: "cmd_shell"
144
- };
145
- }
146
- default:
147
- return { command, args, invocationMode: "direct" };
148
- }
149
- }
150
- function detectInstallKind(resolvedPath, hostPlatform) {
151
- if (!resolvedPath) {
152
- return "missing";
153
- }
154
- const normalizedPath = resolvedPath.replace(/\\/gu, "/").toLowerCase();
155
- const looksWindowsShim = normalizedPath.endsWith(".cmd") ||
156
- normalizedPath.endsWith(".bat") ||
157
- normalizedPath.endsWith(".ps1") ||
158
- normalizedPath.includes("/appdata/roaming/npm/");
159
- const looksMountedWindowsPath = normalizedPath.startsWith("/mnt/c/");
160
- if ((hostPlatform === "linux" || hostPlatform === "wsl") && looksMountedWindowsPath) {
161
- return "windows_mounted_path";
162
- }
163
- if (looksWindowsShim) {
164
- return "windows_shim";
165
- }
166
- return "native";
167
- }
168
- function detectInvocationMode(resolvedPath, platform) {
169
- if (platform !== "win32" || !resolvedPath) {
170
- return "direct";
171
- }
172
- const extension = extname(resolvedPath).toLowerCase();
173
- if (extension === ".ps1") {
174
- return "powershell";
175
- }
176
- if (extension === ".cmd" || extension === ".bat") {
177
- return "cmd_shell";
178
- }
179
- return "direct";
180
- }
181
- function classifyProbeFailure(stderr, stdout, diagnosis) {
182
- const combined = `${stderr}\n${stdout}`;
183
- if (/MARTIN_REMOTE_TOKEN/iu.test(combined) ||
184
- /AuthRequired\(AuthRequiredError/iu.test(combined) ||
185
- /www_authenticate_header/iu.test(combined)) {
186
- const warnings = [...diagnosis.warnings];
187
- const configCollisionWarning = "Codex inherited auth-sensitive MCP or plugin state from the operator's default user config.";
188
- if (!warnings.includes(configCollisionWarning)) {
189
- warnings.push(configCollisionWarning);
190
- }
191
- return {
192
- summary: "Codex inherited auth-sensitive MCP or plugin state from the operator's default user config. Governed Codex runs should launch with `exec --ignore-user-config` so missing remote tokens or third-party auth do not abort MartinLoop work.",
193
- diagnosis: {
194
- ...diagnosis,
195
- warnings,
196
- remediation: "Retry the governed Codex launch with `exec --ignore-user-config`, or remove auth-sensitive MCP/plugin dependencies from the default Codex user config before running MartinLoop."
197
- }
198
- };
199
- }
200
- if (/not supported when using Codex with a ChatGPT account/iu.test(combined) ||
201
- /gpt-5\.3-codex/iu.test(combined)) {
202
- const warnings = [...diagnosis.warnings];
203
- const unsupportedModelWarning = "Codex tried to use a model that is not supported for ChatGPT-account authentication.";
204
- if (!warnings.includes(unsupportedModelWarning)) {
205
- warnings.push(unsupportedModelWarning);
206
- }
207
- return {
208
- summary: `Codex launched with a model that is not supported for ChatGPT-account authentication. Use an explicit supported model such as \`${DEFAULT_CODEX_CHATGPT_MODEL}\` for governed Codex work.`,
209
- diagnosis: {
210
- ...diagnosis,
211
- warnings,
212
- remediation: `Override the Codex launch model to a ChatGPT-account-supported option such as \`${DEFAULT_CODEX_CHATGPT_MODEL}\` before running governed Codex work.`
213
- }
214
- };
215
- }
216
- if (/@openai\/codex-linux-x64/iu.test(combined) ||
217
- /cannot find module ['"]@openai\/codex-linux-x64['"]/iu.test(combined)) {
218
- const warnings = [...diagnosis.warnings];
219
- const missingDependencyWarning = "Codex is missing the native Linux package '@openai/codex-linux-x64' required for this host.";
220
- if (!warnings.includes(missingDependencyWarning)) {
221
- warnings.push(missingDependencyWarning);
222
- }
223
- return {
224
- summary: "Codex native dependency '@openai/codex-linux-x64' is missing for this Linux/WSL environment.",
225
- diagnosis: {
226
- ...diagnosis,
227
- nativeInstallValid: false,
228
- sandboxCompatible: false,
229
- warnings,
230
- nativeDependencyStatus: "missing",
231
- nativeDependencyPackage: "@openai/codex-linux-x64",
232
- remediation: "Reinstall Codex natively inside this Linux/WSL environment so the '@openai/codex-linux-x64' package is present before running governed Codex work."
233
- }
234
- };
235
- }
236
- if (/CreateProcessAsUserW failed:\s*5/iu.test(combined) ||
237
- /windows sandbox: runner error: CreateProcessAsUserW failed:\s*5/iu.test(combined) ||
238
- /spawn setup refresh/iu.test(combined)) {
239
- const warnings = [...diagnosis.warnings];
240
- const sandboxFailureWarning = "Codex workspace-write sandbox could not launch subprocesses on this Windows host.";
241
- if (!warnings.includes(sandboxFailureWarning)) {
242
- warnings.push(sandboxFailureWarning);
243
- }
244
- return {
245
- summary: "Codex workspace-write sandbox could not launch subprocesses on this Windows host.",
246
- diagnosis: {
247
- ...diagnosis,
248
- sandboxCompatible: false,
249
- warnings,
250
- remediation: "MartinLoop already invokes Codex's underlying binary directly when it can resolve the npm shim (bypassing the cmd.exe/PowerShell wrapper hop), so this failure persisted even at the shallowest invocation depth available. Update or reinstall Codex on this Windows host until `codex exec --sandbox workspace-write` can launch a simple shell command before running governed Codex work."
251
- }
252
- };
253
- }
254
- if (/writing is blocked by read-only sandbox/iu.test(combined) ||
255
- /read-only filesystem sandbox/iu.test(combined) ||
256
- /approval is disabled/iu.test(combined)) {
257
- const warnings = [...diagnosis.warnings];
258
- const readOnlySandboxWarning = "Codex stayed in a read-only or approval-disabled sandbox even though MartinLoop requested workspace-write.";
259
- if (!warnings.includes(readOnlySandboxWarning)) {
260
- warnings.push(readOnlySandboxWarning);
261
- }
262
- return {
263
- summary: "Codex stayed in a read-only or approval-disabled sandbox even though MartinLoop requested workspace-write.",
264
- diagnosis: {
265
- ...diagnosis,
266
- sandboxCompatible: false,
267
- warnings,
268
- remediation: "Launch governed Codex runs with `codex exec --ignore-user-config --sandbox workspace-write`. If the session still reports a read-only sandbox, treat it as a host/runtime mismatch and repair or relocate the affected Codex workspace before resuming governed work."
269
- }
270
- };
271
- }
272
- return {};
273
- }
274
- export function buildCodexExecArgs(options) {
275
- const sandbox = options.sandbox ?? "workspace-write";
276
- const modelArgs = options.model ? ["--model", options.model] : [];
277
- const extraArgs = options.extraArgs ?? [];
278
- return [
279
- "exec",
280
- // Governed MartinLoop runs should not inherit auth-sensitive default MCP/plugin state.
281
- "--ignore-user-config",
282
- "--cd",
283
- options.workingDirectory,
284
- "--sandbox",
285
- sandbox,
286
- "--json",
287
- "--color",
288
- "never",
289
- ...modelArgs,
290
- ...extraArgs,
291
- "-"
292
- ];
293
- }
294
- function parseCodexProbeEvents(stdout) {
295
- return stdout
296
- .split(/\r?\n/u)
297
- .map((line) => line.trim())
298
- .filter(Boolean)
299
- .map((line) => {
300
- try {
301
- return JSON.parse(line);
302
- }
303
- catch {
304
- return undefined;
305
- }
306
- })
307
- .filter((event) => event !== undefined);
308
- }
309
- function hasSuccessfulCommandExecution(events) {
310
- return events.some((event) => event.type === "item.completed" &&
311
- event.item?.type === "command_execution" &&
312
- event.item?.status === "completed" &&
313
- event.item?.exit_code === 0);
314
- }
315
- export function resolveCliCommandAvailability(command, options = {}) {
316
- const platform = options.platform ?? process.platform;
317
- const env = options.env ?? process.env;
318
- const spawnSyncImpl = options.spawnSyncImpl ?? spawnSync;
319
- const discovery = readLocatorCandidates(command, platform, spawnSyncImpl);
320
- if (discovery.candidates.length > 0) {
321
- const resolvedPath = discovery.candidates[0];
322
- return {
323
- command,
324
- available: true,
325
- locator: discovery.locator,
326
- detail: `${command} is available on PATH.`,
327
- ...(resolvedPath ? { resolvedPath } : {}),
328
- candidatePaths: discovery.candidates
329
- };
330
- }
331
- // PATH didn't find it — search common install locations before giving up.
332
- const offPathCandidate = discoverCommandOffPath(command, platform, env);
333
- if (offPathCandidate) {
334
- return {
335
- command,
336
- available: true,
337
- locator: "off-path-discovery",
338
- detail: `${command} found at ${offPathCandidate} (not on PATH, auto-discovered).`,
339
- resolvedPath: offPathCandidate,
340
- candidatePaths: [offPathCandidate]
341
- };
342
- }
343
- return {
344
- command,
345
- available: false,
346
- locator: discovery.locator,
347
- detail: `${command} is not installed. ${suggestInstall(command)}`
348
- };
349
- }
350
- function discoverCommandOffPath(command, platform, env) {
351
- const home = env.HOME ?? env.USERPROFILE ?? "";
352
- const dirs = [];
353
- if (platform === "win32") {
354
- const appData = env.APPDATA;
355
- if (appData)
356
- dirs.push(join(appData, "npm"));
357
- const localAppData = env.LOCALAPPDATA;
358
- if (localAppData)
359
- dirs.push(join(localAppData, "OpenAI", "Codex", "bin"));
360
- if (home)
361
- dirs.push(join(home, "scoop", "shims"));
362
- }
363
- else {
364
- dirs.push("/usr/local/bin", "/opt/homebrew/bin");
365
- if (home) {
366
- dirs.push(join(home, ".local", "bin"), join(home, ".npm-global", "bin"), join(home, ".bun", "bin"), join(home, ".cargo", "bin"));
367
- }
368
- const nvmDir = env.NVM_DIR;
369
- if (nvmDir)
370
- dirs.push(join(nvmDir, "current", "bin"));
371
- }
372
- const extensions = platform === "win32"
373
- ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").map((e) => e.trim().toLowerCase()).filter(Boolean)
374
- : [""];
375
- for (const dir of dirs) {
376
- for (const ext of extensions) {
377
- const candidate = ext ? join(dir, `${command}${ext}`) : join(dir, command);
378
- if (existsSync(candidate)) {
379
- return candidate;
380
- }
381
- }
382
- }
383
- return undefined;
384
- }
385
- function suggestInstall(command) {
386
- const installs = {
387
- claude: "Install with: npm install -g @anthropic-ai/claude-code",
388
- codex: "Install with: npm install -g @openai/codex",
389
- gemini: "Install with: npm install -g @google/gemini-cli"
390
- };
391
- return installs[command] ?? `Install ${command} and ensure it is available.`;
392
- }
393
- export function detectCodexHostPlatform(env = process.env, platform = process.platform) {
394
- if (platform === "win32") {
395
- return "windows";
396
- }
397
- if (platform === "darwin") {
398
- return "macos";
399
- }
400
- if (env["WSL_DISTRO_NAME"] || env["WSL_INTEROP"]) {
401
- return "wsl";
402
- }
403
- return "linux";
404
- }
405
- export function diagnoseCodexHost(availability, options = {}) {
406
- const hostPlatform = detectCodexHostPlatform(options.env ?? process.env, options.platform ?? process.platform);
407
- const resolvedPath = availability.resolvedPath;
408
- const installKind = detectInstallKind(resolvedPath, hostPlatform);
409
- const invocationMode = detectInvocationMode(resolvedPath, options.platform ?? process.platform);
410
- const warnings = [];
411
- if (!availability.available) {
412
- return {
413
- hostPlatform,
414
- nativeInstallValid: false,
415
- installKind,
416
- invocationMode,
417
- sandboxMode: "workspace-write",
418
- sandboxCompatible: false,
419
- ...(resolvedPath ? { resolvedPath } : {}),
420
- warnings,
421
- remediation: "Install or expose the Codex CLI on PATH before running governed Codex work."
422
- };
423
- }
424
- if ((hostPlatform === "linux" || hostPlatform === "wsl") &&
425
- (installKind === "windows_shim" || installKind === "windows_mounted_path")) {
426
- warnings.push("Codex resolves to a Windows-hosted install from a Linux/WSL environment.");
427
- return {
428
- hostPlatform,
429
- nativeInstallValid: false,
430
- installKind,
431
- invocationMode,
432
- sandboxMode: "workspace-write",
433
- sandboxCompatible: false,
434
- ...(resolvedPath ? { resolvedPath } : {}),
435
- warnings,
436
- remediation: "Install Codex natively inside this Linux/WSL environment instead of relying on a Windows PATH shim."
437
- };
438
- }
439
- return {
440
- hostPlatform,
441
- nativeInstallValid: true,
442
- installKind,
443
- invocationMode,
444
- sandboxMode: "workspace-write",
445
- sandboxCompatible: true,
446
- ...(resolvedPath ? { resolvedPath } : {}),
447
- ...(hostPlatform === "linux" || hostPlatform === "wsl"
448
- ? { nativeDependencyStatus: "unknown" }
449
- : {}),
450
- warnings
451
- };
452
- }
453
- export function probeCodexLaunch(input) {
454
- const availability = input.availability ??
455
- resolveCliCommandAvailability("codex", {
456
- platform: input.platform,
457
- spawnSyncImpl: input.spawnSyncImpl
458
- });
459
- const diagnosis = diagnoseCodexHost(availability, {
460
- env: input.env,
461
- platform: input.platform
462
- });
463
- const args = buildCodexExecArgs({
464
- workingDirectory: input.workingDirectory,
465
- model: input.model ?? DEFAULT_CODEX_CHATGPT_MODEL,
466
- mode: "probe"
467
- });
468
- if (!availability.available) {
469
- return {
470
- ok: false,
471
- summary: availability.detail,
472
- availability,
473
- diagnosis,
474
- command: availability.command,
475
- args
476
- };
477
- }
478
- if (!isInsideGitRepository(input.workingDirectory)) {
479
- return {
480
- ok: false,
481
- summary: "Working directory is not inside a git repository. Codex exec requires a trusted repo unless --skip-git-repo-check is explicitly enabled.",
482
- availability,
483
- diagnosis,
484
- command: availability.resolvedPath ?? availability.command,
485
- args
486
- };
487
- }
488
- const spawnSyncImpl = input.spawnSyncImpl ?? spawnSync;
489
- const platform = input.platform ?? process.platform;
490
- const env = input.env ?? process.env;
491
- const probeCandidates = buildProbeCandidates({
492
- availability,
493
- env,
494
- platform,
495
- includeDesktopCandidates: input.spawnSyncImpl === undefined
496
- });
497
- const candidatePaths = probeCandidates.map((candidate) => candidate.path);
498
- const cacheKey = buildProbeCacheKey({
499
- workingDirectory: input.workingDirectory,
500
- platform,
501
- candidatePaths,
502
- model: input.model
503
- });
504
- if (input.spawnSyncImpl === undefined) {
505
- const cached = codexLaunchProbeCache.get(cacheKey);
506
- if (cached) {
507
- return cached;
508
- }
509
- }
510
- const candidateResults = [];
511
- const probeCandidatePath = (candidate) => {
512
- const candidateDiagnosis = candidate.diagnosis;
513
- if (!candidateDiagnosis.nativeInstallValid) {
514
- candidateResults.push({
515
- path: candidate.path,
516
- diagnosis: candidateDiagnosis,
517
- ok: false,
518
- summary: candidateDiagnosis.remediation ?? "Codex host installation is not valid for this environment."
519
- });
520
- return false;
521
- }
522
- const spawnPlan = buildProbeCommand(candidate.path, args, platform);
523
- const result = spawnSyncImpl(spawnPlan.command, spawnPlan.args, {
524
- cwd: input.workingDirectory,
525
- encoding: "utf8",
526
- stdio: ["pipe", "pipe", "pipe"],
527
- input: CODEX_LAUNCH_PROBE_PROMPT
528
- });
529
- const probedDiagnosis = {
530
- ...candidateDiagnosis,
531
- invocationMode: spawnPlan.invocationMode
532
- };
533
- if (result.error) {
534
- const classifiedFailure = classifyProbeFailure(result.stderr ?? "", result.stdout ?? "", probedDiagnosis);
535
- candidateResults.push({
536
- path: candidate.path,
537
- diagnosis: classifiedFailure.diagnosis ?? probedDiagnosis,
538
- ok: false,
539
- summary: classifiedFailure.summary ?? `Codex launch probe failed: ${result.error.message}`,
540
- stderr: result.stderr ?? "",
541
- stdout: result.stdout ?? ""
542
- });
543
- return false;
544
- }
545
- if (result.status !== 0) {
546
- const stderr = (result.stderr ?? "").trim();
547
- const classifiedFailure = classifyProbeFailure(result.stderr ?? "", result.stdout ?? "", probedDiagnosis);
548
- candidateResults.push({
549
- path: candidate.path,
550
- diagnosis: classifiedFailure.diagnosis ?? probedDiagnosis,
551
- ok: false,
552
- summary: classifiedFailure.summary ??
553
- (stderr.length > 0 ? `Codex launch probe failed: ${stderr}` : "Codex launch probe exited non-zero."),
554
- exitCode: result.status ?? undefined,
555
- stderr: result.stderr ?? "",
556
- stdout: result.stdout ?? ""
557
- });
558
- return false;
559
- }
560
- const events = parseCodexProbeEvents(result.stdout ?? "");
561
- if (!hasSuccessfulCommandExecution(events)) {
562
- const classifiedFailure = classifyProbeFailure(result.stderr ?? "", result.stdout ?? "", probedDiagnosis);
563
- candidateResults.push({
564
- path: candidate.path,
565
- diagnosis: classifiedFailure.diagnosis ?? probedDiagnosis,
566
- ok: false,
567
- summary: classifiedFailure.summary ?? "Codex launch probe did not complete a shell command successfully.",
568
- exitCode: result.status ?? undefined,
569
- stderr: result.stderr ?? "",
570
- stdout: result.stdout ?? ""
571
- });
572
- return false;
573
- }
574
- candidateResults.push({
575
- path: candidate.path,
576
- diagnosis: probedDiagnosis,
577
- ok: true,
578
- summary: "Codex exec prompt-and-shell probe passed for the current MartinLoop invocation shape.",
579
- exitCode: result.status ?? undefined,
580
- stderr: result.stderr ?? "",
581
- stdout: result.stdout ?? ""
582
- });
583
- return true;
584
- };
585
- for (const candidate of probeCandidates) {
586
- if (probeCandidatePath(candidate)) {
587
- break;
588
- }
589
- }
590
- const successfulCandidates = candidateResults.filter((candidate) => candidate.ok);
591
- const selectedCandidate = successfulCandidates[0];
592
- const candidateProbeResults = candidateResults.map((candidate) => ({
593
- path: candidate.path,
594
- installKind: candidate.diagnosis.installKind,
595
- invocationMode: candidate.diagnosis.invocationMode,
596
- nativeInstallValid: candidate.diagnosis.nativeInstallValid,
597
- sandboxCompatible: candidate.diagnosis.sandboxCompatible,
598
- launchReady: candidate.ok,
599
- summary: candidate.summary,
600
- ...(candidate.diagnosis.remediation ? { remediation: candidate.diagnosis.remediation } : {}),
601
- ...(candidate.diagnosis.nativeDependencyStatus
602
- ? { nativeDependencyStatus: candidate.diagnosis.nativeDependencyStatus }
603
- : {}),
604
- ...(candidate.diagnosis.nativeDependencyPackage
605
- ? { nativeDependencyPackage: candidate.diagnosis.nativeDependencyPackage }
606
- : {})
607
- }));
608
- if (selectedCandidate) {
609
- const successResult = {
610
- ok: true,
611
- summary: selectedCandidate.summary,
612
- availability: {
613
- ...availability,
614
- resolvedPath: selectedCandidate.path,
615
- candidatePaths
616
- },
617
- diagnosis: {
618
- ...selectedCandidate.diagnosis,
619
- resolvedPath: selectedCandidate.path
620
- },
621
- command: selectedCandidate.path,
622
- args,
623
- exitCode: selectedCandidate.exitCode,
624
- stderr: selectedCandidate.stderr,
625
- stdout: selectedCandidate.stdout,
626
- candidateProbeResults
627
- };
628
- if (input.spawnSyncImpl === undefined) {
629
- codexLaunchProbeCache.set(cacheKey, successResult);
630
- }
631
- return successResult;
632
- }
633
- const bestFailure = platform === "win32"
634
- ? candidateResults.find((candidate) => candidate.diagnosis.nativeInstallValid && candidate.diagnosis.installKind === "native") ??
635
- candidateResults.find((candidate) => candidate.diagnosis.nativeInstallValid) ??
636
- candidateResults[0]
637
- : candidateResults[0];
638
- const failureResult = {
639
- ok: false,
640
- summary: bestFailure?.summary ?? diagnosis.remediation ?? "Codex launch probe failed.",
641
- availability: {
642
- ...availability,
643
- ...(bestFailure ? { resolvedPath: bestFailure.path } : {}),
644
- ...(candidatePaths.length ? { candidatePaths } : {})
645
- },
646
- diagnosis: bestFailure
647
- ? {
648
- ...bestFailure.diagnosis,
649
- resolvedPath: bestFailure.path
650
- }
651
- : diagnosis,
652
- command: bestFailure?.path ?? availability.resolvedPath ?? availability.command,
653
- args,
654
- exitCode: bestFailure?.exitCode,
655
- stderr: bestFailure?.stderr,
656
- stdout: bestFailure?.stdout,
657
- candidateProbeResults
658
- };
659
- if (input.spawnSyncImpl === undefined) {
660
- codexLaunchProbeCache.set(cacheKey, failureResult);
661
- }
662
- return failureResult;
663
- }
@@ -1,10 +0,0 @@
1
- import type { MartinAdapter, MartinAdapterRequest, MartinAdapterResult } from "../../../core/index.js";
2
- export interface DirectProviderAdapterOptions {
3
- providerId: string;
4
- model: string;
5
- label?: string;
6
- transport?: "http" | "routed_http";
7
- capabilities?: Partial<NonNullable<MartinAdapter["metadata"]["capabilities"]>>;
8
- responder?: (request: MartinAdapterRequest) => Promise<MartinAdapterResult> | MartinAdapterResult;
9
- }
10
- export declare function createDirectProviderAdapter(options: DirectProviderAdapterOptions): MartinAdapter;