@junghanacs/entwurf 0.13.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/AGENTS.md +5 -3
  2. package/BASELINE.md +57 -203
  3. package/CHANGELOG.md +19 -0
  4. package/CONTRIBUTING.md +1 -1
  5. package/DELIVERY.md +117 -261
  6. package/README.md +68 -408
  7. package/VERIFY.md +58 -87
  8. package/demo/README.md +1 -1
  9. package/docs/acp-backend-rail.md +231 -0
  10. package/docs/external-mcp-host.md +132 -0
  11. package/docs/fresh-cut-policy.md +99 -0
  12. package/docs/setup-clean-host.md +123 -328
  13. package/mcp/entwurf-bridge/dist/mcp/entwurf-bridge/src/index.js +21 -48
  14. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/acp-client.js +12 -0
  15. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/backend-adapter.js +11 -10
  16. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/config.js +1 -1
  17. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/engraving.js +42 -1
  18. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/models.js +4 -4
  19. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/overlay.js +3 -3
  20. package/mcp/entwurf-bridge/src/index.ts +21 -48
  21. package/package.json +12 -9
  22. package/pi-extensions/entwurf-control.ts +20 -49
  23. package/pi-extensions/lib/acp/acp-client.ts +22 -0
  24. package/pi-extensions/lib/acp/augment.ts +42 -3
  25. package/pi-extensions/lib/acp/backend-adapter.ts +12 -11
  26. package/pi-extensions/lib/acp/backend.ts +305 -36
  27. package/pi-extensions/lib/acp/config.ts +1 -1
  28. package/pi-extensions/lib/acp/engraving.ts +43 -1
  29. package/pi-extensions/lib/acp/event-mapper.ts +16 -13
  30. package/pi-extensions/lib/acp/models.ts +4 -4
  31. package/pi-extensions/lib/acp/overlay.ts +3 -3
  32. package/prompts/engraving.md +13 -5
  33. package/run.sh +244 -108
  34. package/scripts/check-acp-carrier-augment.ts +246 -10
  35. package/scripts/check-acp-cortex.ts +5 -5
  36. package/scripts/check-acp-prompt-lifecycle.ts +565 -0
  37. package/scripts/check-acp-sdk-surface.ts +60 -21
  38. package/scripts/check-acp-stop-reason.ts +342 -0
  39. package/scripts/check-entwurf-v2-surface.ts +41 -0
  40. package/scripts/check-gate-qualification.ts +6 -3
  41. package/scripts/check-probe-ordering.ts +39 -7
  42. package/scripts/check-release-gate-outcomes.ts +332 -0
  43. package/scripts/lib/live-skip.ts +33 -0
  44. package/scripts/lib/probe-acp-turn.ts +33 -12
  45. package/scripts/lib/step-outcome.sh +88 -0
  46. package/scripts/mutants/acp-augment.json +106 -0
  47. package/scripts/mutants/acp-cortex.json +2 -2
  48. package/scripts/mutants/acp-prompt-lifecycle.json +100 -0
  49. package/scripts/mutants/acp-stop-reason.json +80 -0
  50. package/scripts/mutants/probe-ordering.json +27 -5
  51. package/scripts/mutants/release-gate.json +105 -0
  52. package/scripts/mutants/v2-surface.json +26 -15
  53. package/scripts/smoke-acp-bundled-mcp-live.ts +4 -3
  54. package/scripts/smoke-acp-carrier-augment-live.ts +2 -2
  55. package/scripts/smoke-acp-cortex-live.ts +8 -14
  56. package/scripts/smoke-acp-long-turn-live.ts +185 -0
  57. package/scripts/smoke-acp-mcp-live.ts +2 -2
  58. package/scripts/smoke-acp-memory-containment-live.ts +2 -2
  59. package/scripts/smoke-acp-ordering-probe-live.ts +2 -2
  60. package/scripts/smoke-acp-overlay-live.ts +2 -2
  61. package/scripts/smoke-acp-provider-live.ts +2 -2
  62. package/scripts/smoke-acp-raw-turn-live.ts +3 -3
  63. package/scripts/smoke-acp-session-reuse-live.ts +2 -2
  64. package/scripts/smoke-acp-skill-live.ts +2 -2
  65. package/scripts/smoke-acp-socket-citizen-live.ts +4 -3
  66. package/scripts/smoke-acp-v2-send-live.ts +4 -3
  67. package/scripts/smoke-agy-native-push-live.ts +4 -3
  68. package/scripts/smoke-claude-native-resume-live.sh +13 -3
  69. package/scripts/smoke-entwurf-chain-live.ts +352 -0
  70. package/scripts/smoke-entwurf-v2-matrix-live.ts +2 -2
  71. package/scripts/smoke-entwurf-v2-spawn-resume-live.ts +2 -4
  72. package/scripts/smoke-meta-install-state.sh +4 -0
@@ -1,9 +1,10 @@
1
1
  // ACP backend adapter rail — the PRODUCT seam by which a curated model id selects
