@cat-factory/executor-harness 1.96.0 → 1.100.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +5 -1
  2. package/dist/agent-capabilities.js +25 -11
  3. package/dist/agent-runner.d.ts +14 -1
  4. package/dist/agent-runner.js +84 -28
  5. package/dist/bootstrap-mode.js +1 -0
  6. package/dist/coding-agent.d.ts +2 -1
  7. package/dist/embed.d.ts +2 -1
  8. package/dist/embed.js +2 -1
  9. package/dist/failure.d.ts +19 -1
  10. package/dist/failure.js +40 -0
  11. package/dist/git.d.ts +6 -0
  12. package/dist/git.js +16 -9
  13. package/dist/inline.d.ts +6 -0
  14. package/dist/inline.js +6 -0
  15. package/dist/job.d.ts +2 -1
  16. package/dist/jsonl-stream.d.ts +70 -0
  17. package/dist/jsonl-stream.js +149 -0
  18. package/dist/pi-reduction.d.ts +136 -0
  19. package/dist/pi-reduction.js +303 -0
  20. package/dist/pi-workspace.d.ts +2 -1
  21. package/dist/pi-workspace.js +6 -1
  22. package/dist/pi.d.ts +8 -81
  23. package/dist/pi.js +124 -310
  24. package/dist/runner.d.ts +31 -0
  25. package/dist/runner.js +50 -3
  26. package/dist/structured-output.js +2 -1
  27. package/dist/tool-silence.d.ts +74 -0
  28. package/dist/tool-silence.js +99 -0
  29. package/package.json +4 -4
  30. package/src/agent-capabilities.ts +22 -13
  31. package/src/agent-runner.ts +100 -30
  32. package/src/agent.ts +1 -1
  33. package/src/bootstrap-mode.ts +2 -1
  34. package/src/coding-agent.ts +2 -1
  35. package/src/embed.ts +8 -5
  36. package/src/failure.ts +36 -9
  37. package/src/git.ts +17 -9
  38. package/src/inline.ts +6 -0
  39. package/src/job.ts +2 -1
  40. package/src/jsonl-stream.ts +149 -0
  41. package/src/pi-reduction.ts +359 -0
  42. package/src/pi-workspace.ts +7 -3
  43. package/src/pi.ts +144 -349
  44. package/src/runner.ts +91 -4
  45. package/src/structured-output.ts +2 -1
  46. package/src/tool-silence.ts +125 -0
package/dist/runner.d.ts CHANGED
@@ -5,6 +5,7 @@ import type { SliceReview } from './subagents.js';
5
5
  import type { ObservedMcpServer } from './agent-capabilities.js';
6
6
  import type { HarnessCallMetric, TodoProgress, ToolSpan } from './pi.js';
7
7
  import { type Logger } from './logger.js';
8
+ import { type ToolProgressWindow } from './tool-silence.js';
8
9
  import { type FailureCause } from './failure.js';
9
10
  /** Non-secret correlation fields a job carries on every log line (jobId, repo, branch, …). */
10
11
  type LogFields = Record<string, unknown>;
@@ -16,6 +17,22 @@ export interface RunOptions {
16
17
  onProgress?: (progress: TodoProgress) => void;
17
18
  /** Receives one compact {@link ToolSpan} per completed tool call (observability). */
18
19
  onSpan?: (span: ToolSpan) => void;
20
+ /**
21
+ * Opens the tool-silence window (stuck-run audit F13) for ONE agent stream, returning the
22
+ * handle that stream beats on every completed tool call and closes when it ends.
23
+ *
24
+ * Called by the agent-CLI runners themselves rather than by the phase marker, because the
25
+ * window is only meaningful while something able to RESET it is running and only the runner
26
+ * knows whether its CLI reports completed tool calls at all. A caller that runs no tool loop
27
+ * (the inline one-shot completion) simply does not forward this, which is a statement, not an
28
+ * omission: the run stays bounded by the inactivity and max-duration watchdogs, and a window
29
+ * nothing could ever beat would only be able to expire.
30
+ *
31
+ * Absent ⇒ no window is opened and this watchdog is silent for that work. It fails toward NOT
32
+ * killing on purpose: this audit exists as much to stop recovery machinery ending healthy runs
33
+ * as to bound wedged ones, and the wall-clock cap is underneath either way.
34
+ */
35
+ beginToolWindow?: () => ToolProgressWindow;
19
36
  /** Receives the forward-looking follow-up / question items the Coder streamed since the last poll. */
20
37
  onFollowUp?: (items: FollowUpLine[]) => void;
21
38
  /**
@@ -246,6 +263,20 @@ export interface RunnerLimits {
246
263
  * progress, which counts as activity). Set to 0 to disable.
247
264
  */
248
265
  coldStartMs: number;
266
+ /**
267
+ * Stuck-run audit F13: force-fail the job if a running agent stream completes no tool call for
268
+ * this long. The gap the other two watchdogs structurally cannot see — a model that keeps
269
+ * talking (or thinking out loud) resets the inactivity timer on every chunk while completing
270
+ * nothing, so the only remaining bound was the full wall-clock cap and the engine's
271
+ * ~70-minute poll budget behind it.
272
+ *
273
+ * Armed only for as long as a stream that REPORTS completed tool calls is running (see
274
+ * {@link RunOptions.beginToolWindow}), so the activity-silent stretches — clone, dependency
275
+ * install, push, a validation loop's check commands — are outside it by construction: they
276
+ * legitimately complete no tool calls, and they are bounded by their own per-command timeouts.
277
+ * Set to 0 to disable.
278
+ */
279
+ toolSilenceMs: number;
249
280
  }
