@agentchatme/agent-core 0.6.0 → 0.7.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.
package/dist/presets.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { TextsRuntime } from 'agentchatme';
2
- import { a as RunProfile, b as RunRunner, q as RunPreflightOptions, f as RunPreflight, g as RunRequest, c as RunOutcome } from './runner-C9kZD3KH.js';
2
+ import { a as RunProfile, b as RunRunner, f as RunPreflight, q as RunPreflightOptions, g as RunRequest, c as RunOutcome } from './runner-BLvFalN4.js';
3
3
 
4
4
  /** What a preset needs to build a runner acting as one agent. */
5
5
  interface PresetContext {
@@ -115,6 +115,48 @@ declare function withoutParentSession(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv
115
115
  /** `actual` (any text containing `x.y.z`) is at least `minimum`. False when either has no version in it. */
116
116
  declare function semverAtLeast(actual: string, minimum: string): boolean;
117
117
 
118
+ /** The fixed prompt: nothing from any peer, nothing to act on. */
119
+ declare const RUNTIME_CHECK_PROMPT = "Reply with the single word OK.";
120
+ /**
121
+ * The check's own budget. Past it the probe is SIGTERMed, SIGKILLed 5 s later
122
+ * and given up 5 s after that: 55 s at most, inside the engine's
123
+ * `RUNTIME_CHECK_DEADLINE_MS` (60 s).
124
+ */
125
+ declare const RUNTIME_CHECK_BUDGET_MS = 45000;
126
+ /** The most of a check's stdout kept for its `judge` (a result line is a few kB); more is not read. */
127
+ declare const RUNTIME_CHECK_OUTPUT_BYTES: number;
128
+ /** The name of the empty folder a runtime check runs in, beside the runtime's own config. */
129
+ declare const RUNTIME_CHECK_DIR = "agentchat-runtime-check";
130
+ /**
131
+ * The variables an AgentChat key travels in (the daemon's own, the listener's
132
+ * Codex bearer variable): never in a runtime check's environment, whatever
133
+ * the runs carry. The check needs no key.
134
+ */
135
+ declare const RUNTIME_CHECK_KEY_ENV: readonly string[];
136
+ interface RuntimeCheckSpec {
137
+ /** The runtime's name, for the diagnostic. */
138
+ readonly label: string;
139
+ readonly command: string;
140
+ readonly args: readonly string[];
141
+ /** An empty folder of the check's own (created owner-only). */
142
+ readonly cwd: string;
143
+ /** The runs' environment; the key variables are taken out (`RUNTIME_CHECK_KEY_ENV`, `keyEnv`). */
144
+ readonly env: NodeJS.ProcessEnv;
145
+ /** Another variable this runtime's runs carry a key in (a Codex runner's `keyEnv`). */
146
+ readonly keyEnv?: string;
147
+ readonly signal?: AbortSignal;
148
+ /**
149
+ * Reads the runtime's answer (its stdout, bounded) after an exit 0: null
150
+ * when it is a good answer, else why not (ids and flags only, never the
151
+ * text). Absent: exit 0 with something on stdout is ok.
152
+ */
153
+ readonly judge?: (stdout: string) => string | null;
154
+ /** Test seam: `RUNTIME_CHECK_BUDGET_MS`. */
155
+ readonly budgetMs?: number;
156
+ }
157
+ /** Run the check once: ok when the runtime exited 0 having printed an answer. Never throws. */
158
+ declare function runRuntimeCheck(spec: RuntimeCheckSpec): Promise<RunPreflight>;
159
+
118
160
  declare const CLAUDE_CODE_PRESET = "claude-code";
119
161
  /**
120
162
  * Two flags set the floor:
@@ -260,6 +302,59 @@ interface ClaudeRunArgOptions {
260
302
  */
261
303
  readonly appendSystemPromptFile?: string | undefined;
262
304
  }
305
+ /**
306
+ * The `--settings` a runtime check is given: no hook of the user's (or a
307
+ * workdir repository's) fires on a health check, the two `ANSWER_ENV`
308
+ * switches again (a settings file's `env` overrides the process environment;
309
+ * `--settings` outranks user, project and local settings), and verbose output
310
+ * off. A constant (`claude --help`: a settings value that fails validation is
311
+ * silently ignored in print mode).
312
+ *
313
+ * verbose: false, viewMode: "default" with verbose on (the user's `verbose`
314
+ * setting or its older `~/.claude.json` copy, or `viewMode: "verbose"`),
315
+ * `--output-format json` prints a JSON array of every message instead of
316
+ * the one result object. Both keys are documented settings
317
+ * (settings-reference.md: `viewMode` overrides `verbose`; only the
318
+ * `--verbose` flag, never passed here, outranks them). `verbose` is a
319
+ * settings key since 2.1.119, below the floor; `viewMode` is newer, and a
320
+ * version that does not know it ignores just that key (seen on 2.1.328:
321
+ * an unknown key or an invalid value leaves the rest of `--settings` in
322
+ * force, hooks off included). Managed settings outrank `--settings`, so
323
+ * the judge reads the array too (`claudeRuntimeCheckJudge`).
324
+ *
325
+ * language: "english" the user's `language` setting is an instruction to
326
+ * answer in that language; the fixed prompt is English, and the check
327
+ * is answered as written (`--settings` outranks the user's value).
328
+ *
329
+ * Verified on 2.1.328 against a stand-in provider: with the user's `verbose:
330
+ * true`, `viewMode: "verbose"` or the `~/.claude.json` `verbose`, settings
331
+ * without the two verbose keys printed an array; with them, one result object.
332
+ */
333
+ declare const RUNTIME_CHECK_SETTINGS: string;
334
+ /**
335
+ * Whether a runtime check's stdout (`--output-format json`) is a good answer:
336
+ * null when its result has `type: "result"`, `subtype: "success"`,
337
+ * `is_error: false`, at least one turn (`num_turns >= 1`: a run a hook
338
+ * blocked before the model has none) and, when it carries `usage`, at least
339
+ * one output token (`usage.output_tokens >= 1`); otherwise why not, in ids,
340
+ * flags and counts only (`is_error`, `api_error_status`, `terminal_reason`,
341
+ * `num_turns`, `output_tokens`), never the result text. It is judged by its
342
+ * shape, never by its words: a model may answer "Okay", or in the user's
343
+ * language. The result is the one object Claude Code prints, or, with verbose
344
+ * output on (the `--verbose` flag, the `verbose` or `viewMode` setting), the
345
+ * last `type: "result"` element of the JSON array it prints instead. A false
346
+ * pass is the dangerous direction (an outage reported as one conversation's
347
+ * failure hides its messages), so anything short of all of that is not ok.
348
+ */
349
+ declare function claudeRuntimeCheckJudge(stdout: string): string | null;
350
+ /**
351
+ * The argv of a runtime check: one `claude -p` with no tool of any kind (no
352
+ * MCP server, no built-in tool), no hooks, never waiting on a prompt; the
353
+ * prompt on stdin, as for a run. `denyReadPaths` are the runs' own deny rules.
354
+ */
355
+ declare function claudeRuntimeCheckArgs(denyReadPaths?: readonly string[]): string[];
356
+ /** The empty folder a runtime check runs in: beside Claude Code's config, outside every denied path. */
357
+ declare function claudeRuntimeCheckWorkdir(configDirOverride: string | undefined): string;
263
358
  /**
264
359
  * The deny paths no rule can carry: on Windows all of them (the rule syntax
265
360
  * for drive paths is undocumented), elsewhere a relative path or one with a
@@ -429,6 +524,15 @@ declare class ClaudeRunner implements RunRunner {
429
524
  * hosted tools through its MCP entry, never through that variable.
430
525
  */
431
526
  runEnv(): NodeJS.ProcessEnv;
527
+ /**
528
+ * Does the model answer right now, through this runner's binary, sign-in
529
+ * and environment? One `claude -p` with a fixed prompt and no tool at all
530
+ * (`claudeRuntimeCheckArgs`), in its own empty folder, with no key in its
531
+ * environment and no instruction file or memory in its context; ok only
532
+ * when its JSON result says success with no error (`claudeRuntimeCheckJudge`).
533
+ * Its output is read for that alone and never logged. Never throws.
534
+ */
535
+ checkRuntime(options?: RunPreflightOptions): Promise<RunPreflight>;
432
536
  start(request: RunRequest): Promise<RunOutcome>;
433
537
  }