2
- // which ACP backend (claude / future backend / …) drives a turn. See docs/acp-backend-rail.md §9.
2
+ // which ACP backend (claude / future backend / …) drives a turn. See the adapter contract in
3
+ // docs/acp-backend-rail.md.
3
4
  //
4
5
  // This seam is DISTINCT from `AcpTurnDeps` (backend.ts), which is the test/runtime
5
- // seam (fake spawn/connection/clock for the gates). The two are kept apart on
6
- // purpose (GPT-agreed §9-2): merging them would make a fake-deps fixture look like
6
+ // seam (fake spawn/connection/clock for the gates). Merging them would make a
7
+ // fake-deps fixture look like
7
8
  // a fake backend and force the adapter to carry clock/sessionDir/createConnection.
8
9
  // The wiring is `defaultDeps(adapter)` — the turn loop in backend.ts stays
9
10
  // backend-invariant; only these per-backend functions change with `adapter`.
@@ -217,7 +218,7 @@ function resolveClaudeLaunch(): AcpLaunchSpec {
217
218
  export const claudeAdapter: AcpBackendAdapter = {
218
219
  backend: "claude",
219
220
 
220
- // Claude owns its UNPREFIXED curated ids only (GPT-agreed §9-1). The native id
221
+ // Claude owns its UNPREFIXED curated ids only (rail “Adapter contract”). The native id
221
222
  // equals the curated id — claude carries no curation prefix to strip.
222
223
  routeModel(modelId) {
223
224
  return SUPPORTED_CLAUDE_IDS.has(modelId) ? { nativeModelId: modelId } : undefined;
@@ -298,13 +299,13 @@ export const claudeAdapter: AcpBackendAdapter = {
298
299
  * adapters claim one id. */
299
300
  // ---------------------------------------------------------------------------
300
301
  // cortex adapter — Snowflake Cortex Code, the first non-claude backend on the
301
- // rail (docs/acp-backend-rail.md §4/§6). It adds ZERO to the common layer:
302
+ // rail (docs/acp-backend-rail.md, “Shipped adapters”). It adds ZERO to the common layer:
302
303
  // everything cortex-specific lives here + models.ts + overlay.ts + the gates.
303
304
  // ---------------------------------------------------------------------------
304
305
 
305
306
  const SUPPORTED_CORTEX_IDS: ReadonlySet<string> = new Set(SUPPORTED_CORTEX_MODEL_IDS);
306
307
 
307
- /** Cortex's OWN settings (§10 B): a Snowflake connection name, or null. Opaque to
308
+ /** Cortex's OWN settings: a Snowflake connection name, or null. Opaque to
308
309
  * config.ts / backend.ts — only cortexAdapter reads it (casting back). */
309
310
  export interface CortexAdapterSettings {
310
311
  cortexConnection: string | null;
@@ -318,7 +319,7 @@ export const CORTEX_CONNECTION_ENV = "ENTWURF_ACP_CORTEX_CONNECTION";
318
319
  export const cortexAdapter: AcpBackendAdapter = {
319
320
  backend: "cortex",
320
321
 
321
- // Cortex owns the reserved `cortex-` prefix (§9-1). routeModel strips it to the
322
+ // Cortex owns the reserved `cortex-` prefix (rail “Adapter contract”). routeModel strips it to the
322
323
  // native id: `cortex-auto` → "auto", `cortex-claude-sonnet-5` → "claude-sonnet-5".
323
324
  routeModel(modelId) {
324
325
  if (!SUPPORTED_CORTEX_IDS.has(modelId)) return undefined;
@@ -406,7 +407,7 @@ export const cortexAdapter: AcpBackendAdapter = {
406
407
  return { envOverrides: { HOME: overlay.home, SNOWFLAKE_HOME: overlay.snowflakeHome } };
407
408
  },
408
409
 
409
- // System-prompt-carrier-less (§9-4/§11-8): Cortex ACP exposes no
410
+ // System-prompt-carrier-less (ACP rail “Cortex Code audit”): Cortex ACP exposes no
410
411
  // `_meta.systemPrompt` and has no developer_instructions / GEMINI_SYSTEM_MD
411
412
  // equivalent. (It does READ `_meta` — a caller-session-id seam, measured but
412
413
  // unexplored and deliberately not part of this contract.) loadCarrier returns
@@ -438,7 +439,7 @@ export const cortexAdapter: AcpBackendAdapter = {
438
439
  await setConfig.call(connection, { sessionId: acpSessionId, configId: "model", value: nativeModelId });
439
440
  },
440
441
 
441
- // A connection change must invalidate a reused session (§4/§7). Flat,
442
+ // A connection change must invalidate a reused session (rail: Adapter contract). Flat,
442
443
  // sorted-stable primitive map; reads ONLY the opaque adapterSettings. `backend`
443
444
  // + `nativeModelId` are added by backend.ts.
444
445
  configSignatureFields(adapterSettings) {
@@ -452,7 +453,7 @@ const ADAPTERS: readonly AcpBackendAdapter[] = [claudeAdapter, cortexAdapter];
452
453
  /**
453
454
  * Resolve the backend adapter that owns `modelId`.
454
455
  *
455
- * GPT-agreed §9-1 fail-fast contract:
456
+ * Routing fail-fast contract (rail “Adapter contract”):
456
457
  * - 0 matches → throw (unknown model — no silent default).
457
458
  * - 2+ matches → throw (prefix collision — a startup-visible registry bug).
458
459
  *
@@ -476,7 +477,7 @@ export function resolveAcpBackendAdapter(modelId: string): { adapter: AcpBackend
476
477
  }
477
478
 
478
479
  /** Every curated model row across all registered adapters — for provider registration.
479
- * GPT-agreed §9-6 registration-time fail-fast: every curated id must route to EXACTLY
480
+ * Registration-time fail-fast (rail “Adapter contract”): every curated id must route to EXACTLY
480
481
  * one adapter and no id may be duplicated across adapters. Catching it here means a
481
482
  * prefix-collision / duplicate surfaces at provider registration, not mid-turn. */
482
483
  export function allCuratedModels(): AcpModelRow[] {
@@ -55,7 +55,7 @@ import {
55
55
  type ResolvedAcpConfig,
56
56
  resolveProviderConfig,
57
57
  } from "./config.js";
58
- import { buildAcpPrompt } from "./context.js";
58
+ import { type AcpTextBlock, buildAcpPrompt } from "./context.js";
59
59
  import {
60
60
  type AcpPiStreamState,
61
61
  applyAcpSessionUpdate,
@@ -78,10 +78,31 @@ import {
78
78
  } from "./session-store.js";
79
79
  import { assertExcludeToolsHonored, PI_BUILTIN_BACKED_TOOLS } from "./tool-surface.js";
80
80
 
81
+ // Bootstrap boundaries ONLY. initialize / newSession / set-model are handshake
82
+ // steps that make no model progress, so a stuck one is a dead session and a cold
83
+ // retry costs nothing — a wall-clock bound is honest there.
84
+ //
85
+ // There is deliberately NO prompt boundary. A running turn is not a failure for
86
+ // having taken long: tool use, reasoning, and provider queueing all legitimately
87
+ // outlive any number we could pick, and the previous 600s absolute cutoff killed
88
+ // turns that were still actively producing tool calls. Worse, the cutoff's own
89
+ // message ("prompt timed out after 600000ms") lands inside pi's transient-error
90
+ // dictionary (`RETRYABLE_PROVIDER_ERROR_PATTERN` in @earendil-works/pi-ai
91
+ // `utils/retry.ts` matches `timed? out` / `timeout`), so pi replayed the SAME
92
+ // full prompt from a cold ACP session up to `retry.maxRetries` times — paying the
93
+ // whole turn again to arrive at the same wall. Elapsed time is not evidence.
94
+ // A prompt now ends only on lifecycle events: it resolves, the operator aborts,
95
+ // or the child dies / its stdio ends (see awaitAcpPromptTurn).
81
96
  const INITIALIZE_TIMEOUT_MS = 30_000;
82
97
  const NEW_SESSION_TIMEOUT_MS = 30_000;
83
98
  const SET_MODEL_TIMEOUT_MS = 30_000;
84
- const PROMPT_TIMEOUT_MS = 600_000;
99
+
100
+ // Bounded CLEANUP window after a user abort — not a turn deadline. On abort we
101
+ // send the ACP `session/cancel` notification and give the agent this long to
102
+ // answer the pending prompt with `cancelled` (the protocol's own ending, which
103
+ // maps to aborted). Only if it does not do so within the window do we escalate
104
+ // to process-group teardown, so an abort always returns promptly.
105
+ const ABORT_CANCEL_GRACE_MS = 5_000;
85
106
 
86
107
  type StdioChild = ChildProcessByStdio<Writable, Readable, Readable>;
87
108
 
@@ -121,6 +142,12 @@ export interface AcpTurnDeps {
121
142
  now(): string;
122
143
  /** Record dir override (tests). Defaults to the real session cache dir. */
123
144
  sessionDir?: string;
145
+ /**
146
+ * Post-abort cleanup grace (gates). Defaults to ABORT_CANCEL_GRACE_MS. This is
147
+ * the ONLY injectable clock left on the turn path and it bounds cleanup after
148
+ * an abort — never a running prompt.
149
+ */
150
+ abortGraceMs?: number;
124
151
  }
125
152
 
126
153
  // ---------------------------------------------------------------------------
@@ -147,6 +174,24 @@ interface BridgeSession {
147
174
  busy: boolean;
148
175
  /** Mutable per-turn router — see the CRITICAL note in the file header. */
149
176
  activePromptHandler?: (event: AcpBridgeEvent) => void;
177
+ /**
178
+ * The child's own dying words, SESSION-scoped on purpose. The stderr drain is
179
+ * installed once at spawn; keeping the buffer on the turn that spawned would
180
+ * leave every later reuse turn reporting a bare "ACP connection closed" with
181
+ * nothing to diagnose it by (observed 2026-07-30 on a live sonnet reuse turn).
182
+ */
183
+ stderrTail: string[];
184
+ /** How the child ended, once it has — folded into the prompt-phase error. */
185
+ exit?: { code: number | null; signal: NodeJS.Signals | null };
186
+ /** Set while a prompt is in flight so a child death can close it (awaitAcpPromptTurn). */
187
+ notifyChildGone?: (err: Error) => void;
188
+ /**
189
+ * We are tearing this child down ON PURPOSE (turn-scoped teardown, config
190
+ * drift, error/abort cleanup). Its exit is then expected, not news: without
191
+ * this flag every ordinary turn-scoped turn would announce its own routine
192
+ * teardown to the NEXT turn as if the session had died.
193
+ */
194
+ retiring?: boolean;
150
195
  }
151
196
 
152
197
  const bridgeSessions = new Map<string, BridgeSession>();
@@ -173,21 +218,78 @@ function registerGlobalCleanup(): void {
173
218
  });
174
219
  }
175
220
 
176
- /** A retained child died between turns: mark dead + drop from map + retained set. */
177
- function onChildGone(session: BridgeSession): void {
221
+ /**
222
+ * The child died: mark dead + drop from map + retained set, RECORD how it ended,
223
+ * and close any prompt that was waiting on it. Without that last step a
224
+ * mid-prompt death is only observable through the SDK's generic "ACP connection
225
+ * closed" rejection, which names neither the exit status nor the stderr.
226
+ */
227
+ function onChildGone(session: BridgeSession, exit?: { code: number | null; signal: NodeJS.Signals | null }): void {
178
228
  session.alive = false;
229
+ if (exit) session.exit = exit;
179
230
  if (bridgeSessions.get(session.key) === session) bridgeSessions.delete(session.key);
180
231
  retainedChildren.delete(session.child);
232
+ if (session.notifyChildGone) {
233
+ // A turn was waiting on this child — it reports the death itself.
234
+ session.notifyChildGone(childEndedError(session));
235
+ } else if (!session.retiring) {
236
+ // Died BETWEEN turns with no turn to fail and nobody tearing it down, so
237
+ // nobody has seen it. Without this the next turn would silently open a
238
+ // fresh child and read as an ordinary cold start, hiding that the backend
239
+ // session the operator was talking to is gone. A DELIBERATE teardown is
240
+ // excluded — announcing our own routine cleanup would be noise, not news.
241
+ unreportedChildEnds.set(session.key, session.exit ?? { code: null, signal: null });
242
+ }
243
+ }
244
+
245
+ /** Deaths no turn observed, keyed by sessionKey and announced once by the next turn. */
246
+ const unreportedChildEnds = new Map<string, { code: number | null; signal: NodeJS.Signals | null }>();
247
+
248
+ /** Read-and-clear: an unreported death is announced exactly once. */
249
+ function takeUnreportedChildEnd(
250
+ sessionKey: string,
251
+ ): { code: number | null; signal: NodeJS.Signals | null } | undefined {
252
+ const end = unreportedChildEnds.get(sessionKey);
253
+ if (end) unreportedChildEnds.delete(sessionKey);
254
+ return end;
255
+ }
256
+
257
+ /** "exit code 1" / "signal SIGKILL" / "exit code 0, signal SIGTERM" / "no exit status". */
258
+ function describeChildEnd(exit?: { code: number | null; signal: NodeJS.Signals | null }): string {
259
+ if (!exit) return "no exit status";
260
+ const parts = [
261
+ exit.code !== null ? `exit code ${exit.code}` : undefined,
262
+ exit.signal ? `signal ${exit.signal}` : undefined,
263
+ ].filter(Boolean);
264
+ return parts.length > 0 ? parts.join(", ") : "no exit status";
265
+ }
266
+
267
+ /**
268
+ * The prompt-phase error for a child that died under a live turn.
269
+ *
270
+ * Wording is load-bearing: pi classifies a failed assistant message by matching
271
+ * its errorMessage against `RETRYABLE_PROVIDER_ERROR_PATTERN`, so anything we
272
+ * author here that reads like "timed out" / "timeout" / "terminated" /
273
+ * "connection lost" would put a full cold prompt replay back on the table. This
274
+ * text names the lifecycle fact and nothing that looks transient.
275
+ * (The appended backend stderr tail is the child's text, not ours.)
276
+ */
277
+ function childEndedError(session: BridgeSession): Error {
278
+ return new Error(
279
+ `entwurf: the ACP backend process ended while the prompt was still in flight (${describeChildEnd(session.exit)}) — ` +
280
+ "this turn has no answer",
281
+ );
181
282
  }
182
283
 
183
284
  // ---------------------------------------------------------------------------
184
285
  // timeout / launch / permission / stopReason / teardown helpers
185
286
  // ---------------------------------------------------------------------------
186
287
 
187
- // Race a promise against a timeout, ALWAYS clearing the timer afterwards. A
188
- // naive `Promise.race([p, sleep(ms)])` leaves the timer pending when `p` wins —
189
- // a dangling (here 10-minute) timer that keeps pi's event loop alive long after
288
+ // Race a BOOTSTRAP phase against its timeout, ALWAYS clearing the timer
289
+ // afterwards. A naive `Promise.race([p, sleep(ms)])` leaves the timer pending
290
+ // when `p` wins — a dangling timer that keeps pi's event loop alive long after
190
291
  // the turn, so pi would never exit a `-p` run. clearTimeout in finally fixes it.
292
+ // Only initialize / newSession / set-model use this; the prompt has no deadline.
191
293
  function withTimeout<T>(label: string, p: Promise<T>, ms: number): Promise<T> {
192
294
  let timer: ReturnType<typeof setTimeout> | undefined;
193
295
  const timeout = new Promise<never>((_, reject) => {
@@ -199,6 +301,80 @@ function withTimeout<T>(label: string, p: Promise<T>, ms: number): Promise<T> {
199
301
  });
200
302
  }
201
303
 
304
+ /**
305
+ * Await ONE ACP prompt with NO wall-clock deadline — the turn ends on lifecycle
306
+ * events only. Shared by the new and the reuse turn so both close the same way.
307
+ *
308
+ * The three endings:
309
+ *
310
+ * resolve the agent answered `session/prompt` (any stopReason — the
311
+ * verdict mapping is the caller's job).
312
+ * child gone the child exited or its stdio ended. Both are already fatal to
313
+ * the request — the SDK rejects every pending response when the
314
+ * read loop hits EOF — but the SDK's own error says only "ACP
315
+ * connection closed". `notifyChildGone` gets there first with the
316
+ * exit status, and the caller appends the session stderr tail.
317
+ * abort the operator cancelled. We send ACP `session/cancel` and let
318
+ * the agent end its own turn (`cancelled` → aborted). Escalation
319
+ * to process-group teardown happens only after a bounded grace,
320
+ * and closing the connection rejects the pending request, so an
321
+ * abort is always answered even against a wedged child.
322
+ *
323
+ * A stalled-but-alive child is deliberately NOT an ending: a silent turn is not
324
+ * a failed turn, and nothing here may kill one for being quiet.
325
+ */
326
+ async function awaitAcpPromptTurn(
327
+ session: BridgeSession,
328
+ promptArgs: { sessionId: string; prompt: AcpTextBlock[] },
329
+ opts: { signal?: AbortSignal; graceMs: number },
330
+ ): Promise<{ stopReason?: string }> {
331
+ let rejectLifecycle: ((err: Error) => void) | undefined;
332
+ const lifecycle = new Promise<never>((_, reject) => {
333
+ rejectLifecycle = reject;
334
+ });
335
+ // The race's loser stays pending forever when the prompt wins; a rejection
336
+ // nobody observed would surface as an unhandled rejection at that point.
337
+ lifecycle.catch(() => {});
338
+
339
+ let graceTimer: ReturnType<typeof setTimeout> | undefined;
340
+ const escalateAbort = (): void => {
341
+ killChildGroup(session.child, "SIGTERM");
342
+ // Closing rejects the still-pending ACP request, so the await below settles
343
+ // even when the child ignores both the cancel notification and the signal.
344
+ session.connection.close?.(new Error("entwurf: ACP prompt cancelled by the operator"));
345
+ rejectLifecycle?.(new Error("entwurf: the ACP prompt was cancelled by the operator"));
346
+ };
347
+ const onAbort = (): void => {
348
+ try {
349
+ session.connection.cancel?.({ sessionId: promptArgs.sessionId });
350
+ } catch {
351
+ // best-effort: escalation below is what guarantees the abort returns.
352
+ }
353
+ // NOT unref'd, deliberately. This timer is the only thing that finishes an
354
+ // abort against an agent that ignores session/cancel, so letting the event
355
+ // loop drain past it would leave the turn unsettled and the child alive.
356
+ // It is bounded (graceMs) and cleared in the finally below, so the worst it
357
+ // can do is hold an exiting process for that grace — which is the cleanup
358
+ // we asked for.
359
+ graceTimer = setTimeout(escalateAbort, opts.graceMs);
360
+ };
361
+
362
+ session.notifyChildGone = (err) => rejectLifecycle?.(err);
363
+ const signal = opts.signal;
364
+ if (signal) {
365
+ if (signal.aborted) onAbort();
366
+ else signal.addEventListener("abort", onAbort, { once: true });
367
+ }
368
+
369
+ try {
370
+ return await Promise.race([session.connection.prompt(promptArgs), lifecycle]);
371
+ } finally {
372
+ if (graceTimer) clearTimeout(graceTimer);
373
+ signal?.removeEventListener("abort", onAbort);
374
+ session.notifyChildGone = undefined;
375
+ }
376
+ }
377
+
202
378
  /** Approve-all permission policy (YOLO — oracle F). options empty → cancelled. */
203
379
  function resolvePermissionResponse(params: { options?: Array<{ optionId: string; kind?: string }> }): {
204
380
  outcome: { outcome: "selected"; optionId: string } | { outcome: "cancelled" };
@@ -209,15 +385,61 @@ function resolvePermissionResponse(params: { options?: Array<{ optionId: string;
209
385
  return { outcome: { outcome: "selected", optionId: (allow ?? options[0]).optionId } };
210
386
  }
211
387
 
212
- /** ACP prompt stopReason pi stopReason. */
213
- function mapPromptStopReason(stopReason: string | undefined): AssistantMessage["stopReason"] {
388
+ /** Verdict for one ACP prompt result what pi should report, and why. */
389
+ export type AcpStopVerdict = {
390
+ stopReason: AssistantMessage["stopReason"];
391
+ /** The raw ACP reason, preserved whenever the wire carried one. */
392
+ rawStopReason?: string;
393
+ /** Set exactly when `stopReason` is "error" — carries the reason into the UI. */
394
+ errorMessage?: string;
395
+ };
396
+
397
+ /**
398
+ * ACP prompt stopReason → pi verdict.
399
+ *
400
+ * The ACP terminal set is closed (`@agentclientprotocol/sdk` 1.3.0
401
+ * `schema/types.gen`): end_turn | max_tokens | max_turn_requests | refusal |
402
+ * cancelled. Only three of those are successful or benign ends. The previous
403
+ * implementation returned a bare StopReason with `default: "stop"`, which turned
404
+ * `refusal`, `max_turn_requests`, any future member, AND a missing reason into a
405
+ * clean successful turn — pi then rendered a silently truncated answer as if the
406
+ * model had finished. pi 0.83 closed the same hole in its own providers (#7272:
407
+ * unmapped terminal reasons surface as provider errors, never successful stops)
408
+ * and added `rawStopReason` so the wire value survives the mapping. This mirrors
409
+ * that contract rather than inventing a local one.
410
+ */
411
+ export function mapPromptStopReason(stopReason: string | undefined): AcpStopVerdict {
214
412
  switch (stopReason) {
413
+ case "end_turn":
414
+ return { stopReason: "stop", rawStopReason: stopReason };
215
415
  case "max_tokens":
216
- return "length";
416
+ return { stopReason: "length", rawStopReason: stopReason };
217
417
  case "cancelled":
218
- return "aborted";
418
+ return { stopReason: "aborted", rawStopReason: stopReason };
419
+ case "refusal":
420
+ return {
421
+ stopReason: "error",
422
+ rawStopReason: stopReason,
423
+ errorMessage: "ACP backend stopped with: refusal (the model declined to answer; the turn is incomplete)",
424
+ };
425
+ case "max_turn_requests":
426
+ return {
427
+ stopReason: "error",
428
+ rawStopReason: stopReason,
429
+ errorMessage:
430
+ "ACP backend stopped with: max_turn_requests (the backend's per-turn request budget was exhausted; the turn is incomplete)",
431
+ };
432
+ case undefined:
433
+ return {
434
+ stopReason: "error",
435
+ errorMessage: "ACP backend ended the turn without a stop reason",
436
+ };
219
437
  default:
220
- return "stop";
438
+ return {
439
+ stopReason: "error",
440
+ rawStopReason: stopReason,
441
+ errorMessage: `ACP backend stopped with an unrecognized reason: ${stopReason}`,
442
+ };
221
443
  }
222
444
  }
223
445
 
@@ -426,15 +648,30 @@ export function streamAcpTurn(
426
648
  };
427
649
  }
428
650
 
651
+ /**
652
+ * Seal the turn from the ACP prompt result. "Success" here means the RPC
653
+ * returned, not that the turn ended well — a returned `refusal` /
654
+ * `max_turn_requests` / unknown / absent reason is sealed as an error event,
655
+ * never a `done`. `rawStopReason` carries the wire value out either way.
656
+ */
429
657
  function finishSuccess(promptResult: { stopReason?: string }): void {
430
658
  finalizeAcpStreamState(state);
431
- const mapped = mapPromptStopReason(promptResult?.stopReason);
432
- if (signal?.aborted || mapped === "aborted") {
659
+ const verdict = mapPromptStopReason(promptResult?.stopReason);
660
+ if (verdict.rawStopReason !== undefined) state.output.rawStopReason = verdict.rawStopReason;
661
+ if (signal?.aborted || verdict.stopReason === "aborted") {
433
662
  state.output.stopReason = "aborted";
434
663
  stream.push({ type: "error", reason: "aborted", error: state.output });
664
+ } else if (verdict.stopReason === "error") {
665
+ state.output.stopReason = "error";
666
+ state.output.errorMessage = verdict.errorMessage;
667
+ stream.push({ type: "error", reason: "error", error: state.output });
435
668
  } else {
436
- state.output.stopReason = mapped;
437
- stream.push({ type: "done", reason: mapped === "length" ? "length" : "stop", message: state.output });
669
+ state.output.stopReason = verdict.stopReason;
670
+ stream.push({
671
+ type: "done",
672
+ reason: verdict.stopReason === "length" ? "length" : "stop",
673
+ message: state.output,
674
+ });
438
675
  }
439
676
  stream.end();
440
677
  }
@@ -601,6 +838,7 @@ export function streamAcpTurn(
601
838
  // connection + child so it is not orphaned in retainedChildren (GPT blocker 2).
602
839
  if (decision.path === "new" && existing) {
603
840
  existing.alive = false;
841
+ existing.retiring = true;
604
842
  if (bridgeSessions.get(sessionKey) === existing) bridgeSessions.delete(sessionKey);
605
843
  retainedChildren.delete(existing.child);
606
844
  existing.connection.close?.();
@@ -639,10 +877,23 @@ export function streamAcpTurn(
639
877
  try {
640
878
  if (signal?.aborted) throw new Error("aborted before launch");
641
879
 
880
+ // A backend session that died BETWEEN turns is announced here, before
881
+ // the bootstrap notice — otherwise this turn looks like an ordinary
882
+ // cold start and the operator never learns that the session they were
883
+ // talking to ended. Announced once (read-and-clear); the turn continues
884
+ // normally, since opening a fresh child for a NEW user turn is not a
885
+ // replay of anything.
886
+ const priorEnd = takeUnreportedChildEnd(sessionKey);
887
+ if (priorEnd) {
888
+ pushAcpLifecycleNotice(
889
+ state,
890
+ `previous ${adapter.backend} session ended between turns (${describeChildEnd(priorEnd)}) — opening a new one`,
891
+ );
892
+ }
642
893
  // S2f visibility: surface the otherwise-silent bootstrap so a slow
643
894
  // overlay/spawn/init does not read as a hang. Display-only (marked).
644
895
  pushAcpLifecycleNotice(state, `preparing ${adapter.backend} session`);
645
- // GPT §9-5: materialize the overlay first, then spawn with launchEnvDefaults
896
+ // Overlay ordering (rail “Adapter contract”): materialize the overlay first, then spawn with launchEnvDefaults
646
897
  // + overlay.envOverrides merged over process.env (defaultDeps spawnChild).
647
898
  // sessionKey is the AUTHORITATIVE per-session identity (resolveSessionKey:
648
899
  // opts.sessionId → PI_SESSION_ID → cwd) — a session-scoped overlay must
@@ -659,6 +910,11 @@ export function streamAcpTurn(
659
910
  if (stderrTail.length > 50) stderrTail.shift();
660
911
  });
661
912
 
913
+ // Abort during BOOTSTRAP (spawn → initialize → newSession → set-model):
914
+ // there is no prompt turn for the agent to cancel yet, so the child is
915
+ // simply torn down. This listener is handed off before the prompt —
916
+ // awaitAcpPromptTurn installs the protocol-cancel-first one for that
917
+ // window, and two live listeners would race SIGTERM against the cancel.
662
918
  if (signal) {
663
919
  onAbort = () => killChildGroup(spawned, "SIGTERM");
664
920
  signal.addEventListener("abort", onAbort, { once: true });
@@ -700,9 +956,15 @@ export function streamAcpTurn(
700
956
  alive: true,
701
957
  busy: true,
702
958
  activePromptHandler: undefined,
959
+ // SAME array the stderr drain above pushes into: the buffer outlives
960
+ // this turn with the session, so a later reuse turn can still report
961
+ // the child's dying words.
962
+ stderrTail,
703
963
  };
704
964
  const sess = session;
705
- spawned.once("exit", () => onChildGone(sess));
965
+ spawned.once("exit", (...args: unknown[]) =>
966
+ onChildGone(sess, { code: (args[0] as number | null) ?? null, signal: (args[1] as NodeJS.Signals) ?? null }),
967
+ );
706
968
  spawned.once("error", () => onChildGone(sess));
707
969
 
708
970
  await withTimeout(
@@ -730,7 +992,7 @@ export function streamAcpTurn(
730
992
  modelId: model.id,
731
993
  piSessionId: process.env.PI_SESSION_ID?.trim() || undefined,
732
994
  });
733
- // GPT §9-4: omit the `_meta` KEY entirely for a carrier-less backend
995
+ // Carrier-less shape (rail “Adapter contract”): omit the `_meta` KEY entirely for a carrier-less backend
734
996
  // (sessionMeta === undefined), not `_meta: undefined`.
735
997
  const newSessionArgs =
736
998
  sessionMeta === undefined
@@ -776,10 +1038,16 @@ export function streamAcpTurn(
776
1038
  // prompt could still sync-reject before the wire write; the next visible
777
1039
  // event after this is the backend's own first token / tool notice.
778
1040
  pushAcpLifecycleNotice(state, "sending prompt");
779
- const promptResult = await withTimeout(
780
- "prompt",
781
- connection.prompt({ sessionId: acpSessionId, prompt }),
782
- PROMPT_TIMEOUT_MS,
1041
+ // Hand the abort window over to the prompt driver: from here on an abort
1042
+ // is a protocol `session/cancel` first, teardown only after the grace.
1043
+ if (signal && onAbort) {
1044
+ signal.removeEventListener("abort", onAbort);
1045
+ onAbort = undefined;
1046
+ }
1047
+ const promptResult = await awaitAcpPromptTurn(
1048
+ session,
1049
+ { sessionId: acpSessionId, prompt },
1050
+ { signal, graceMs: deps.abortGraceMs ?? ABORT_CANCEL_GRACE_MS },
783
1051
  );
784
1052
 
785
1053
  session.activePromptHandler = undefined;
@@ -798,6 +1066,7 @@ export function streamAcpTurn(
798
1066
  unrefRetainedChild(spawned);
799
1067
  persistRecord(session, deps);
800
1068
  } else {
1069
+ session.retiring = true;
801
1070
  connection.close?.();
802
1071
  teardownChild(spawned);
803
1072
  }
@@ -811,11 +1080,12 @@ export function streamAcpTurn(
811
1080
  // error/abort → drop the (uncertain) session and close its child; an
812
1081
  // uncertain connection must never be reused (GPT ④).
813
1082
  if (child) {
1083
+ if (session) session.retiring = true;
814
1084
  retainedChildren.delete(child);
815
1085
  session?.connection.close?.(err);
816
1086
  teardownChild(child);
817
1087
  }
818
- finishError(err, aborted, stderrTail);
1088
+ finishError(err, aborted, session?.stderrTail ?? stderrTail);
819
1089
  } finally {
820
1090
  if (signal && onAbort) signal.removeEventListener("abort", onAbort);
821
1091
  }
@@ -823,7 +1093,6 @@ export function streamAcpTurn(
823
1093
 
824
1094
  // --- reuse: send only the latest user delta to the live ACP session
825
1095
  async function runReuseTurn(session: BridgeSession, ctxSigs: string[]): Promise<void> {
826
- let onAbort: (() => void) | undefined;
827
1096
  try {
828
1097
  if (signal?.aborted) throw new Error("aborted before prompt");
829
1098
 
@@ -832,10 +1101,6 @@ export function streamAcpTurn(
832
1101
  pushAcpLifecycleNotice(state, "reusing live session");
833
1102
  session.busy = true;
834
1103
  session.activePromptHandler = makePromptHandler(session);
835
- if (signal) {
836
- onAbort = () => killChildGroup(session.child, "SIGTERM");
837
- signal.addEventListener("abort", onAbort, { once: true });
838
- }
839
1104
 
840
1105
  // The live ACP session already remembers the prior turns → send only the
841
1106
  // latest user delta (re-sending the transcript would duplicate history).
@@ -844,10 +1109,12 @@ export function streamAcpTurn(
844
1109
 
845
1110
  // S2f visibility: about to send the delta to the resident child.
846
1111
  pushAcpLifecycleNotice(state, "sending prompt");
847
- const promptResult = await withTimeout(
848
- "prompt",
849
- session.connection.prompt({ sessionId: session.acpSessionId, prompt }),
850
- PROMPT_TIMEOUT_MS,
1112
+ // A reuse turn has no bootstrap window at all — the prompt driver owns
1113
+ // the whole abort surface (protocol cancel first, teardown after grace).
1114
+ const promptResult = await awaitAcpPromptTurn(
1115
+ session,
1116
+ { sessionId: session.acpSessionId, prompt },
1117
+ { signal, graceMs: deps.abortGraceMs ?? ABORT_CANCEL_GRACE_MS },
851
1118
  );
852
1119
 
853
1120
  session.activePromptHandler = undefined;
@@ -864,12 +1131,14 @@ export function streamAcpTurn(
864
1131
  session.busy = false;
865
1132
  // error/abort on a reused session → drop it and close the child (GPT ④).
866
1133
  if (bridgeSessions.get(session.key) === session) bridgeSessions.delete(session.key);
1134
+ session.retiring = true;
867
1135
  retainedChildren.delete(session.child);
868
1136
  session.connection.close?.(err);
869
1137
  teardownChild(session.child);
870
- finishError(err, aborted);
871
- } finally {
872
- if (signal && onAbort) signal.removeEventListener("abort", onAbort);
1138
+ // The SAME diagnostics a new turn reports. Without the session-scoped
1139
+ // tail a mid-turn child death on a resident session surfaced as a bare
1140
+ // "ACP connection closed" with nothing to read it by.
1141
+ finishError(err, aborted, session.stderrTail);
873
1142
  }
874
1143
  }
875
1144
 
@@ -23,7 +23,7 @@
23
23
  // the backend-invariant exclude-tools preflight and folds every one of them into
24
24
  // `bridgeConfigSignature` (so changing one still invalidates a reused cortex
25
25
  // session). Backend-OWNED settings never land here: they ride the opaque
26
- // `adapterSettings` seam (§10 B), which is what keeps a backend-named key like
26
+ // `adapterSettings` seam (rail “Adapter contract”), which is what keeps a backend-named key like
27
27
  // `cortexConnection` off this common shape.
28
28
  //
29
29
  // PURITY / SIGNATURE contract (NEXT oracle C / 핀1 / GPT `…2f9325` boost):