250
281
  export declare function loadRunnerLimits(env?: NodeJS.ProcessEnv): RunnerLimits;
251
282
  /**
package/dist/runner.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { redactSecrets } from './redact.js';
2
2
  import { log } from './logger.js';
3
- import { failureCauseOf, inactivityAbortMessage, maxDurationAbortMessage, } from './failure.js';
3
+ import { ToolSilenceWatchdog } from './tool-silence.js';
4
+ import { failureCauseOf, inactivityAbortMessage, maxDurationAbortMessage, toolSilenceAbortMessage, } from './failure.js';
4
5
  function intEnv(value, fallback) {
5
6
  const n = value ? Number(value) : NaN;
6
7
  return Number.isFinite(n) && n > 0 ? n : fallback;
@@ -13,22 +14,43 @@ function intEnvAllowZero(value, fallback) {
13
14
  return Number.isFinite(n) && n >= 0 ? n : fallback;
14
15
  }
15
16
  export function loadRunnerLimits(env = process.env) {
17
+ const maxDurationMs = intEnv(env.JOB_MAX_DURATION_MS, 60 * 60_000);
18
+ const inactivityMs = intEnv(env.JOB_INACTIVITY_MS, 10 * 60_000);
16
19
  return {
17
20
  // 60 minutes: generous headroom for serious multi-file coding tasks while
18
21
  // still bounding a runaway container.
19
- maxDurationMs: intEnv(env.JOB_MAX_DURATION_MS, 60 * 60_000),
22
+ maxDurationMs,
20
23
  // 10 minutes of zero output is treated as hung (a single long LLM/tool call
21
24
  // is far shorter; Pi streams events as it works). The per-git command ceiling
22
25
  // (`GIT_TIMEOUT_MS` in git.ts) is DERIVED from this value — a fixed margin below
23
26
  // it — so a slow clone/push (which emits no activity events) always times out
24
27
  // with git's own clear reason rather than this watchdog's "likely hung" message,
25
28
  // for any configured window. See the invariant note in git.ts.
26
- inactivityMs: intEnv(env.JOB_INACTIVITY_MS, 10 * 60_000),
29
+ inactivityMs,
27
30
  // 2 minutes: comfortably longer than a warm agent's time-to-first-token yet far
28
31
  // under the 10-minute inactivity kill, so a truly output-less start is flagged early.
29
32
  coldStartMs: intEnvAllowZero(env.JOB_COLD_START_MS, 2 * 60_000),
33
+ toolSilenceMs: intEnvAllowZero(env.JOB_TOOL_SILENCE_MS, toolSilenceDefault(maxDurationMs, inactivityMs)),
30
34
  };
31
35
  }
36
+ /**
37
+ * The tool-silence window when the operator has not set one: HALF the configured wall-clock cap,
38
+ * DERIVED rather than a constant so lowering `JOB_MAX_DURATION_MS` tightens it too (a fixed
39
+ * 30 minutes would sit past the whole budget of a deployment that runs 20-minute jobs, i.e. be
40
+ * silently disabled).
41
+ *
42
+ * Floored at the inactivity window so the default never races the gone-quiet diagnostic more
43
+ * often than it has to. The floor is a sizing choice, NOT the thing that keeps the two watchdogs
44
+ * apart: they anchor on different events (the last completed tool call vs the last byte of
45
+ * output), so the tool-silence anchor is always the earlier of the two and equal windows would
46
+ * still have it firing first. What actually keeps this watchdog off a hang is the expiry test in
47
+ * {@link ToolSilenceWatchdog}, which fires only when output arrived DURING the window that
48
+ * elapsed — and which also holds for an operator who sets `JOB_TOOL_SILENCE_MS` below
49
+ * `JOB_INACTIVITY_MS`, where no default-side clamp applies at all.
50
+ */
51
+ function toolSilenceDefault(maxDurationMs, inactivityMs) {
52
+ return Math.max(Math.round(maxDurationMs / 2), inactivityMs);
53
+ }
32
54
  function toView(entry) {
33
55
  const { promise: _promise, spanBuffer: _spanBuffer, followUpBuffer: _followUpBuffer, callMetricBuffer: _callMetricBuffer, callMetricSeq: _callMetricSeq, abort: _abort, ...view } = entry;
34
56
  return { ...view };
@@ -224,6 +246,20 @@ export class JobRegistry {
224
246
  // spoken yet" test and, on a failure, the difference between a run that died mid-work and one
225
247
  // that never got going at all.
226
248
  let lastActivityAt;
249
+ // Stuck-run audit F13: the third watchdog, and the only one that can see a model which keeps
250
+ // TALKING while completing nothing — its output resets the inactivity timer on every chunk,
251
+ // and it is nowhere near the wall-clock cap. It is armed by the agent stream itself rather
252
+ // than by the phase marker (see `RunOptions.beginToolWindow`) and reads `lastActivityAt` at
253
+ // expiry, which is what keeps the gone-quiet case with the inactivity watchdog that owns it.
254
+ const toolSilence = new ToolSilenceWatchdog({
255
+ windowMs: this.limits.toolSilenceMs,
256
+ lastActivityAt: () => lastActivityAt,
257
+ onExpired: () => {
258
+ // First watchdog to fire wins the reason (see `resetInactivity` above).
259
+ killReason ??= 'no-tool-progress';
260
+ controller.abort(new Error('no tool progress'));
261
+ },
262
+ });
227
263
  // ADR 0026 D4: a one-shot cold-start watchdog. If the job produces no activity within
228
264
  // `coldStartMs`, record a structured diagnostic (a likely onboarding/auth wedge) so it
229
265
  // is legible early — it does NOT abort the run (the inactivity watchdog still owns
@@ -261,6 +297,7 @@ export class JobRegistry {
261
297
  entry.spanBuffer.push(span);
262
298
  lastTool = { name: span.tool, at: span.endedAt };
263
299
  },
300
+ beginToolWindow: () => toolSilence.open(),
264
301
  onFollowUp: (items) => {
265
302
  entry.followUpBuffer.push(...items);
266
303
  },
@@ -338,6 +375,7 @@ export class JobRegistry {
338
375
  clearTimeout(inactivity);
339
376
  clearTimeout(cap);
340
377
  clearTimeout(coldStart);
378
+ toolSilence.stop();
341
379
  entry.abort = undefined;
342
380
  entry.heartbeatAt = Date.now();
343
381
  }
@@ -376,6 +414,15 @@ export class JobRegistry {
376
414
  detail: redactSecrets(`Phase timings: ${phaseBreakdown || '(none)'}. ${breadcrumb}.${cold}`),
377
415
  };
378
416
  }
417
+ if (ctx.killReason === 'no-tool-progress') {
418
+ return {
419
+ // The breadcrumb carries the last completed tool, which is the whole diagnostic here:
420
+ // it names what the agent was doing when it stopped doing anything.
421
+ message: redactSecrets(`${toolSilenceAbortMessage(this.limits.toolSilenceMs)} (${breadcrumb})`),
422
+ cause: 'no-tool-progress',
423
+ detail: redactSecrets(`Phase timings: ${phaseBreakdown || '(none)'}. ${breadcrumb}.${cold}`),
424
+ };
425
+ }
379
426
  const raw = ctx.error instanceof Error ? ctx.error.message : String(ctx.error);
380
427
  // A thrown error tagged with a structured cause (a git op / an upstream API call) keeps
381
428
  // it; an untagged throw is a generic agent failure.
@@ -1,6 +1,7 @@
1
1
  import { redact, redactSecrets, secretsToRedact } from './redact.js';
2
2
  import { log } from './logger.js';
3
- import { PI_MAX_OUTPUT_TOKENS, phasedProxyBaseUrl } from './pi.js';
3
+ import { phasedProxyBaseUrl } from './pi.js';
4
+ import { PI_MAX_OUTPUT_TOKENS } from './pi-reduction.js';
4
5
  // A reusable abstraction for the "agent returns a structured JSON document as its
5
6
  // final assistant message" pattern (requirements, blueprint, merger — and any future
6
7
  // kind). An agent of this kind emits its result as text, not a tool call, and the
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The live window for ONE tool-reporting agent stream. Opened by the stream, beaten by each
3
+ * completed tool call, closed when the stream ends (cleanly or not) — so the window can never
4
+ * outlive the only thing able to reset it.
5
+ */
6
+ export interface ToolProgressWindow {
7
+ /** A tool call completed: the only evidence this watchdog accepts as progress. */
8
+ toolCompleted(): void;
9
+ /** The stream ended; the window closes with it. Idempotent. */
10
+ close(): void;
11
+ }
12
+ /**
13
+ * A window that measures nothing: what the watchdog hands out when disabled, and what a producer
14
+ * substitutes when its caller wired no watchdog at all. Having one means every producer holds a
15
+ * real window and states its tool progress unconditionally, rather than guarding each call site
16
+ * with a `?.` that reads as though beating the window were optional.
17
+ */
18
+ export declare const NO_TOOL_WINDOW: ToolProgressWindow;
19
+ export interface ToolSilenceDeps {
20
+ /** The window length. `<= 0` disables the watchdog entirely (every window is inert). */
21
+ windowMs: number;
22
+ /**
23
+ * When the run last produced ANY output, or undefined if it never has — the same clock the
24
+ * inactivity watchdog resets on. Read at EXPIRY (see {@link ToolSilenceWatchdog.open}), which
25
+ * is what keeps this watchdog off the gone-quiet case.
26
+ */
27
+ lastActivityAt: () => number | undefined;
28
+ /** Called when a window expires with the run demonstrably still talking. */
29
+ onExpired: () => void;
30
+ }
31
+ /**
32
+ * Hands out {@link ToolProgressWindow}s and fires `onExpired` for one that goes a full window
33
+ * without a completed tool call while the run keeps producing output.
34
+ *
35
+ * ONE window is open at a time (a job runs one agent stream at a time, and a repair loop runs
36
+ * them in sequence). Opening a second supersedes the first, and a superseded handle's calls are
37
+ * ignored rather than reaching back into the live window — a stale `close()` from a stream that
38
+ * finished after its successor started would otherwise disarm the watchdog for the rest of the job.
39
+ */
40
+ export declare class ToolSilenceWatchdog {
41
+ private readonly deps;
42
+ private timer;
43
+ /** Identity of the window currently open; every handout takes the next number. */
44
+ private openId;
45
+ /** When the live window was last armed — the start of the span `onExpired` is a verdict about. */
46
+ private armedAt;
47
+ constructor(deps: ToolSilenceDeps);
48
+ /** Open a window for one agent stream. Returns an inert handle when the watchdog is disabled. */
49
+ open(): ToolProgressWindow;
50
+ /** Disarm for good (the job settled). Safe to call with no window open. */
51
+ stop(): void;
52
+ private arm;
53
+ /**
54
+ * A window elapsed with no completed tool call. Fire ONLY if the run was talking through it.
55
+ *
56
+ * `no-tool-progress` claims something specific — output arrived, but nothing got done — and
57
+ * that is only a truthful reading when output actually arrived DURING the window that just
58
+ * expired. A window that passed in total silence is the INACTIVITY watchdog's fact, whose
59
+ * diagnostic ("the container went quiet") is the one an operator can act on; relabelling it as
60
+ * a rabbit-hole would send them looking at the model instead of at the hang.
61
+ *
62
+ * This is a structural guard, not a tie-breaker: the two timers anchor on different events (the
63
+ * last tool call vs the last byte of output), so no arithmetic between the two window LENGTHS
64
+ * can order them. Equal windows put the tool-silence anchor strictly earlier — it fires first —
65
+ * and an operator setting `JOB_TOOL_SILENCE_MS` below `JOB_INACTIVITY_MS` gets that on every
66
+ * quiet run. Deciding from what the expired window actually SAW is independent of both numbers.
67
+ *
68
+ * A deferred window re-arms rather than standing down, so a run that goes quiet and then
69
+ * resumes its monologue is still caught, one full window later. The deferral terminates:
70
+ * either output resumes (the next expiry has output in its window and fires) or it does not
71
+ * (inactivity fires).
72
+ */
73
+ private expire;
74
+ }
@@ -0,0 +1,99 @@
1
+ // The tool-silence watchdog (stuck-run audit F13): the third bound on a job, and the only one
2
+ // that can see a model which keeps TALKING while completing nothing. Its output resets the
3
+ // inactivity timer on every chunk, and it is nowhere near the wall-clock cap.
4
+ //
5
+ // WHY THIS IS ITS OWN MODULE — the window is only meaningful while something that REPORTS
6
+ // completed tool calls is running, and only that producer knows whether it does. Keying the
7
+ // window on the job's coarse phase label instead looked equivalent and was not: `agent` is a
8
+ // telemetry breadcrumb several call sites mark for several different things (a Codex pass, a
9
+ // tool-less inline completion, the label restored around a repair loop's shell commands), so a
10
+ // phase-armed window spent most of its time armed over work that could not possibly reset it.
11
+ // The producer opens its own window instead, which makes "armed" and "can beat" the same fact by
12
+ // construction rather than by two call sites agreeing.
13
+ /**
14
+ * A window that measures nothing: what the watchdog hands out when disabled, and what a producer
15
+ * substitutes when its caller wired no watchdog at all. Having one means every producer holds a
16
+ * real window and states its tool progress unconditionally, rather than guarding each call site
17
+ * with a `?.` that reads as though beating the window were optional.
18
+ */
19
+ export const NO_TOOL_WINDOW = { toolCompleted: () => { }, close: () => { } };
20
+ /**
21
+ * Hands out {@link ToolProgressWindow}s and fires `onExpired` for one that goes a full window
22
+ * without a completed tool call while the run keeps producing output.
23
+ *
24
+ * ONE window is open at a time (a job runs one agent stream at a time, and a repair loop runs
25
+ * them in sequence). Opening a second supersedes the first, and a superseded handle's calls are
26
+ * ignored rather than reaching back into the live window — a stale `close()` from a stream that
27
+ * finished after its successor started would otherwise disarm the watchdog for the rest of the job.
28
+ */
29
+ export class ToolSilenceWatchdog {
30
+ deps;
31
+ timer;
32
+ /** Identity of the window currently open; every handout takes the next number. */
33
+ openId = 0;
34
+ /** When the live window was last armed — the start of the span `onExpired` is a verdict about. */
35
+ armedAt = 0;
36
+ constructor(deps) {
37
+ this.deps = deps;
38
+ }
39
+ /** Open a window for one agent stream. Returns an inert handle when the watchdog is disabled. */
40
+ open() {
41
+ if (this.deps.windowMs <= 0)
42
+ return NO_TOOL_WINDOW;
43
+ const id = ++this.openId;
44
+ this.arm();
45
+ const live = () => this.openId === id;
46
+ return {
47
+ toolCompleted: () => {
48
+ if (live())
49
+ this.arm();
50
+ },
51
+ close: () => {
52
+ if (!live())
53
+ return;
54
+ // Retire the id as well as the timer, so a late `toolCompleted()` from this stream
55
+ // cannot re-arm a window whose producer has already gone.
56
+ this.openId++;
57
+ this.stop();
58
+ },
59
+ };
60
+ }
61
+ /** Disarm for good (the job settled). Safe to call with no window open. */
62
+ stop() {
63
+ clearTimeout(this.timer);
64
+ this.timer = undefined;
65
+ }
66
+ arm() {
67
+ clearTimeout(this.timer);
68
+ this.armedAt = Date.now();
69
+ this.timer = setTimeout(() => this.expire(), this.deps.windowMs);
70
+ }
71
+ /**
72
+ * A window elapsed with no completed tool call. Fire ONLY if the run was talking through it.
73
+ *
74
+ * `no-tool-progress` claims something specific — output arrived, but nothing got done — and
75
+ * that is only a truthful reading when output actually arrived DURING the window that just
76
+ * expired. A window that passed in total silence is the INACTIVITY watchdog's fact, whose
77
+ * diagnostic ("the container went quiet") is the one an operator can act on; relabelling it as
78
+ * a rabbit-hole would send them looking at the model instead of at the hang.
79
+ *
80
+ * This is a structural guard, not a tie-breaker: the two timers anchor on different events (the
81
+ * last tool call vs the last byte of output), so no arithmetic between the two window LENGTHS
82
+ * can order them. Equal windows put the tool-silence anchor strictly earlier — it fires first —
83
+ * and an operator setting `JOB_TOOL_SILENCE_MS` below `JOB_INACTIVITY_MS` gets that on every
84
+ * quiet run. Deciding from what the expired window actually SAW is independent of both numbers.
85
+ *
86
+ * A deferred window re-arms rather than standing down, so a run that goes quiet and then
87
+ * resumes its monologue is still caught, one full window later. The deferral terminates:
88
+ * either output resumes (the next expiry has output in its window and fires) or it does not
89
+ * (inactivity fires).
90
+ */
91
+ expire() {
92
+ const lastActivityAt = this.deps.lastActivityAt();
93
+ if (lastActivityAt === undefined || lastActivityAt <= this.armedAt) {
94
+ this.arm();
95
+ return;
96
+ }
97
+ this.deps.onExpired();
98
+ }
99
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cat-factory/executor-harness",
3
- "version": "1.96.0",
3
+ "version": "1.100.0",
4
4
  "description": "Container payload: a thin TypeScript wrapper that runs the Pi coding agent against a cloned repo and opens a PR. Runs in the Cloudflare Container (and, in local native mode, as a host process); carries no secrets.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -30,9 +30,9 @@
30
30
  "hono": "^4.13.0",
31
31
  "typescript": "7.0.2",
32
32
  "vitest": "^4.1.10",
33
- "@cat-factory/kernel": "0.264.0",
34
- "@cat-factory/server": "0.244.0",
35
- "@cat-factory/spend": "0.15.32"
33
+ "@cat-factory/kernel": "0.272.0",
34
+ "@cat-factory/server": "0.252.0",
35
+ "@cat-factory/spend": "0.15.40"
36
36
  },
37
37
  "scripts": {
38
38
  "build": "tsc -p tsconfig.json",
@@ -382,19 +382,28 @@ export const MCP_TOOL_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/
382
382
  * reached the container by any other route is held to the rule too.
383
383
  */
384
384
  export function isAllowedMcpHttpUrl(raw: string): boolean {
385
- const match = /^(https?):\/\/([^/?#]*)/i.exec(raw)
386
- if (!match) return false
387
- if (match[1]!.toLowerCase() === 'https') return true
388
- // Plain http from here: the host must be loopback. Strip userinfo FIRST and from the LAST `@`,
389
- // or `http://127.0.0.1@evil.example` reads as loopback while the request goes to evil.example.
390
- const authority = match[2]!
391
- const hostPort = authority.slice(authority.lastIndexOf('@') + 1)
392
- const closingBracket = hostPort.indexOf(']')
393
- const host = (
394
- hostPort.startsWith('[') && closingBracket !== -1
395
- ? hostPort.slice(1, closingBracket) // IPv6 literal, e.g. [::1]:8080
396
- : (hostPort.split(':')[0] ?? '')
397
- ).toLowerCase()
385
+ // ASCII control characters and the space are refused ANYWHERE rather than canonicalised: the
386
+ // WHATWG parser trims leading/trailing C0-and-space and removes tab, LF and CR from anywhere, so
387
+ // a url carrying one parses to something other than what it reads as, and this url is written
388
+ // VERBATIM into the CLI's MCP config below.
389
+ for (let i = 0; i < raw.length; i += 1) if (raw.charCodeAt(i) <= 0x20) return false
390
+ let parsed: URL
391
+ try {
392
+ parsed = new URL(raw)
393
+ } catch {
394
+ // silent-catch-ok: an unparseable url is exactly what this predicate refuses.
395
+ return false
396
+ }
397
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false
398
+ if (parsed.protocol === 'https:') return true
399
+ // Plain http from here: the host must be loopback. `new URL` rather than a hand-written parse
400
+ // because it is the parser the CLI resolves the request with, so the host ruled on is the host
401
+ // the credential header travels to. It strips userinfo from the LAST `@` (or
402
+ // `http://127.0.0.1@evil.example` reads as loopback while the request goes to evil.example), and
403
+ // it terminates the authority at a backslash as well as at `/?#` (or
404
+ // `http://evil.example\@127.0.0.1` reads as loopback the same way).
405
+ const hostname = parsed.hostname
406
+ const host = hostname.startsWith('[') ? hostname.slice(1, -1) : hostname
398
407
  return host === 'localhost' || host === '::1' || /^127\.\d+\.\d+\.\d+$/.test(host)
399
408
  }
400
409