434
538
  /** Where a listener keeps the `--mcp-config` file for this preset, inside its identity home. */
@@ -470,6 +574,35 @@ declare const CODEX_ANSWER_FILESYSTEM = "{ \":workspace_roots\" = \"read\" }";
470
574
  */
471
575
  declare const CODEX_ANSWER_DISABLED_FEATURES: readonly ["shell_tool", "view_image", "image_generation", "plugins", "apps", "memories", "browser_use", "browser_use_external", "computer_use", "in_app_browser"];
472
576
  declare function codexProfileArgs(profile: RunProfile): string[];
577
+ /**
578
+ * The features a runtime check turns off, as an `answer` run does (names at
579
+ * the 0.154.0 floor, `codex features list`). Not `hooks`: a user's hook that
580
+ * breaks every run must fail the check too (see the header).
581
+ */
582
+ declare const CODEX_RUNTIME_CHECK_DISABLED_FEATURES: readonly ["memories", "plugins", "apps"];
583
+ /**
584
+ * The argv of a runtime check: `codex exec` in `dir` (an empty folder), the
585
+ * read-only sandbox, no session files, no web search, memories, plugins or
586
+ * connectors (the user's hooks stay on, as in the runs), and the hosted
587
+ * AgentChat server switched off for it;
588
+ * the prompt on stdin, as for a run. The model and its reasoning effort are
589
+ * the runs' (see the header). `agentchatUrl` is the URL the runs pin (with
590
+ * it, the `agentchat` table stays valid whether or not a config layer defines
591
+ * one); without it a config layer must define the table, as the runs need.
592
+ */
593
+ declare function codexRuntimeCheckArgs(dir: string, agentchatUrl?: string): string[];
594
+ /** The empty folder a runtime check runs in, under CODEX_HOME. */
595
+ declare function codexRuntimeCheckWorkdir(codexHome: string): string;
596
+ /**
597
+ * Whether a runtime check's stdout (`codex exec --json`: one event per line,
598
+ * exec/src/exec_events.rs) is a good answer: null when it holds a
599
+ * `turn.completed` event and an `item.completed` whose item is an
600
+ * `agent_message` with text, and no `turn.failed`; otherwise why not, in event
601
+ * types only, never a message or an error's text. Exit 0 alone is not an
602
+ * answer. A line that is not a JSON object is skipped (a cut-off last line
603
+ * included: its events are then missing, and the check is not ok).
604
+ */
605
+ declare function codexRuntimeCheckJudge(stdout: string): string | null;
473
606
  /** Where a run's hosted tool server points, and which variable carries its bearer token. */
474
607
  interface CodexMcpOverride {
475
608
  readonly url: string;
@@ -679,6 +812,16 @@ declare class CodexRunner implements RunRunner {
679
812
  private listingFlags;
680
813
  /** `codex mcp list --json <flags>` from the run's workdir, with the run's environment: its output, or why there is none. Killed with its whole tree past its time. */
681
814
  private listMcpServers;
815
+ /**
816
+ * Does the model answer right now, through this runner's binary, sign-in,
817
+ * CODEX_HOME and environment? One `codex exec` with a fixed prompt in its
818
+ * own empty folder, read-only, with the hosted AgentChat server switched
819
+ * off and the user's hooks on, as in the runs (`codexRuntimeCheckArgs`),
820
+ * and no key in its environment; ok only on exit 0 with a completed turn
821
+ * that holds an agent message (`codexRuntimeCheckJudge`). Its output is
822
+ * read for that alone and never logged. Never throws.
823
+ */
824
+ checkRuntime(options?: RunPreflightOptions): Promise<RunPreflight>;
682
825
  start(request: RunRequest): Promise<RunOutcome>;
683
826
  }
684
827
  /** Where a listener's `own` runs' headers helper lives: `<home>/presets/codex.mcp-headers.mjs` (owner-only; it holds no key). */
@@ -711,4 +854,4 @@ declare const PRESETS: Readonly<Record<string, Preset>>;
711
854
  declare function presetNamed(name: string): Preset | null;
712
855
  declare function presetNames(): string[];
713
856
 
714
- export { AGENTCHAT_TOOL_ALLOW, ANSWER_DENIED_TOOLS, ANSWER_ENV, ANSWER_SETTINGS, ANSWER_TOOLS, CLAUDE_CODE_ENV_KEPT, CLAUDE_CODE_PRESET, CLAUDE_MCP_SERVER_NAME, CLAUDE_SESSION_ENV, CODEX_ANSWER_DISABLED_FEATURES, CODEX_ANSWER_FILESYSTEM, CODEX_ANSWER_PERMISSIONS, CODEX_LISTENER_HEADERS_HELPER_SOURCE, CODEX_MANAGED_PROXY_ENV, CODEX_MCP_LIST_MAX_AGE_MS, CODEX_MCP_LIST_TIMEOUT_MS, CODEX_MCP_SERVER_NAME, CODEX_PRESET, CODEX_PROBE_TIMEOUT_MS, CODEX_PROMPT_FROM_STDIN, CODEX_SESSION_ENV, type ClaudeAnswerMcp, type ClaudeRunArgOptions, ClaudeRunner, type ClaudeRunnerOptions, type ClaudeSignIn, type CodexMcpOverride, CodexRunner, type CodexRunnerOptions, LISTENER_KEY_ENV, MIN_CLAUDE_CODE_VERSION, MIN_CODEX_VERSION, PARENT_ENV_KEYS, PRESETS, PROBE_TIMEOUT_MS, type Preset, type PresetContext, type PresetInspection, WEB_TOOLS, WORK_TOOLS, agentchatTableKeys, buildClaudeEnv, claudeAnswerFallbackWorkdir, claudeCodePreset, claudeConfigDirFrom, claudeExtraDirectoriesGrant, claudeHomeFor, claudeIsLoggedIn, claudeManagedSettingsDir, claudeMcpConfig, claudeMcpConfigPath, claudeProfileArgs, claudeProjectsDirFor, claudeRunArgs, claudeSettingsFilesGrantingDirectories, claudeSignIn, claudeUserStatePathFor, codexAgentchatExplicitAuth, codexAnswerFallbackWorkdir, codexClientHeadersToml, codexConfigLayerFiles, codexDotEnvKeyNames, codexHeadersHelperCommand, codexHomeFrom, codexIsLoggedIn, codexListenerHeadersHelperPath, codexMcpDisableArgs, codexMcpOverrideArgs, codexPinnedUrlArgs, codexPreset, codexProfileArgs, codexRunArgs, codexServerNameAddressable, deniedAncestorOf, inexpressibleDenyPaths, inspectClaudeRuntime, inspectCodexRuntime, isParentSessionEnv, parseCodexMcpList, presetNamed, presetNames, readDenyRules, semverAtLeast, withoutParentSession, workdirPaths, workdirReadRules };
857
+ export { AGENTCHAT_TOOL_ALLOW, ANSWER_DENIED_TOOLS, ANSWER_ENV, ANSWER_SETTINGS, ANSWER_TOOLS, CLAUDE_CODE_ENV_KEPT, CLAUDE_CODE_PRESET, CLAUDE_MCP_SERVER_NAME, CLAUDE_SESSION_ENV, CODEX_ANSWER_DISABLED_FEATURES, CODEX_ANSWER_FILESYSTEM, CODEX_ANSWER_PERMISSIONS, CODEX_LISTENER_HEADERS_HELPER_SOURCE, CODEX_MANAGED_PROXY_ENV, CODEX_MCP_LIST_MAX_AGE_MS, CODEX_MCP_LIST_TIMEOUT_MS, CODEX_MCP_SERVER_NAME, CODEX_PRESET, CODEX_PROBE_TIMEOUT_MS, CODEX_PROMPT_FROM_STDIN, CODEX_RUNTIME_CHECK_DISABLED_FEATURES, CODEX_SESSION_ENV, type ClaudeAnswerMcp, type ClaudeRunArgOptions, ClaudeRunner, type ClaudeRunnerOptions, type ClaudeSignIn, type CodexMcpOverride, CodexRunner, type CodexRunnerOptions, LISTENER_KEY_ENV, MIN_CLAUDE_CODE_VERSION, MIN_CODEX_VERSION, PARENT_ENV_KEYS, PRESETS, PROBE_TIMEOUT_MS, type Preset, type PresetContext, type PresetInspection, RUNTIME_CHECK_BUDGET_MS, RUNTIME_CHECK_DIR, RUNTIME_CHECK_KEY_ENV, RUNTIME_CHECK_OUTPUT_BYTES, RUNTIME_CHECK_PROMPT, RUNTIME_CHECK_SETTINGS, type RuntimeCheckSpec, WEB_TOOLS, WORK_TOOLS, agentchatTableKeys, buildClaudeEnv, claudeAnswerFallbackWorkdir, claudeCodePreset, claudeConfigDirFrom, claudeExtraDirectoriesGrant, claudeHomeFor, claudeIsLoggedIn, claudeManagedSettingsDir, claudeMcpConfig, claudeMcpConfigPath, claudeProfileArgs, claudeProjectsDirFor, claudeRunArgs, claudeRuntimeCheckArgs, claudeRuntimeCheckJudge, claudeRuntimeCheckWorkdir, claudeSettingsFilesGrantingDirectories, claudeSignIn, claudeUserStatePathFor, codexAgentchatExplicitAuth, codexAnswerFallbackWorkdir, codexClientHeadersToml, codexConfigLayerFiles, codexDotEnvKeyNames, codexHeadersHelperCommand, codexHomeFrom, codexIsLoggedIn, codexListenerHeadersHelperPath, codexMcpDisableArgs, codexMcpOverrideArgs, codexPinnedUrlArgs, codexPreset, codexProfileArgs, codexRunArgs, codexRuntimeCheckArgs, codexRuntimeCheckJudge, codexRuntimeCheckWorkdir, codexServerNameAddressable, deniedAncestorOf, inexpressibleDenyPaths, inspectClaudeRuntime, inspectCodexRuntime, isParentSessionEnv, parseCodexMcpList, presetNamed, presetNames, readDenyRules, runRuntimeCheck, semverAtLeast, withoutParentSession, workdirPaths, workdirReadRules };
package/dist/presets.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  VERSION,
3
3
  hostedMcpUrl,
4
4
  runProbe
5
- } from "./chunk-QUANHUVW.js";
5
+ } from "./chunk-4PCDVXAR.js";
6
6
  import {
7
7
  atomicWriteFile,
8
8
  clientHeadersOf,
@@ -11,11 +11,12 @@ import {
11
11
  redactDiagnostic,
12
12
  spawnCommand,
13
13
  spawnRun,
14
+ spawnRunCapturing,
14
15
  workdirExposesHome
15
- } from "./chunk-AVLI55C5.js";
16
+ } from "./chunk-5KMQ23O6.js";
16
17
 
17
18
  // src/presets/claude-code.ts
18
- import * as fs from "fs";
19
+ import * as fs2 from "fs";
19
20
  import * as os from "os";
20
21
  import * as path from "path";
21
22
 
@@ -34,6 +35,41 @@ function semverAtLeast(actual, minimum) {
34
35
  return true;
35
36
  }
36
37
 
38
+ // src/presets/runtime-check.ts
39
+ import * as fs from "fs";
40
+ var RUNTIME_CHECK_PROMPT = "Reply with the single word OK.";
41
+ var RUNTIME_CHECK_BUDGET_MS = 45e3;
42
+ var RUNTIME_CHECK_OUTPUT_BYTES = 128 * 1024;
43
+ var RUNTIME_CHECK_DIR = "agentchat-runtime-check";
44
+ var RUNTIME_CHECK_KEY_ENV = ["AGENTCHAT_API_KEY", "AGENTCHAT_LISTENER_API_KEY"];
45
+ function withoutKeys(env, also) {
46
+ const names = new Set([...RUNTIME_CHECK_KEY_ENV, ...also].map((name) => name.toUpperCase()));
47
+ const out = {};
48
+ for (const [key, value] of Object.entries(env)) if (!names.has(key.toUpperCase())) out[key] = value;
49
+ return out;
50
+ }
51
+ async function runRuntimeCheck(spec) {
52
+ if (spec.signal?.aborted === true) return { ok: false, detail: `${spec.label} runtime check: stopped before it started` };
53
+ try {
54
+ fs.mkdirSync(spec.cwd, { recursive: true, mode: 448 });
55
+ } catch (err) {
56
+ return { ok: false, detail: `${spec.label} runtime check: could not create its folder ${spec.cwd}: ${err instanceof Error ? err.message : String(err)}` };
57
+ }
58
+ const { outcome, stdout } = await spawnRunCapturing({
59
+ command: spec.command,
60
+ args: spec.args,
61
+ cwd: spec.cwd,
62
+ env: withoutKeys(spec.env, spec.keyEnv !== void 0 ? [spec.keyEnv] : []),
63
+ stdin: RUNTIME_CHECK_PROMPT,
64
+ budgetMs: spec.budgetMs ?? RUNTIME_CHECK_BUDGET_MS,
65
+ requireStdout: true,
66
+ ...spec.signal !== void 0 ? { signal: spec.signal } : {}
67
+ }, spec.judge !== void 0 ? RUNTIME_CHECK_OUTPUT_BYTES : 0);
68
+ if (outcome.state !== "ok") return { ok: false, detail: `${spec.label} runtime check ${outcome.state.replace("_", " ")}${outcome.detail ? `: ${outcome.detail}` : ""}` };
69
+ const verdict = spec.judge === void 0 ? null : spec.judge(stdout);
70
+ return verdict === null ? { ok: true } : { ok: false, detail: `${spec.label} runtime check failed: exit 0, but ${verdict}` };
71
+ }
72
+
37
73
  // src/presets/types.ts
38
74
  var CLAUDE_CODE_ENV_KEPT = [
39
75
  // Sign-in and provider
@@ -249,7 +285,7 @@ async function claudeSignIn(configDirOverride, command = "claude", timeoutMs = P
249
285
  if (status.status === 0) return { signedIn: true, unanswered: null };
250
286
  }
251
287
  const configDir = claudeHomeFor(configDirOverride);
252
- if (fs.existsSync(path.join(configDir, ".credentials.json"))) return { signedIn: true, unanswered: null };
288
+ if (fs2.existsSync(path.join(configDir, ".credentials.json"))) return { signedIn: true, unanswered: null };
253
289
  if (process.platform !== "darwin") return { signedIn: false, unanswered: null };
254
290
  const keychain = await runProbe("security", ["find-generic-password", "-s", "Claude Code-credentials"], { timeoutMs: Math.min(timeoutMs, 5e3), ...signal !== void 0 ? { signal } : {} });
255
291
  return { signedIn: !keychain.error && keychain.status === 0, unanswered: null };
@@ -284,7 +320,7 @@ function workdirPaths(workdir) {
284
320
  const given = path.resolve(workdir);
285
321
  let real = given;
286
322
  try {
287
- real = fs.realpathSync(given);
323
+ real = fs2.realpathSync(given);
288
324
  } catch {
289
325
  }
290
326
  return real === given ? [given] : [given, real];
@@ -333,6 +369,78 @@ function claudeProfileArgs(profile, workdir) {
333
369
  return ["--dangerously-skip-permissions", "--permission-prompts", "none", "--allowedTools", AGENTCHAT_TOOL_ALLOW];
334
370
  }
335
371
  }
372
+ var RUNTIME_CHECK_SETTINGS = JSON.stringify({
373
+ env: { CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1", CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1" },
374
+ disableAllHooks: true,
375
+ verbose: false,
376
+ viewMode: "default",
377
+ language: "english"
378
+ });
379
+ function lastResultMessage(messages) {
380
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
381
+ const m = messages[i];
382
+ if (m !== null && typeof m === "object" && !Array.isArray(m) && m["type"] === "result") return m;
383
+ }
384
+ return null;
385
+ }
386
+ function claudeRuntimeCheckJudge(stdout) {
387
+ const text = stdout.trim();
388
+ let parsed = null;
389
+ for (const candidate of [text, text.split(/\r?\n/).filter((line) => line.trim().length > 0).at(-1) ?? ""]) {
390
+ try {
391
+ parsed = JSON.parse(candidate);
392
+ break;
393
+ } catch {
394
+ parsed = null;
395
+ }
396
+ }
397
+ if (Array.isArray(parsed)) {
398
+ parsed = lastResultMessage(parsed);
399
+ if (parsed === null) return "its answer is a list of messages with no result";
400
+ }
401
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return "its answer is not a JSON result";
402
+ const r = parsed;
403
+ if (r["type"] === "result" && r["subtype"] === "success" && r["is_error"] === false) {
404
+ const turns = r["num_turns"];
405
+ if (typeof turns !== "number" || !(turns >= 1)) return `the result has no turn (num_turns ${typeof turns === "number" ? turns : "?"})`;
406
+ const usage = r["usage"];
407
+ if (usage !== void 0 && usage !== null) {
408
+ const tokens = typeof usage === "object" && !Array.isArray(usage) ? usage["output_tokens"] : void 0;
409
+ if (typeof tokens !== "number" || !(tokens >= 1)) return `the result has no output (usage.output_tokens ${typeof tokens === "number" ? tokens : "?"})`;
410
+ }
411
+ return null;
412
+ }
413
+ const facts = [
414
+ `type ${typeof r["type"] === "string" ? r["type"] : "?"}`,
415
+ `subtype ${typeof r["subtype"] === "string" ? r["subtype"] : "?"}`,
416
+ `is_error ${typeof r["is_error"] === "boolean" ? String(r["is_error"]) : "?"}`,
417
+ ...typeof r["api_error_status"] === "number" ? [`api_error_status ${r["api_error_status"]}`] : [],
418
+ ...typeof r["terminal_reason"] === "string" && /^[a-z_]{1,40}$/.test(r["terminal_reason"]) ? [`terminal_reason ${r["terminal_reason"]}`] : []
419
+ ];
420
+ return `the result is not a success (${facts.join(", ")})`;
421
+ }
422
+ function claudeRuntimeCheckArgs(denyReadPaths = []) {
423
+ const deny = readDenyRules(denyReadPaths);
424
+ return [
425
+ "-p",
426
+ "--output-format",
427
+ "json",
428
+ "--no-session-persistence",
429
+ // No --mcp-config: with this flag, no MCP server loads at all.
430
+ "--strict-mcp-config",
431
+ // Variadic; "" is none (`claude --help`). Closed by the option after it.
432
+ "--tools",
433
+ "",
434
+ "--permission-prompts",
435
+ "none",
436
+ "--settings",
437
+ RUNTIME_CHECK_SETTINGS,
438
+ ...deny.length > 0 ? ["--disallowedTools", deny.join(",")] : []
439
+ ];
440
+ }
441
+ function claudeRuntimeCheckWorkdir(configDirOverride) {
442
+ return path.join(claudeHomeFor(configDirOverride), RUNTIME_CHECK_DIR);
443
+ }
336
444
  function expressible(raw) {
337
445
  return raw.startsWith("/") && !/[,\s]/.test(raw);
338
446
  }
@@ -387,7 +495,7 @@ function claudeManagedSettingsDir(platform = process.platform) {
387
495
  function gitRootOf(dir) {
388
496
  let current = path.resolve(dir);
389
497
  for (; ; ) {
390
- if (fs.existsSync(path.join(current, ".git"))) return current;
498
+ if (fs2.existsSync(path.join(current, ".git"))) return current;
391
499
  const parent = path.dirname(current);
392
500
  if (parent === current) return null;
393
501
  current = parent;
@@ -397,7 +505,7 @@ function claudeSettingsFilesGrantingDirectories(configDirOverride, workdir) {
397
505
  const managed = claudeManagedSettingsDir();
398
506
  const dropIns = (() => {
399
507
  try {
400
- return fs.readdirSync(path.join(managed, "managed-settings.d")).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => path.join(managed, "managed-settings.d", name));
508
+ return fs2.readdirSync(path.join(managed, "managed-settings.d")).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => path.join(managed, "managed-settings.d", name));
401
509
  } catch {
402
510
  return [];
403
511
  }
@@ -416,7 +524,7 @@ function claudeExtraDirectoriesGrant(configDirOverride, workdir) {
416
524
  for (const file of claudeSettingsFilesGrantingDirectories(configDirOverride, workdir)) {
417
525
  let text;
418
526
  try {
419
- text = fs.readFileSync(file, "utf-8");
527
+ text = fs2.readFileSync(file, "utf-8");
420
528
  } catch {
421
529
  continue;
422
530
  }
@@ -506,10 +614,10 @@ var ClaudeRunner = class _ClaudeRunner {
506
614
  log.warn(`${why}: runs can read those paths.`);
507
615
  }
508
616
  }
509
- if (this.options.mcpConfigPath !== void 0 && !fs.existsSync(this.options.mcpConfigPath)) {
617
+ if (this.options.mcpConfigPath !== void 0 && !fs2.existsSync(this.options.mcpConfigPath)) {
510
618
  return { ok: false, detail: `the hosted tool config ${this.options.mcpConfigPath} is missing` };
511
619
  }
512
- fs.mkdirSync(this.workdir(), { recursive: true, mode: 448 });
620
+ fs2.mkdirSync(this.workdir(), { recursive: true, mode: 448 });
513
621
  return { ok: true };
514
622
  }
515
623
  /** `<dir>/<stem>.<run id><ext>`: a file of this run's own beside `file` (the run id reduced to letters, digits and `-`). */
@@ -577,6 +685,27 @@ var ClaudeRunner = class _ClaudeRunner {
577
685
  const env = buildClaudeEnv(this.options.configDir, this.options.profile === "own" ? withoutInheritedKey(source) : source);
578
686
  return this.options.profile === "answer" ? { ...env, ...ANSWER_ENV } : env;
579
687
  }
688
+ /**
689
+ * Does the model answer right now, through this runner's binary, sign-in
690
+ * and environment? One `claude -p` with a fixed prompt and no tool at all
691
+ * (`claudeRuntimeCheckArgs`), in its own empty folder, with no key in its
692
+ * environment and no instruction file or memory in its context; ok only
693
+ * when its JSON result says success with no error (`claudeRuntimeCheckJudge`).
694
+ * Its output is read for that alone and never logged. Never throws.
695
+ */
696
+ async checkRuntime(options = {}) {
697
+ return runRuntimeCheck({
698
+ label: "claude",
699
+ command: this.command,
700
+ args: claudeRuntimeCheckArgs(this.readDenyPaths()),
701
+ cwd: claudeRuntimeCheckWorkdir(this.options.configDir),
702
+ // No key (runRuntimeCheck takes every key variable out); no instruction file or memory.
703
+ env: { ...this.runEnv(), ...ANSWER_ENV },
704
+ // Exit 0 is not enough: the JSON result must say success with no error.
705
+ judge: claudeRuntimeCheckJudge,
706
+ ...options.signal !== void 0 ? { signal: options.signal } : {}
707
+ });
708
+ }
580
709
  async start(request) {
581
710
  const startedAt = Date.now();
582
711
  const notStarted = (detail) => ({ state: "not_started", exitCode: null, durationMs: Date.now() - startedAt, detail });
@@ -593,7 +722,7 @@ var ClaudeRunner = class _ClaudeRunner {
593
722
  const identityFile = request.identityLine !== void 0 ? files.identityFile : void 0;
594
723
  const written = [];
595
724
  const cleanup = () => {
596
- for (const file of written) fs.rmSync(file, { force: true });
725
+ for (const file of written) fs2.rmSync(file, { force: true });
597
726
  };
598
727
  if (answerMcp !== void 0 && files.mcpConfigPath !== void 0) {
599
728
  const key = answerMcp.apiKey();
@@ -618,7 +747,7 @@ var ClaudeRunner = class _ClaudeRunner {
618
747
  }
619
748
  try {
620
749
  const args = this.argsFor(files.mcpConfigPath ?? this.options.mcpConfigPath, identityFile);
621
- log.debug(`claude ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
750
+ log.debug(`claude ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId}${request.conversationId !== void 0 ? ` for ${request.conversationId}` : ""})`);
622
751
  return await spawnRun({
623
752
  command: this.command,
624
753
  args,
@@ -685,7 +814,7 @@ var claudeCodePreset = {
685
814
  };
686
815
 
687
816
  // src/presets/codex.ts
688
- import * as fs2 from "fs";
817
+ import * as fs3 from "fs";
689
818
  import * as os2 from "os";
690
819
  import * as path2 from "path";
691
820
  var CODEX_PRESET = "codex";
@@ -758,6 +887,61 @@ function codexProfileArgs(profile) {
758
887
  return ["--dangerously-bypass-approvals-and-sandbox"];
759
888
  }
760
889
  }
890
+ var CODEX_RUNTIME_CHECK_DISABLED_FEATURES = ["memories", "plugins", "apps"];
891
+ function codexRuntimeCheckArgs(dir, agentchatUrl) {
892
+ const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`;
893
+ return [
894
+ "exec",
895
+ "--json",
896
+ "--skip-git-repo-check",
897
+ "--ephemeral",
898
+ "-C",
899
+ dir,
900
+ "--sandbox",
901
+ "read-only",
902
+ "-c",
903
+ 'web_search="disabled"',
904
+ ...CODEX_RUNTIME_CHECK_DISABLED_FEATURES.flatMap((feature) => ["--disable", feature]),
905
+ ...agentchatUrl !== void 0 ? ["-c", `${table}.url=${JSON.stringify(agentchatUrl)}`] : [],
906
+ "-c",
907
+ `${table}.enabled=false`,
908
+ CODEX_PROMPT_FROM_STDIN
909
+ ];
910
+ }
911
+ function codexRuntimeCheckWorkdir(codexHome) {
912
+ return path2.join(codexHome, RUNTIME_CHECK_DIR);
913
+ }
914
+ function jsonObject(value) {
915
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
916
+ }
917
+ function codexRuntimeCheckJudge(stdout) {
918
+ let events = 0;
919
+ let completed = false;
920
+ let failed = false;
921
+ let answered = false;
922
+ for (const line of stdout.split(/\r?\n/)) {
923
+ if (line.trim().length === 0) continue;
924
+ let event;
925
+ try {
926
+ event = jsonObject(JSON.parse(line));
927
+ } catch {
928
+ continue;
929
+ }
930
+ if (event === null) continue;
931
+ events += 1;
932
+ if (event["type"] === "turn.completed") completed = true;
933
+ else if (event["type"] === "turn.failed") failed = true;
934
+ else if (event["type"] === "item.completed") {
935
+ const item = jsonObject(event["item"]);
936
+ if (item !== null && item["type"] === "agent_message" && typeof item["text"] === "string" && item["text"].trim().length > 0) answered = true;
937
+ }
938
+ }
939
+ if (events === 0) return "its answer holds no JSON event";
940
+ if (failed) return "the turn failed (turn.failed)";
941
+ if (!completed) return "the turn did not complete (no turn.completed)";
942
+ if (!answered) return "the turn completed with no agent message";
943
+ return null;
944
+ }
761
945
  function codexClientHeadersToml(clientVersion = VERSION) {
762
946
  const pairs = Object.entries(clientHeadersOf({ runtime: "codex", version: clientVersion })).map(([name, value]) => `${JSON.stringify(name)} = ${JSON.stringify(value)}`);
763
947
  return `{ ${pairs.join(", ")} }`;
@@ -883,7 +1067,7 @@ function codexConfigLayerFiles(codexHome, workdir, platform = process.platform,
883
1067
  function codexListingKey(files, parts) {
884
1068
  const stats = files.map((file) => {
885
1069
  try {
886
- const st = fs2.statSync(file);
1070
+ const st = fs3.statSync(file);
887
1071
  return `${file}\0${st.size}\0${st.mtimeMs}`;
888
1072
  } catch {
889
1073
  return `${file}\0-`;
@@ -924,7 +1108,7 @@ var CodexRunner = class {
924
1108
  this.warnedHome = true;
925
1109
  log.warn(`the run workdir ${this.options.workdir} is your home folder or contains it: ${this.options.profile} runs work in ${this.workdir()} instead, so a peer-started run reaches none of your files there. Point the workdir at a folder of its own to choose another.`);
926
1110
  }
927
- fs2.mkdirSync(this.workdir(), { recursive: true });
1111
+ fs3.mkdirSync(this.workdir(), { recursive: true });
928
1112
  if (this.options.profile === "answer") {
929
1113
  const disables = await this.answerMcpDisables();
930
1114
  if (!disables.ok) return { ok: false, detail: codexAnswerListingRefusal(disables.detail) };
@@ -994,7 +1178,7 @@ var CodexRunner = class {
994
1178
  const dotenv = path2.join(this.options.codexHome, ".env");
995
1179
  let names = [];
996
1180
  try {
997
- names = codexDotEnvKeyNames(fs2.readFileSync(dotenv, "utf-8"));
1181
+ names = codexDotEnvKeyNames(fs3.readFileSync(dotenv, "utf-8"));
998
1182
  } catch {
999
1183
  names = [];
1000
1184
  }
@@ -1080,6 +1264,31 @@ var CodexRunner = class {
1080
1264
  });
1081
1265
  });
1082
1266
  }
1267
+ /**
1268
+ * Does the model answer right now, through this runner's binary, sign-in,
1269
+ * CODEX_HOME and environment? One `codex exec` with a fixed prompt in its
1270
+ * own empty folder, read-only, with the hosted AgentChat server switched
1271
+ * off and the user's hooks on, as in the runs (`codexRuntimeCheckArgs`),
1272
+ * and no key in its environment; ok only on exit 0 with a completed turn
1273
+ * that holds an agent message (`codexRuntimeCheckJudge`). Its output is
1274
+ * read for that alone and never logged. Never throws.
1275
+ */
1276
+ async checkRuntime(options = {}) {
1277
+ if (this.options.refuse !== void 0) return { ok: false, detail: this.options.refuse };
1278
+ const dir = codexRuntimeCheckWorkdir(this.options.codexHome);
1279
+ return runRuntimeCheck({
1280
+ label: "codex",
1281
+ command: this.command,
1282
+ args: codexRuntimeCheckArgs(dir, this.options.mcp?.url ?? this.options.pinMcpUrl),
1283
+ cwd: dir,
1284
+ // The runs' environment; runRuntimeCheck takes every key variable out, this runner's own included.
1285
+ env: this.env(),
1286
+ keyEnv: this.options.keyEnv,
1287
+ // Exit 0 is not enough: the events must show a completed turn with the model's answer.
1288
+ judge: codexRuntimeCheckJudge,
1289
+ ...options.signal !== void 0 ? { signal: options.signal } : {}
1290
+ });
1291
+ }
1083
1292
  async start(request) {
1084
1293
  const startedAt = Date.now();
1085
1294
  if (this.options.refuse !== void 0) return { state: "not_started", exitCode: null, durationMs: 0, detail: this.options.refuse };
@@ -1091,7 +1300,7 @@ var CodexRunner = class {
1091
1300
  }
1092
1301
  const ownProblem = await this.ownAuthProblem();
1093
1302
  if (ownProblem !== null) return { state: "not_started", exitCode: null, durationMs: Date.now() - startedAt, detail: ownProblem };
1094
- log.debug(`codex ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
1303
+ log.debug(`codex ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId}${request.conversationId !== void 0 ? ` for ${request.conversationId}` : ""})`);
1095
1304
  return spawnRun({
1096
1305
  command: this.command,
1097
1306
  args,
@@ -1150,7 +1359,7 @@ var codexPreset = {
1150
1359
  const file = path2.join(codexHomeFrom(env), "config.toml");
1151
1360
  let own = null;
1152
1361
  try {
1153
- own = agentchatTableKeys(fs2.readFileSync(file, "utf-8"));
1362
+ own = agentchatTableKeys(fs3.readFileSync(file, "utf-8"));
1154
1363
  } catch {
1155
1364
  own = null;
1156
1365
  }
@@ -1235,6 +1444,7 @@ export {
1235
1444
  CODEX_PRESET,
1236
1445
  CODEX_PROBE_TIMEOUT_MS,
1237
1446
  CODEX_PROMPT_FROM_STDIN,
1447
+ CODEX_RUNTIME_CHECK_DISABLED_FEATURES,
1238
1448
  CODEX_SESSION_ENV,
1239
1449
  ClaudeRunner,
1240
1450
  CodexRunner,
@@ -1244,6 +1454,12 @@ export {
1244
1454
  PARENT_ENV_KEYS,
1245
1455
  PRESETS,
1246
1456
  PROBE_TIMEOUT_MS,
1457
+ RUNTIME_CHECK_BUDGET_MS,
1458
+ RUNTIME_CHECK_DIR,
1459
+ RUNTIME_CHECK_KEY_ENV,
1460
+ RUNTIME_CHECK_OUTPUT_BYTES,
1461
+ RUNTIME_CHECK_PROMPT,
1462
+ RUNTIME_CHECK_SETTINGS,
1247
1463
  WEB_TOOLS,
1248
1464
  WORK_TOOLS,
1249
1465
  agentchatTableKeys,
@@ -1260,6 +1476,9 @@ export {
1260
1476
  claudeProfileArgs,
1261
1477
  claudeProjectsDirFor,
1262
1478
  claudeRunArgs,
1479
+ claudeRuntimeCheckArgs,
1480
+ claudeRuntimeCheckJudge,
1481
+ claudeRuntimeCheckWorkdir,
1263
1482
  claudeSettingsFilesGrantingDirectories,
1264
1483
  claudeSignIn,
1265
1484
  claudeUserStatePathFor,
@@ -1278,6 +1497,9 @@ export {
1278
1497
  codexPreset,
1279
1498
  codexProfileArgs,
1280
1499
  codexRunArgs,
1500
+ codexRuntimeCheckArgs,
1501
+ codexRuntimeCheckJudge,
1502
+ codexRuntimeCheckWorkdir,
1281
1503
  codexServerNameAddressable,
1282
1504
  deniedAncestorOf,
1283
1505
  inexpressibleDenyPaths,
@@ -1288,6 +1510,7 @@ export {
1288
1510
  presetNamed,
1289
1511
  presetNames,
1290
1512
  readDenyRules,
1513
+ runRuntimeCheck,
1291
1514
  semverAtLeast,
1292
1515
  withoutParentSession,
1293
1516
  workdirPaths,