@f5-sales-demo/xcsh 21.20.0 → 21.21.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@f5-sales-demo/xcsh",
4
- "version": "21.20.0",
4
+ "version": "21.21.0",
5
5
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
6
6
  "homepage": "https://github.com/f5-sales-demo/xcsh",
7
7
  "author": "Can Boluk",
@@ -62,13 +62,13 @@
62
62
  },
63
63
  "dependencies": {
64
64
  "@agentclientprotocol/sdk": "1.3.0",
65
- "@f5-sales-demo/pi-agent-core": "21.20.0",
66
- "@f5-sales-demo/pi-ai": "21.20.0",
67
- "@f5-sales-demo/pi-natives": "21.20.0",
68
- "@f5-sales-demo/pi-resource-management": "21.20.0",
69
- "@f5-sales-demo/pi-tui": "21.20.0",
70
- "@f5-sales-demo/pi-utils": "21.20.0",
71
- "@f5-sales-demo/xcsh-stats": "21.20.0",
65
+ "@f5-sales-demo/pi-agent-core": "21.21.0",
66
+ "@f5-sales-demo/pi-ai": "21.21.0",
67
+ "@f5-sales-demo/pi-natives": "21.21.0",
68
+ "@f5-sales-demo/pi-resource-management": "21.21.0",
69
+ "@f5-sales-demo/pi-tui": "21.21.0",
70
+ "@f5-sales-demo/pi-utils": "21.21.0",
71
+ "@f5-sales-demo/xcsh-stats": "21.21.0",
72
72
  "@mozilla/readability": "^0.6",
73
73
  "@sinclair/typebox": "^0.34",
74
74
  "@xterm/headless": "^6.0",
@@ -4,6 +4,7 @@ import type { AssistantMessage } from "@f5-sales-demo/pi-ai";
4
4
  import type { ExtensionAPI, ExtensionContext, UserPromptKind } from "@f5-sales-demo/xcsh";
5
5
  import { HerdrClient } from "../../../herdr/client";
6
6
  import { finalAnswerText } from "../../../session/final-answer";
7
+ import { requestNativeLifecycleCancellation } from "./native-lifecycle-control";
7
8
 
8
9
  /**
9
10
  * herdr integration (bundled, default-on).
@@ -66,13 +67,19 @@ const SESSION_METHOD = "pane.report_agent_session";
66
67
  const HEARTBEAT_METHOD = "pane.report_agent_heartbeat";
67
68
  const RELEASE_METHOD = "pane.release_agent";
68
69
  const TURN_REPORT_METHOD = "agent.turn.report";
70
+ const TURN_ACTION_GET_METHOD = "agent.turn.action.get";
71
+ const TURN_ACTION_ACK_METHOD = "agent.turn.action.ack";
69
72
  const SOCKET_TIMEOUT_MS = 2000;
70
73
  const HEARTBEAT_INTERVAL_MS = 10_000;
71
74
  const PHASE_LABEL_TTL_MS = 60_000;
72
75
  const RESULT_MAX_CHARS = 80;
73
76
  const SEMANTIC_RESULT_MAX_BYTES = 8_000;
74
77
  const TURN_ENTRY_TYPE = "herdr.semantic-turn";
78
+ const ACTION_ENTRY_TYPE = "herdr.semantic-action";
75
79
  const EXECUTION_GENERATION_ENV = "HERDR_EXECUTION_GENERATION";
80
+ const NATIVE_CAPABILITY_ENV = "HERDR_NATIVE_CAPABILITY";
81
+ const ACTION_POLL_INTERVAL_MS = 250;
82
+ const ACTION_SAFE_POINT_TIMEOUT_MS = 30_000;
76
83
  const SETTLED_TURN_RECONCILE_DELAY_MS = 25;
77
84
  const PROMPT_BLOCKED_REASONS = {
78
85
  select: "selection required",
@@ -114,6 +121,30 @@ interface PersistedTurn {
114
121
  delivered?: boolean;
115
122
  }
116
123
 
124
+ interface PersistedAction {
125
+ executionId: string;
126
+ paneId: string;
127
+ sessionId: string;
128
+ turnId: string;
129
+ generation: number;
130
+ backendExecutionId: string;
131
+ actionId: "cancel";
132
+ actionRevision: 1;
133
+ state: "requested" | "safe_point" | "timed_out";
134
+ requestedAtUnixMs: number;
135
+ timedOutAtUnixMs?: number;
136
+ ackDelivered?: boolean;
137
+ }
138
+
139
+ interface NativeActionRecord {
140
+ backend_execution_id: string;
141
+ action_id: string;
142
+ action_revision: number;
143
+ state: "requested" | "safe_point" | "timed_out";
144
+ requested_at_unix_ms: number;
145
+ timed_out_at_unix_ms?: number;
146
+ }
147
+
117
148
  /**
118
149
  * A journal event is authenticated to one execution generation. The execution
119
150
  * backend, rather than the reporter, owns that value: guessing a generation
@@ -135,6 +166,11 @@ function executionBinding(paneId: string): { executionId: string; paneId: string
135
166
  return { executionId, paneId, generation };
136
167
  }
137
168
 
169
+ function nativeCapability(): string | undefined {
170
+ const value = process.env[NATIVE_CAPABILITY_ENV];
171
+ return typeof value === "string" && value.length > 0 ? value : undefined;
172
+ }
173
+
138
174
  function persistedTurns(ctx: ExtensionContext): PersistedTurn[] {
139
175
  try {
140
176
  const entries = ctx.sessionManager?.getEntries?.() as unknown[] | undefined;
@@ -174,6 +210,69 @@ function persistedTurns(ctx: ExtensionContext): PersistedTurn[] {
174
210
  }
175
211
  }
176
212
 
213
+ function persistedActions(ctx: ExtensionContext): PersistedAction[] {
214
+ try {
215
+ const entries = ctx.sessionManager?.getEntries?.() as unknown[] | undefined;
216
+ return (entries ?? []).flatMap(entry => {
217
+ if (typeof entry !== "object" || entry === null) return [];
218
+ const record = entry as Record<string, unknown>;
219
+ if (record.type !== "custom" || record.customType !== ACTION_ENTRY_TYPE) return [];
220
+ if (typeof record.data !== "object" || record.data === null) return [];
221
+ const action = record.data as Record<string, unknown>;
222
+ if (
223
+ typeof action.executionId !== "string" ||
224
+ typeof action.paneId !== "string" ||
225
+ typeof action.sessionId !== "string" ||
226
+ typeof action.turnId !== "string" ||
227
+ !Number.isSafeInteger(action.generation) ||
228
+ typeof action.backendExecutionId !== "string" ||
229
+ action.actionId !== "cancel" ||
230
+ action.actionRevision !== 1 ||
231
+ !Number.isSafeInteger(action.requestedAtUnixMs) ||
232
+ !["requested", "safe_point", "timed_out"].includes(String(action.state))
233
+ )
234
+ return [];
235
+ return [
236
+ {
237
+ executionId: action.executionId,
238
+ paneId: action.paneId,
239
+ sessionId: action.sessionId,
240
+ turnId: action.turnId,
241
+ generation: action.generation as number,
242
+ backendExecutionId: action.backendExecutionId,
243
+ actionId: "cancel" as const,
244
+ actionRevision: 1 as const,
245
+ state: action.state as PersistedAction["state"],
246
+ requestedAtUnixMs: action.requestedAtUnixMs as number,
247
+ ...(typeof action.timedOutAtUnixMs === "number" ? { timedOutAtUnixMs: action.timedOutAtUnixMs } : {}),
248
+ ackDelivered: action.ackDelivered === true,
249
+ },
250
+ ];
251
+ });
252
+ } catch {
253
+ return [];
254
+ }
255
+ }
256
+
257
+ function decodeNativeActions(result: Record<string, unknown>): NativeActionRecord[] {
258
+ if (result.type !== "agent_turn_action_list" || !Array.isArray(result.actions)) {
259
+ throw new Error("Herdr returned an invalid native action list");
260
+ }
261
+ return result.actions.flatMap(value => {
262
+ if (typeof value !== "object" || value === null) return [];
263
+ const action = value as Record<string, unknown>;
264
+ if (
265
+ typeof action.backend_execution_id !== "string" ||
266
+ action.action_id !== "cancel" ||
267
+ action.action_revision !== 1 ||
268
+ !["requested", "safe_point", "timed_out"].includes(String(action.state)) ||
269
+ !Number.isSafeInteger(action.requested_at_unix_ms)
270
+ )
271
+ return [];
272
+ return [action as unknown as NativeActionRecord];
273
+ });
274
+ }
275
+
177
276
  // Reused across calls for the life of the extension so `ensureProtocol()`'s
178
277
  // `ping` validation happens at most once per socket path, not once per frame.
179
278
  let cachedClient: HerdrClient | undefined;
@@ -272,6 +371,14 @@ export default function herdrReporter(pi: ExtensionAPI): void {
272
371
  // session anchor.
273
372
  let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
274
373
  let heartbeatActive = false;
374
+ let actionPollTimer: ReturnType<typeof setTimeout> | undefined;
375
+ let actionPolling = false;
376
+ let actionAfterRevision = 0;
377
+ let handledActionKey: string | undefined;
378
+ let nativeActionsEnabled = false;
379
+ let cancelAckGate: Promise<boolean> | undefined;
380
+ let resolveCancelAckGate: ((acknowledged: boolean) => void) | undefined;
381
+ let cancelAckDeadlineTimer: ReturnType<typeof setTimeout> | undefined;
275
382
  // Serializes frames: herdr compares `seq` across all methods for this source,
276
383
  // so frames must reach it in the order they were generated.
277
384
  let queue: Promise<void> = Promise.resolve();
@@ -313,11 +420,11 @@ export default function herdrReporter(pi: ExtensionAPI): void {
313
420
  );
314
421
  };
315
422
 
316
- const reportSemanticTurn = (
423
+ const reportSemanticTurn = async (
317
424
  state: "starting" | "working" | "waiting_input" | "completed" | "failed" | "cancelled" | "interrupted",
318
425
  options: { result?: string; reason?: string } = {},
319
- ): Promise<void> => {
320
- if (!executionBinding(paneId) || !activeSemanticTurn) return Promise.resolve();
426
+ ): Promise<boolean> => {
427
+ if (!executionBinding(paneId) || !activeSemanticTurn) return false;
321
428
  const revision = ++semanticRevision;
322
429
  const event: PersistedTurn = {
323
430
  ...activeSemanticTurn,
@@ -332,7 +439,7 @@ export default function herdrReporter(pi: ExtensionAPI): void {
332
439
  return deliverSemanticEvent(event);
333
440
  };
334
441
 
335
- const deliverSemanticEvent = (event: PersistedTurn): Promise<void> => {
442
+ const deliverSemanticEvent = async (event: PersistedTurn): Promise<boolean> => {
336
443
  const socketPath = process.env.HERDR_SOCKET_PATH;
337
444
  const binding = executionBinding(paneId);
338
445
  if (
@@ -344,9 +451,9 @@ export default function herdrReporter(pi: ExtensionAPI): void {
344
451
  event.eventRevision === undefined ||
345
452
  event.state === undefined
346
453
  ) {
347
- return Promise.resolve();
454
+ return false;
348
455
  }
349
- const frame = {
456
+ const baseFrame = {
350
457
  execution_id: event.executionId,
351
458
  pane_id: event.paneId,
352
459
  producer: HERDR_AGENT_LABEL,
@@ -358,7 +465,8 @@ export default function herdrReporter(pi: ExtensionAPI): void {
358
465
  ...(event.result === undefined ? {} : { result: event.result, result_digest: event.resultDigest }),
359
466
  ...(event.reason === undefined ? {} : { reason: event.reason }),
360
467
  };
361
- return enqueue(async () => {
468
+ let delivered = false;
469
+ await enqueue(async () => {
362
470
  const client = getHerdrClient(socketPath);
363
471
  try {
364
472
  await client.ensureProtocol();
@@ -366,13 +474,193 @@ export default function herdrReporter(pi: ExtensionAPI): void {
366
474
  onError(new Error("Herdr does not advertise agent_turn_journal; semantic tracking is degraded"));
367
475
  return;
368
476
  }
369
- await client.request<Record<string, unknown>>(TURN_REPORT_METHOD, frame);
477
+ const capability = nativeCapability();
478
+ const frame =
479
+ client.protocolVersion === 22 && capability
480
+ ? { ...baseFrame, native_capability: capability }
481
+ : baseFrame;
482
+ const response = await client.request<Record<string, unknown>>(TURN_REPORT_METHOD, frame);
483
+ if (client.protocolVersion === 22 && response.type !== "agent_turn") {
484
+ throw new Error("Herdr did not confirm the protocol-22 turn journal write");
485
+ }
370
486
  pi.appendEntry(TURN_ENTRY_TYPE, { ...event, delivered: true });
487
+ delivered = true;
371
488
  (latestContext as { ui?: ExtensionContext["ui"] } | undefined)?.ui?.setStatus("herdr-tracking", undefined);
372
489
  } catch (err) {
373
490
  onError(err);
374
491
  }
375
492
  });
493
+ return delivered;
494
+ };
495
+
496
+ const actionTarget = (action: PersistedAction): Record<string, unknown> | undefined => {
497
+ const capability = nativeCapability();
498
+ const binding = executionBinding(paneId);
499
+ if (
500
+ !capability ||
501
+ !binding ||
502
+ action.executionId !== binding.executionId ||
503
+ action.paneId !== binding.paneId ||
504
+ action.generation !== binding.generation
505
+ )
506
+ return undefined;
507
+ return {
508
+ execution_id: action.executionId,
509
+ pane_id: action.paneId,
510
+ producer: HERDR_AGENT_LABEL,
511
+ session_id: action.sessionId,
512
+ generation: action.generation,
513
+ native_capability: capability,
514
+ after_revision: 0,
515
+ };
516
+ };
517
+
518
+ const deliverActionAck = async (action: PersistedAction): Promise<boolean> => {
519
+ const socketPath = process.env.HERDR_SOCKET_PATH;
520
+ const target = actionTarget(action);
521
+ if (!socketPath || !target) return false;
522
+ try {
523
+ const client = getHerdrClient(socketPath);
524
+ await client.ensureProtocol();
525
+ if (client.protocolVersion !== 22) return false;
526
+ const response = await client.request<Record<string, unknown>>(TURN_ACTION_ACK_METHOD, {
527
+ ...target,
528
+ action_id: action.actionId,
529
+ action_revision: action.actionRevision,
530
+ state: "safe_point",
531
+ });
532
+ if (response.type !== "agent_turn_action" || typeof response.action !== "object" || response.action === null) {
533
+ throw new Error("Herdr returned an invalid native action acknowledgement");
534
+ }
535
+ const acknowledged = response.action as Record<string, unknown>;
536
+ if (
537
+ acknowledged.action_id !== action.actionId ||
538
+ acknowledged.action_revision !== action.actionRevision ||
539
+ acknowledged.state !== "safe_point" ||
540
+ acknowledged.turn_id !== action.turnId
541
+ ) {
542
+ throw new Error("Herdr acknowledged a different native action or turn");
543
+ }
544
+ pi.appendEntry(ACTION_ENTRY_TYPE, { ...action, state: "safe_point", ackDelivered: true });
545
+ return true;
546
+ } catch (err) {
547
+ onError(err);
548
+ return false;
549
+ }
550
+ };
551
+
552
+ const settleCancelGate = (acknowledged: boolean): void => {
553
+ if (cancelAckDeadlineTimer !== undefined) {
554
+ clearTimeout(cancelAckDeadlineTimer);
555
+ cancelAckDeadlineTimer = undefined;
556
+ }
557
+ resolveCancelAckGate?.(acknowledged);
558
+ resolveCancelAckGate = undefined;
559
+ };
560
+
561
+ const ensureCancelGate = (): void => {
562
+ if (cancelAckGate) return;
563
+ cancelAckGate = new Promise<boolean>(resolve => {
564
+ resolveCancelAckGate = resolve;
565
+ });
566
+ cancelAckDeadlineTimer = setTimeout(() => settleCancelGate(false), ACTION_SAFE_POINT_TIMEOUT_MS);
567
+ (cancelAckDeadlineTimer as { unref?: () => void }).unref?.();
568
+ };
569
+
570
+ const handleNativeAction = async (record: NativeActionRecord, ctx: ExtensionContext): Promise<void> => {
571
+ if (!activeSemanticTurn) return;
572
+ const action: PersistedAction = {
573
+ ...activeSemanticTurn,
574
+ backendExecutionId: record.backend_execution_id,
575
+ actionId: "cancel",
576
+ actionRevision: 1,
577
+ state: record.state,
578
+ requestedAtUnixMs: record.requested_at_unix_ms,
579
+ ...(record.timed_out_at_unix_ms === undefined ? {} : { timedOutAtUnixMs: record.timed_out_at_unix_ms }),
580
+ };
581
+ const actionKey = `${action.backendExecutionId}:${action.actionId}:${action.actionRevision}`;
582
+ if (record.state === "timed_out") {
583
+ pi.appendEntry(ACTION_ENTRY_TYPE, action);
584
+ actionAfterRevision = action.actionRevision;
585
+ settleCancelGate(false);
586
+ return;
587
+ }
588
+ ensureCancelGate();
589
+ if (handledActionKey !== actionKey) {
590
+ pi.appendEntry(ACTION_ENTRY_TYPE, { ...action, state: "requested", ackDelivered: false });
591
+ // This is the producer safe point: dismiss the actual managed UI prompt
592
+ // if one is open, then cooperatively abort the active AgentSession.
593
+ requestNativeLifecycleCancellation("Herdr native cancel action");
594
+ ctx.abort();
595
+ pi.appendEntry(ACTION_ENTRY_TYPE, { ...action, state: "safe_point", ackDelivered: false });
596
+ handledActionKey = actionKey;
597
+ }
598
+ const acknowledged = await deliverActionAck({ ...action, state: "safe_point", ackDelivered: false });
599
+ if (acknowledged) {
600
+ actionAfterRevision = action.actionRevision;
601
+ settleCancelGate(true);
602
+ }
603
+ };
604
+
605
+ const stopActionPolling = (): void => {
606
+ actionPolling = false;
607
+ if (actionPollTimer !== undefined) {
608
+ clearTimeout(actionPollTimer);
609
+ actionPollTimer = undefined;
610
+ }
611
+ };
612
+
613
+ const pollNativeActions = async (ctx: ExtensionContext): Promise<void> => {
614
+ const socketPath = process.env.HERDR_SOCKET_PATH;
615
+ const capability = nativeCapability();
616
+ const turn = activeSemanticTurn;
617
+ if (!actionPolling || !socketPath || !capability || !turn) return;
618
+ try {
619
+ const client = getHerdrClient(socketPath);
620
+ const result = await client.request<Record<string, unknown>>(TURN_ACTION_GET_METHOD, {
621
+ execution_id: turn.executionId,
622
+ pane_id: turn.paneId,
623
+ producer: HERDR_AGENT_LABEL,
624
+ session_id: turn.sessionId,
625
+ generation: turn.generation,
626
+ native_capability: capability,
627
+ after_revision: actionAfterRevision,
628
+ });
629
+ for (const action of decodeNativeActions(result)) await handleNativeAction(action, ctx);
630
+ } catch (err) {
631
+ onError(err);
632
+ } finally {
633
+ if (actionPolling && activeSemanticTurn) {
634
+ actionPollTimer = setTimeout(() => void pollNativeActions(ctx), ACTION_POLL_INTERVAL_MS);
635
+ (actionPollTimer as { unref?: () => void }).unref?.();
636
+ }
637
+ }
638
+ };
639
+
640
+ const startActionPolling = (ctx: ExtensionContext): void => {
641
+ if (actionPolling) return;
642
+ actionPolling = true;
643
+ void pollNativeActions(ctx);
644
+ };
645
+
646
+ const replayPersistedActionAcks = async (ctx: ExtensionContext): Promise<void> => {
647
+ const binding = executionBinding(paneId);
648
+ if (!binding || !nativeCapability()) return;
649
+ const latest = new Map<string, PersistedAction>();
650
+ for (const action of persistedActions(ctx)) {
651
+ if (
652
+ action.executionId !== binding.executionId ||
653
+ action.paneId !== binding.paneId ||
654
+ action.generation !== binding.generation
655
+ ) {
656
+ onError(new Error("Persisted Herdr action binding does not match this execution"));
657
+ continue;
658
+ }
659
+ latest.set(`${action.backendExecutionId}:${action.actionId}:${action.actionRevision}`, action);
660
+ }
661
+ for (const action of latest.values()) {
662
+ if (action.state === "safe_point" && !action.ackDelivered) await deliverActionAck(action);
663
+ }
376
664
  };
377
665
 
378
666
  const beginSemanticTurn = async (ctx: ExtensionContext): Promise<void> => {
@@ -383,8 +671,16 @@ export default function herdrReporter(pi: ExtensionAPI): void {
383
671
  activeSemanticTurn = { ...binding, sessionId, turnId: randomUUID() };
384
672
  semanticRevision = 0;
385
673
  pendingSemanticResult = "";
674
+ actionAfterRevision = 0;
675
+ handledActionKey = undefined;
676
+ cancelAckGate = undefined;
677
+ resolveCancelAckGate = undefined;
386
678
  pi.appendEntry(TURN_ENTRY_TYPE, { ...activeSemanticTurn, eventRevision: 0 });
387
- await reportSemanticTurn("starting");
679
+ const registered = await reportSemanticTurn("starting");
680
+ const socketPath = process.env.HERDR_SOCKET_PATH;
681
+ const client = socketPath ? getHerdrClient(socketPath) : undefined;
682
+ nativeActionsEnabled = registered && client?.protocolVersion === 22 && nativeCapability() !== undefined;
683
+ if (nativeActionsEnabled) startActionPolling(ctx);
388
684
  };
389
685
 
390
686
  const finishSemanticTurn = async (
@@ -392,8 +688,24 @@ export default function herdrReporter(pi: ExtensionAPI): void {
392
688
  options: { result?: string; reason?: string } = {},
393
689
  ): Promise<void> => {
394
690
  if (!activeSemanticTurn) return;
691
+ if (state !== "cancelled") stopActionPolling();
692
+ if (state === "cancelled" && nativeActionsEnabled) {
693
+ const acknowledged = cancelAckGate ? await cancelAckGate : false;
694
+ if (!acknowledged) {
695
+ state = "interrupted";
696
+ options = { reason: "XCSH cancelled outside an authenticated Herdr safe point" };
697
+ }
698
+ }
395
699
  await reportSemanticTurn(state, options);
700
+ stopActionPolling();
396
701
  activeSemanticTurn = undefined;
702
+ nativeActionsEnabled = false;
703
+ cancelAckGate = undefined;
704
+ resolveCancelAckGate = undefined;
705
+ if (cancelAckDeadlineTimer !== undefined) {
706
+ clearTimeout(cancelAckDeadlineTimer);
707
+ cancelAckDeadlineTimer = undefined;
708
+ }
397
709
  };
398
710
 
399
711
  const report = (state: "idle" | "working" | "blocked", message?: string): Promise<void> =>
@@ -571,7 +883,15 @@ export default function herdrReporter(pi: ExtensionAPI): void {
571
883
  onError(new Error("Persisted Herdr turn binding does not match this execution"));
572
884
  return false;
573
885
  });
886
+ // Replay turn reports first. Herdr may have journaled revision 1 and lost
887
+ // the reply before confirming the cross-ledger native registration; the
888
+ // byte-identical starting replay repairs that gate before any action call.
574
889
  for (const event of events.filter(event => !event.delivered)) await deliverSemanticEvent(event);
890
+ // A safe point is persisted before its acknowledgement is attempted. If
891
+ // the response was lost (or the producer restarted), replay the identical
892
+ // authenticated ACK only after starting registration has been reconciled,
893
+ // and before emitting the restart interruption receipt.
894
+ await replayPersistedActionAcks(ctx);
575
895
  const last = events.at(-1);
576
896
  const terminal = last && ["completed", "failed", "cancelled", "interrupted"].includes(last.state ?? "");
577
897
  if (last && !terminal) {
@@ -751,6 +1071,7 @@ export default function herdrReporter(pi: ExtensionAPI): void {
751
1071
  // Relinquish pane authority so herdr stops showing xcsh once we exit.
752
1072
  pi.on("session_shutdown", async () => {
753
1073
  stopHeartbeat();
1074
+ stopActionPolling();
754
1075
  await finishSemanticTurn("interrupted", { reason: "XCSH shut down before semantic settlement" });
755
1076
  await send(RELEASE_METHOD, {
756
1077
  pane_id: paneId,
@@ -6,6 +6,20 @@ export const NATIVE_LIFECYCLE_CONTINUATION_TITLE = "Native lifecycle continuatio
6
6
 
7
7
  type NativeLifecycleControl = "await-user";
8
8
 
9
+ let activeManagedCancellation: ((reason: string) => void) | undefined;
10
+
11
+ /**
12
+ * Abort an acceptance prompt at its real ExtensionUIController signal boundary.
13
+ * The protocol-22 reporter also aborts the AgentSession through its current
14
+ * ExtensionContext; this hook only owns the interactive prompt that would
15
+ * otherwise remain open while the session cancellation unwinds.
16
+ */
17
+ export function requestNativeLifecycleCancellation(reason: string): boolean {
18
+ if (!activeManagedCancellation) return false;
19
+ activeManagedCancellation(reason);
20
+ return true;
21
+ }
22
+
9
23
  function configuredControl(pi: ExtensionAPI): NativeLifecycleControl | undefined {
10
24
  const value = pi.getFlag(NATIVE_LIFECYCLE_CONTROL_FLAG);
11
25
  return value === "await-user" ? value : undefined;
@@ -45,6 +59,10 @@ export default function nativeLifecycleControl(pi: ExtensionAPI): void {
45
59
  const controller = new AbortController();
46
60
  activeController = controller;
47
61
  activeContext = ctx;
62
+ const managedCancellation = (reason: string): void => {
63
+ controller.abort(reason);
64
+ };
65
+ activeManagedCancellation = managedCancellation;
48
66
  removeSigintInterceptor = postmortem.interceptSignal(postmortem.Reason.SIGINT, () => {
49
67
  onSigint();
50
68
  return true;
@@ -65,6 +83,7 @@ export default function nativeLifecycleControl(pi: ExtensionAPI): void {
65
83
  },
66
84
  };
67
85
  } finally {
86
+ if (activeManagedCancellation === managedCancellation) activeManagedCancellation = undefined;
68
87
  removeSigintInterceptor?.();
69
88
  removeSigintInterceptor = undefined;
70
89
  activeController = undefined;
@@ -73,6 +92,7 @@ export default function nativeLifecycleControl(pi: ExtensionAPI): void {
73
92
  });
74
93
 
75
94
  pi.on("session_shutdown", () => {
95
+ activeManagedCancellation = undefined;
76
96
  removeSigintInterceptor?.();
77
97
  removeSigintInterceptor = undefined;
78
98
  activeController?.abort("native lifecycle shutdown");
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { connect } from "node:net";
3
3
 
4
4
  export const HERDR_PROTOCOL_MIN_VERSION = 19;
5
- export const HERDR_PROTOCOL_MAX_VERSION = 20;
5
+ export const HERDR_PROTOCOL_MAX_VERSION = 22;
6
6
  const DEFAULT_TIMEOUT_MS = 5_000;
7
7
  const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
8
8
 
@@ -17,17 +17,17 @@ export interface BuildInfo {
17
17
  }
18
18
 
19
19
  export const BUILD_INFO: BuildInfo = {
20
- "version": "21.20.0",
21
- "commit": "f7b6a95e7675dbb7aa2f3d59617d17b3a497a0e1",
22
- "shortCommit": "f7b6a95",
20
+ "version": "21.21.0",
21
+ "commit": "1d087d1f95b4fd1cfebe3d6dcb1b156e8212733c",
22
+ "shortCommit": "1d087d1",
23
23
  "branch": "main",
24
- "tag": "v21.20.0",
25
- "commitDate": "2026-09-09T08:44:55+00:00",
26
- "buildDate": "2026-09-09T09:39:35.157Z",
24
+ "tag": "v21.21.0",
25
+ "commitDate": "2026-09-09T11:06:00+00:00",
26
+ "buildDate": "2026-09-09T12:00:55.126Z",
27
27
  "dirty": true,
28
28
  "prNumber": "",
29
29
  "repoUrl": "https://github.com/f5-sales-demo/xcsh",
30
30
  "repoSlug": "f5-sales-demo/xcsh",
31
- "commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/f7b6a95e7675dbb7aa2f3d59617d17b3a497a0e1",
32
- "releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.20.0"
31
+ "commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/1d087d1f95b4fd1cfebe3d6dcb1b156e8212733c",
32
+ "releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.21.0"
33
33
  };
@@ -49,7 +49,7 @@ export const EMBEDDED_DOCS: Readonly<Record<string, string>> = {
49
49
  "en/index.mdx": "---\ntitle: xcsh\ndescription: Independent open-source agentic shell for terminal work and F5 Distributed Cloud workflows.\ntemplate: splash\neditUrl: false\nhero:\n tagline: An agentic shell for terminal work, extensible automation, and reviewable F5 Distributed Cloud resource workflows.\n image:\n html: '<img src=\"/xcsh/images/xcsh-workflow.svg\" alt=\"Prompt, tools, and F5 Distributed Cloud workflow\" width=\"560\" height=\"360\" />'\n actions:\n - text: Install xcsh\n link: /xcsh/en/getting-started/installation/\n icon: right-arrow\n variant: primary\n - text: Run the quickstart\n link: /xcsh/en/getting-started/quickstart/\n icon: rocket\nsidebar:\n hidden: true\n order: 0\nhead:\n - tag: style\n content: >-\n .hero img { width: min(100%, 35rem); height: auto; filter: drop-shadow(0 1rem 2.5rem color-mix(in srgb, var(--sl-color-accent) 28%, transparent)); }\n .hero h1 { text-wrap: balance; }\n---\n\nxcsh combines an interactive coding agent with deterministic F5 Distributed Cloud resource commands. It is an independent open-source project, not an F5 product.\n\n## Where should I start?\n\n- New installation: [install xcsh](./getting-started/installation/), then run the [quickstart](./getting-started/quickstart/).\n- F5 Distributed Cloud change: select a [context and namespace](./f5-distributed-cloud/contexts-namespaces/), then [validate and diff](./f5-distributed-cloud/validate-diff/).\n- Existing session: review the [interactive shell](./use-xcsh/interactive-tui/) and [session controls](./use-xcsh/sessions-memory/).\n- Automation: choose a [headless mode](./automate-extend/headless-protocols/) or use the [software development kit (SDK)](./automate-extend/sdk/).\n",
50
50
  "en/integrations-deployment/chrome.mdx": "---\ntitle: \"Chrome\"\ndescription: \"Use the xcsh Chrome extension and native host with an isolated automation profile.\"\nsidebar:\n order: 3\n label: \"Chrome\"\n---\n\nThe Chrome integration connects xcsh to a browser session for supported console automation. The installed `xcsh chrome --help` output is the command authority.\n\n## What is the safe operating boundary?\n\nUse a dedicated profile and an authorized target. Confirm the visible account, uniform resource locator (URL), and object before an action that changes state. Prefer deterministic F5 Distributed Cloud resource commands whenever they cover the same operation.\n\n## Which Chrome capabilities does xcsh expose?\n\nThe `chrome` command inspects and arranges browser sessions, and `chrome-host` runs the native messaging host that connects the extension to the executable. Page-level interaction is driven by the browser tool inside a session rather than by a subcommand, so scope it with `--tools` in the same way as any other tool.\n",
51
51
  "en/integrations-deployment/containers.mdx": "---\ntitle: \"Containers\"\ndescription: \"Run the published multi-architecture Alpine image with explicit mounts and credentials.\"\nsidebar:\n order: 4\n label: \"Containers\"\n---\n\nThe published container packages xcsh for process isolation and repeatable deployment. It does not grant cloud credentials or filesystem access by itself.\n\n## How do I verify an image?\n\n```bash\ndocker pull ghcr.io/f5-sales-demo/xcsh:latest\ndocker run --rm ghcr.io/f5-sales-demo/xcsh:latest --version\n```\n\nPin a version tag or digest for automation. Mount only the task directory and inject credentials through the runtime's secret mechanism.\n\n## What must remain outside the image?\n\nKeep user contexts, provider tokens, and writable session data in explicit mounts or secret stores. Do not bake them into a derived layer.\n",
52
- "en/integrations-deployment/herdr.mdx": "---\ntitle: \"Integrate with Herdr\"\ndescription: \"Understand Herdr workspace launch, terminal actions, protocol negotiation, and isolation.\"\nsidebar:\n order: 5\n label: \"Herdr\"\n---\n\nHerdr support is optional and host-dependent. When the host does not provide it, xcsh terminal operation is unaffected.\n\n## How is the host protocol negotiated?\n\nThe integration checks the available socket protocol and media or graphics capabilities before it requests a workspace. Missing negotiation support leaves ordinary xcsh terminal operation intact.\n\n## How is a conversation-owned workspace launched?\n\nA workspace is tied to the conversation identity supplied at startup. Terminal-management actions create or address panes within that workspace, and lifecycle reporting stays anchored to the same startup context. Do not reuse an unrelated workspace merely because its socket is reachable.\n\n## How do I recover from socket failure?\n\nConnection and framing failures surface as integration diagnostics. The client must not open an inbound listener as a fallback. Close conversation-owned resources through the supported lifecycle and preserve unrelated Herdr workspaces.\n\n## What lifecycle state does xcsh publish?\n\nXCSH publishes native turn phases rather than inferring completion from terminal idleness or process exit. With Herdr protocol 20 and the advertised `agent_turn_journal` capability, a tracked execution publishes a persisted session/turn identity and a bounded semantic result to Herdr's durable journal. The existing 80-character metadata preview remains display-only and is never completion evidence.\nCommentary, prompt content, tool data, and failed or cancelled partial output are excluded.\n\n### External execution driver contract\n\nThe supported producer is the normal `xcsh` executable launched by Herdr's execution backend; it is not a mock or a no-provider/offline actor. For a journal-tracked invocation, that backend must inject the exact allocated `HERDR_EXECUTION_ID` and decimal safe-integer `HERDR_EXECUTION_GENERATION` into the child environment before it starts `xcsh`.\n\nXCSH never guesses a generation: without both values it retains ordinary pane lifecycle reporting but emits no semantic journal event. A continuation must be launched with its newly allocated generation.\n\nThe control/manager side owns translating `execution.cancel` to the child cancellation mechanism. XCSH then reports its native `cancelled` phase; asking a model to say it was cancelled is not a lifecycle event. Likewise, an input wait is only journaled after native `awaiting_user`, not from prose that asks a question.\n\nSession shutdown releases pane authority. It does not convert an unfinished turn into a successful completion.\n\n### Producer-native acceptance driver\n\n`xcsh lifecycle --json` prints the version 1 machine-readable producer contract. To execute a source or installed\nproducer check, supply a fresh absolute session directory, a normally configured model, and one scenario:\n\n```bash\nxcsh lifecycle --json \\\n --scenario await-continue \\\n --model openai-codex/gpt-5.6-luna \\\n --session-dir /absolute/fresh/xcsh-lifecycle-session\n```\n\nSupported scenarios are `success`, `failure`, `await-continue`, `cancel`, and `reply-loss-replay`. The driver first\nuses the prompt-free JSON session contract to persist one canonical 16-character lowercase hexadecimal session\nheader, then reopens that exact path in an ordinary interactive XCSH child. It generates a random mode-0600 fixture\nfor successful reads. `await-continue` pauses in the real `ExtensionUiController` input surface before the configured\nmodel runs; `cancel` sends SIGINT through `PtySession.interrupt()` and requires XCSH's native `cancelled` transition.\n\nThe reply-loss scenario owns a temporary local protocol-20 socket that acknowledges ordinary reporter traffic but\ndrops exactly one `agent.turn.report` reply. XCSH creates and persists the semantic event before transport, runs the\nconfigured provider and `read` tool, then a second XCSH process resumes the exact session path. The scenario passes\nonly when the reporter redelivers the byte-equivalent execution, pane, session, turn, generation, event revision, and\nstate fields. The socket never authors a lifecycle frame or substitutes an offline model.\n\nThe receipt's `evidenceClass` is `source_native_child`. This proves the measured source or executable behavior only;\nthe Control Manager remains responsible for its own admission, authenticated execution binding, generation changes,\nconsumer receipts, and installed-artifact acceptance. The command does not install or release XCSH or Herdr and does\nnot change normal launch defaults.\n\nThe verified contract is:\n\n| Concern | XCSH signal | Herdr disposition |\n| --- | --- | --- |\n| Session start and identity | Persisted native session ID/path | Herdr resume reference plus stable semantic session identity. |\n| Turn start/progress | Persisted UUID and normalized `turn_phase` | `starting`/`working` journal events with producer revision and server revision. |\n| Waiting for input/approval | `awaiting_user` and closed prompt kind | `waiting_input` with fixed safe reason; private prompt content is excluded. |\n| Successful completion | Settlement-aware `idle` after `agent_end` | `completed` with at most 8,000 UTF-8 bytes and a matching SHA-256 digest. |\n| Failure/cancellation | `error` or `cancelled` | Distinct terminal state and bounded safe reason; no partial result. |\n| Resume/fork | Session events and persisted custom turn entries | Resume preserves identity; unfinished recovered work becomes `interrupted`; fork has separate session lineage. |\n| Reconnect/order | Serialized queue and persisted event revision | Exact duplicates are idempotent; stale/conflicting revisions fail; terminal state is immutable. |\n| Application exit | `session_shutdown` | Active turn becomes `interrupted`, then pane authority is released; never success. |\n\nXCSH implementation is tracked by [issue #3768](https://github.com/f5-sales-demo/xcsh/issues/3768). The complete cross-project work packages and acceptance gates are in [Herdr native signaling gap-closing plan](../architecture-contribution/herdr-gap-closing-plan).\n\nHerdr lifecycle reconciliation is tracked by issue #5 in the F5 Herdr fork. Current source already recognizes the exact `(\"herdr:xcsh\", \"xcsh\")` resume pair; deployed build provenance and live resume/fork acceptance remain required before feature acceptance.\n",
52
+ "en/integrations-deployment/herdr.mdx": "---\ntitle: \"Integrate with Herdr\"\ndescription: \"Understand Herdr workspace launch, terminal actions, protocol negotiation, and isolation.\"\nsidebar:\n order: 5\n label: \"Herdr\"\n---\n\nHerdr support is optional and host-dependent. When the host does not provide it, xcsh terminal operation is unaffected.\n\n## How is the host protocol negotiated?\n\nThe integration checks the available socket protocol and media or graphics capabilities before it requests a workspace. Missing negotiation support leaves ordinary xcsh terminal operation intact.\n\n## How is a conversation-owned workspace launched?\n\nA workspace is tied to the conversation identity supplied at startup. Terminal-management actions create or address panes within that workspace, and lifecycle reporting stays anchored to the same startup context. Do not reuse an unrelated workspace merely because its socket is reachable.\n\n## How do I recover from socket failure?\n\nConnection and framing failures surface as integration diagnostics. The client must not open an inbound listener as a fallback. Close conversation-owned resources through the supported lifecycle and preserve unrelated Herdr workspaces.\n\n## What lifecycle state does xcsh publish?\n\nXCSH publishes native turn phases rather than inferring completion from terminal idleness or process exit. With Herdr protocol 20 or 22 and the advertised `agent_turn_journal` capability, a tracked execution publishes a persisted session/turn identity and a bounded semantic result to Herdr's durable journal. The existing 80-character metadata preview remains display-only and is never completion evidence.\nCommentary, prompt content, tool data, and failed or cancelled partial output are excluded.\n\n### External execution driver contract\n\nThe supported producer is the normal `xcsh` executable launched by Herdr's execution backend; it is not a mock or a no-provider/offline actor. For a journal-tracked invocation, that backend must inject the exact allocated `HERDR_EXECUTION_ID` and decimal safe-integer `HERDR_EXECUTION_GENERATION` into the child environment before it starts `xcsh`.\n\nXCSH never guesses a generation: without both values it retains ordinary pane lifecycle reporting but emits no semantic journal event. A continuation must be launched with its newly allocated generation.\n\nProtocol 22 adds producer-native controls. Herdr injects a one-time `HERDR_NATIVE_CAPABILITY` into the child. XCSH includes it only in authenticated turn-report and action requests; it is never written to the session journal, logs, diagnostics, or receipts.\nHerdr does not authorize actions until the first `starting` report has been durably journaled and bound to the owned PTY, pane, session, generation, and turn.\n\nThe producer wire shapes align with [Herdr PR #49](https://github.com/f5-sales-demo/herdr/pull/49) at cancellation-settlement commit `2c838cf545ed06439b4988cedb3e044f1d436264`, starting-replay recovery commit `edd5611cfd7685c0f069f244ceee0ac6c0a0678e`, and native-argv alignment commit `3397302960593a552fb37ceb71053cf99f2619a3`.\nThose commits are an integration contract under independent review, not released-backend evidence.\n\nAfter that registration, XCSH polls `agent.turn.action.get` with the same immutable provenance. A `cancel` action dismisses an active managed UI prompt and calls the real `AgentSession` abort path. XCSH persists the requested action and local safe point before sending the exact `agent.turn.action.ack`; it emits `cancelled` only after Herdr confirms that safe point.\nA lost ACK response is retried with the same action ID and revision, including after reporter restart. A backend `timed_out` action never triggers a late abort. PTY exit alone is not semantic cancellation.\n\nSession shutdown releases pane authority. It does not convert an unfinished turn into a successful completion.\n\n### Producer-native acceptance driver\n\n`xcsh lifecycle --json` prints the version 2 machine-readable producer contract. To execute a source or installed\nproducer check, supply a fresh absolute session directory, a normally configured model, and one scenario:\n\n```bash\nxcsh lifecycle --json \\\n --scenario await-continue \\\n --model openai-codex/gpt-5.6-luna \\\n --session-dir /absolute/fresh/xcsh-lifecycle-session\n```\n\nSupported scenarios are `success`, `failure`, `await-continue`, `cancel`, `managed-cancel`, `managed-working-cancel`, and `reply-loss-replay`. The driver first\nuses the prompt-free JSON session contract to persist one canonical 16-character lowercase hexadecimal session\nheader, then reopens that exact path in an ordinary interactive XCSH child. It generates a random mode-0600 fixture\nfor successful reads. `await-continue` pauses in the real `ExtensionUiController` input surface before the configured\nmodel runs; `cancel` sends SIGINT through `PtySession.interrupt()` and requires XCSH's native `cancelled` transition.\n`managed-cancel` uses a local protocol-22 control fixture to request the action and requires the executable child to\nacknowledge its safe point before its native `cancelled` report. That fixture validates the producer adapter only; it\nis not evidence for Herdr's durable action journal, manager generation replacement, or consumer deduplication.\n`managed-working-cancel` requests the same cooperative action after the real child reports `working`, without opening\nthe acceptance prompt, and verifies cancellation through the active `AgentSession` path.\n\nThe reply-loss scenario owns a temporary local protocol-20 socket that acknowledges ordinary reporter traffic but\ndrops exactly one `agent.turn.report` reply. XCSH creates and persists the semantic event before transport, runs the\nconfigured provider and `read` tool, then a second XCSH process resumes the exact session path. The scenario passes\nonly when the reporter redelivers the byte-equivalent execution, pane, session, turn, generation, event revision, and\nstate fields. The socket never authors a lifecycle frame or substitutes an offline model.\n\nThe receipt's `evidenceClass` is `source_native_child`. This proves the measured source or executable behavior only;\nthe Control Manager remains responsible for its own admission, authenticated execution binding, generation changes,\nconsumer receipts, and installed-artifact acceptance. The command does not install or release XCSH or Herdr and does\nnot change normal launch defaults.\n\nThe verified contract is:\n\n| Concern | XCSH signal | Herdr disposition |\n| --- | --- | --- |\n| Session start and identity | Persisted native session ID/path | Herdr resume reference plus stable semantic session identity. |\n| Turn start/progress | Persisted UUID and normalized `turn_phase` | `starting`/`working` journal events with producer revision and server revision. |\n| Waiting for input/approval | `awaiting_user` and closed prompt kind | `waiting_input` with fixed safe reason; private prompt content is excluded. |\n| Successful completion | Settlement-aware `idle` after `agent_end` | `completed` with at most 8,000 UTF-8 bytes and a matching SHA-256 digest. |\n| Failure/cancellation | `error` or `cancelled` | Distinct terminal state and bounded safe reason; no partial result. |\n| Managed cancellation | Persisted action receipt, Extension UI signal, and `AgentSession.abort()` | Authenticated `safe_point` precedes and is linked to the native `cancelled` report. |\n| Resume/fork | Session events and persisted custom turn entries | Resume preserves identity; unfinished recovered work becomes `interrupted`; fork has separate session lineage. |\n| Reconnect/order | Serialized queue and persisted event revision | Exact duplicates are idempotent; stale/conflicting revisions fail; terminal state is immutable. |\n| Application exit | `session_shutdown` | Active turn becomes `interrupted`, then pane authority is released; never success. |\n\nThe protocol-22 producer integration is tracked by [issue #3791](https://github.com/f5-sales-demo/xcsh/issues/3791); its lifecycle foundation is tracked by [issue #3768](https://github.com/f5-sales-demo/xcsh/issues/3768). The complete cross-project work packages and acceptance gates are in [Herdr native signaling gap-closing plan](../architecture-contribution/herdr-gap-closing-plan).\n\nHerdr lifecycle reconciliation is tracked by issue #5 in the F5 Herdr fork. Current source already recognizes the exact `(\"herdr:xcsh\", \"xcsh\")` resume pair; deployed build provenance and live resume/fork acceptance remain required before feature acceptance.\n",
53
53
  "en/integrations-deployment/index.mdx": "---\ntitle: \"Integrations and deployment\"\ndescription: \"Deploy xcsh in containers and connect the editor, browser, Office, and Herdr surfaces.\"\nsidebar:\n order: 0\n label: \"Overview\"\n---\n\nChoose an integration by host, authority, and lifecycle boundary.\n\n## Which integration fits?\n\n- [Containers](./containers/) for an isolated packaged runtime.\n- [VS Code](./vscode/), [Chrome](./chrome/), [Office](./office/), or [Herdr](./herdr/) only when that companion surface is installed and the task needs it.\n",
54
54
  "en/integrations-deployment/office.mdx": "---\ntitle: \"Microsoft Office task pane\"\ndescription: \"Serve or sideload the embedded task pane for Excel, Word, and PowerPoint.\"\nsidebar:\n order: 2\n label: \"Microsoft Office task pane\"\n---\n\nThe Office pane packages an xcsh sidebar for supported Excel, Word, and PowerPoint hosts. `xcsh office --help` describes the installed serve, print, and sideload actions.\n\n## Who owns the test surface?\n\nPackage tests own pane components, bridge messages, and host-independent state. Office-host integration tests own document application programming interfaces (APIs), sideloading, and task-pane lifecycle. A change that crosses the bridge requires both suites; a passing browser-style component test does not prove Word, Excel, or PowerPoint host behavior.\n\n## What must be running?\n\nThe pane build and its local bridge server must match the xcsh version used for the session. One active sidebar binds to one server session at a time.\n\n## Which host steps vary by platform?\n\nRibbon placement, the sideload mechanism, and trust prompts differ across Office on Windows, Office on macOS, and Office on the web. Read the sideload action from `xcsh office --help`, then follow the Microsoft sideloading procedure for the specific host you are targeting.\n",
55
55
  "en/integrations-deployment/vscode.mdx": "---\ntitle: \"VS Code\"\ndescription: \"Use the companion VS Code integration with the same xcsh model and session foundation.\"\nsidebar:\n order: 1\n label: \"VS Code\"\n---\n\nThe companion VS Code extension embeds an xcsh conversation in an editor workspace. Its extension manifest and source repository define the supported commands and distribution channel.\n\n## What carries over from the terminal?\n\nProvider configuration, model selection, session concepts, and workspace file boundaries follow the xcsh runtime. Open the intended workspace before starting a conversation.\n\n## Which behavior should I validate in the terminal?\n\nEditor menus and command palette entries belong to the extension host and change with its release. Reproduce runtime behavior with the command-line interface (CLI) first:\n\n1. Run the same prompt with `xcsh -p` in the workspace directory.\n2. Compare the model, provider, and tool set reported there with the editor session.\n3. Inspect the persisted session file rather than the editor transcript when an exact sequence matters.\n\nA difference between the two points at extension configuration, not at the agent loop.\n",
@@ -21,10 +21,18 @@ interface TurnAttempt {
21
21
  replyLost: boolean;
22
22
  }
23
23
 
24
+ interface ActionAttempt {
25
+ ordinal: number;
26
+ method: "agent.turn.action.get" | "agent.turn.action.ack";
27
+ params: Record<string, unknown>;
28
+ }
29
+
24
30
  interface ReporterTransport {
25
31
  socketPath: string;
26
32
  attempts: TurnAttempt[];
33
+ actionAttempts: ActionAttempt[];
27
34
  requests: string[];
35
+ requestCancel: () => void;
28
36
  waitFor: (predicate: (attempt: TurnAttempt) => boolean, afterOrdinal?: number) => Promise<TurnAttempt>;
29
37
  close: () => Promise<void>;
30
38
  }
@@ -51,9 +59,10 @@ export interface NativeLifecycleReceipt {
51
59
  status: "passed";
52
60
  evidenceClass: "source_native_child";
53
61
  fixture: { path: string; value: string };
54
- session: { id: string; path: string };
62
+ session: { id: string; path: string; headerSha256: string };
55
63
  childRuns: Array<{ exitCode?: number; cancelled: boolean; timedOut: boolean }>;
56
64
  turnAttempts: TurnAttempt[];
65
+ actionAttempts: ActionAttempt[];
57
66
  control: Record<string, unknown>;
58
67
  }
59
68
 
@@ -67,6 +76,11 @@ function sameTurnFrame(left: Record<string, unknown>, right: Record<string, unkn
67
76
  return JSON.stringify(left) === JSON.stringify(right);
68
77
  }
69
78
 
79
+ export function redactNativeLifecycleRequest(params: Record<string, unknown>): Record<string, unknown> {
80
+ const { native_capability: _nativeCapability, ...safe } = params;
81
+ return safe;
82
+ }
83
+
70
84
  export function currentXcshCommand(args: string[], argv = process.argv, execPath = process.execPath): string {
71
85
  const script = argv[1];
72
86
  const executable = path.basename(execPath).toLowerCase();
@@ -77,11 +91,12 @@ export function currentXcshCommand(args: string[], argv = process.argv, execPath
77
91
 
78
92
  async function startReporterTransport(
79
93
  directory: string,
80
- options: { loseFirstTurnReply: boolean },
94
+ options: { loseFirstTurnReply: boolean; managedCancel: boolean },
81
95
  ): Promise<ReporterTransport> {
82
96
  const socketPath = path.join(directory, `.native-lifecycle-${randomUUID()}.sock`);
83
97
  const attempts: TurnAttempt[] = [];
84
98
  const requests: string[] = [];
99
+ const actionAttempts: ActionAttempt[] = [];
85
100
  const sockets = new Set<net.Socket>();
86
101
  const waiters = new Set<{
87
102
  predicate: (attempt: TurnAttempt) => boolean;
@@ -91,6 +106,17 @@ async function startReporterTransport(
91
106
  }>();
92
107
  let handshakeComplete = false;
93
108
  let lostReply = false;
109
+ let cancellationRequested = false;
110
+ let cancellationAcknowledged = false;
111
+ let registeredTurnId: string | undefined;
112
+ const cancelAction = () => ({
113
+ backend_execution_id: "native-lifecycle-backend",
114
+ action_id: "cancel",
115
+ action_revision: 1,
116
+ state: cancellationAcknowledged ? "safe_point" : "requested",
117
+ requested_at_unix_ms: 1,
118
+ ...(cancellationAcknowledged ? { acknowledged_at_unix_ms: 2, turn_id: registeredTurnId } : {}),
119
+ });
94
120
 
95
121
  const publish = (attempt: TurnAttempt): void => {
96
122
  for (const waiter of waiters) {
@@ -118,7 +144,7 @@ async function startReporterTransport(
118
144
  if (request.method === "ping") {
119
145
  handshakeComplete = true;
120
146
  socket.end(
121
- `${JSON.stringify({ id: request.id, result: { type: "pong", protocol: 20, version: "native-lifecycle", capabilities: { agent_turn_journal: true } } })}\n`,
147
+ `${JSON.stringify({ id: request.id, result: { type: "pong", protocol: options.managedCancel ? 22 : 20, version: "native-lifecycle", capabilities: { agent_turn_journal: true } } })}\n`,
122
148
  );
123
149
  continue;
124
150
  }
@@ -129,6 +155,9 @@ async function startReporterTransport(
129
155
  continue;
130
156
  }
131
157
  if (request.method === "agent.turn.report" && isRecord(request.params)) {
158
+ if (request.params.state === "starting" && typeof request.params.turn_id === "string") {
159
+ registeredTurnId = request.params.turn_id;
160
+ }
132
161
  const replyLost = options.loseFirstTurnReply && !lostReply;
133
162
  lostReply ||= replyLost;
134
163
  const attempt = { ordinal: attempts.length + 1, params: request.params, replyLost };
@@ -138,6 +167,35 @@ async function startReporterTransport(
138
167
  socket.destroy();
139
168
  continue;
140
169
  }
170
+ if (options.managedCancel) {
171
+ socket.end(
172
+ `${JSON.stringify({ id: request.id, result: { type: "agent_turn", turn: {}, admitted: true } })}\n`,
173
+ );
174
+ continue;
175
+ }
176
+ }
177
+ if (options.managedCancel && request.method === "agent.turn.action.get" && isRecord(request.params)) {
178
+ actionAttempts.push({
179
+ ordinal: actionAttempts.length + 1,
180
+ method: request.method,
181
+ params: request.params,
182
+ });
183
+ socket.end(
184
+ `${JSON.stringify({ id: request.id, result: { type: "agent_turn_action_list", actions: cancellationRequested ? [cancelAction()] : [] } })}\n`,
185
+ );
186
+ continue;
187
+ }
188
+ if (options.managedCancel && request.method === "agent.turn.action.ack" && isRecord(request.params)) {
189
+ actionAttempts.push({
190
+ ordinal: actionAttempts.length + 1,
191
+ method: request.method,
192
+ params: request.params,
193
+ });
194
+ cancellationAcknowledged = true;
195
+ socket.end(
196
+ `${JSON.stringify({ id: request.id, result: { type: "agent_turn_action", action: cancelAction(), admitted: true } })}\n`,
197
+ );
198
+ continue;
141
199
  }
142
200
  socket.end(`${JSON.stringify({ id: request.id, result: {} })}\n`);
143
201
  }
@@ -155,7 +213,11 @@ async function startReporterTransport(
155
213
  return {
156
214
  socketPath,
157
215
  attempts,
216
+ actionAttempts,
158
217
  requests,
218
+ requestCancel: () => {
219
+ cancellationRequested = true;
220
+ },
159
221
  waitFor: (predicate, afterOrdinal = 0) => {
160
222
  const existing = attempts.find(attempt => attempt.ordinal > afterOrdinal && predicate(attempt));
161
223
  if (existing) return Promise.resolve(existing);
@@ -234,17 +296,25 @@ async function prepareFixture(options: NativeLifecycleDriverOptions): Promise<{
234
296
  return { path: fixturePath, value };
235
297
  }
236
298
 
237
- async function readCanonicalSession(sessionDir: string): Promise<{ id: string; path: string }> {
299
+ async function readCanonicalSession(sessionDir: string): Promise<{ id: string; path: string; headerSha256: string }> {
238
300
  const entries = await fs.readdir(sessionDir, { withFileTypes: true });
239
- const candidates: Array<{ id: string; path: string }> = [];
301
+ const candidates: Array<{ id: string; path: string; headerSha256: string }> = [];
240
302
  for (const entry of entries) {
241
303
  if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
242
304
  const sessionPath = path.join(sessionDir, entry.name);
243
- const first = (await fs.readFile(sessionPath, "utf8")).split("\n", 1)[0];
305
+ const contents = await fs.readFile(sessionPath);
306
+ const newline = contents.indexOf(0x0a);
307
+ if (newline < 0) continue;
308
+ const firstBytes = contents.subarray(0, newline + 1);
309
+ const first = firstBytes.subarray(0, -1).toString("utf8");
244
310
  if (!first) continue;
245
311
  const header = JSON.parse(first) as Record<string, unknown>;
246
312
  if (header.type === "session" && typeof header.id === "string" && /^[0-9a-f]{16}$/u.test(header.id)) {
247
- candidates.push({ id: header.id, path: sessionPath });
313
+ candidates.push({
314
+ id: header.id,
315
+ path: sessionPath,
316
+ headerSha256: createHash("sha256").update(firstBytes).digest("hex"),
317
+ });
248
318
  }
249
319
  }
250
320
  if (candidates.length !== 1) throw new Error(`Expected exactly one canonical session, found ${candidates.length}`);
@@ -300,6 +370,7 @@ export async function runNativeLifecycleAcceptance(
300
370
  const fixture = await prepareFixture(options);
301
371
  const transport = await startReporterTransport(options.sessionDir, {
302
372
  loseFirstTurnReply: options.scenario === "reply-loss-replay",
373
+ managedCancel: options.scenario === "managed-cancel" || options.scenario === "managed-working-cancel",
303
374
  });
304
375
  const executionId = `xcsh-native-${randomUUID()}`;
305
376
  const paneId = `native:${randomUUID()}`;
@@ -308,6 +379,9 @@ export async function runNativeLifecycleAcceptance(
308
379
  HERDR_SOCKET_PATH: transport.socketPath,
309
380
  HERDR_EXECUTION_ID: executionId,
310
381
  HERDR_EXECUTION_GENERATION: "0",
382
+ ...(options.scenario === "managed-cancel" || options.scenario === "managed-working-cancel"
383
+ ? { HERDR_NATIVE_CAPABILITY: randomBytes(32).toString("hex") }
384
+ : {}),
311
385
  };
312
386
  const childRuns: NativeLifecycleReceipt["childRuns"] = [];
313
387
  const control: Record<string, unknown> = {};
@@ -323,13 +397,27 @@ export async function runNativeLifecycleAcceptance(
323
397
  const session = await readCanonicalSession(options.sessionDir);
324
398
 
325
399
  let args = baseChildArgs(options, fixture, session.path);
326
- if (options.scenario === "await-continue" || options.scenario === "cancel") {
400
+ if (
401
+ options.scenario === "await-continue" ||
402
+ options.scenario === "cancel" ||
403
+ options.scenario === "managed-cancel"
404
+ ) {
327
405
  args = [...args, NATIVE_LIFECYCLE_CONTROL_FLAG, "await-user"];
328
406
  }
329
407
  if (options.scenario === "failure") args = [...args, "--api-key", "native-lifecycle-invalid-credential"];
330
408
  active = startChild(args, path.dirname(fixture.path), environment, timeoutMs);
409
+ if (options.scenario === "managed-working-cancel") {
410
+ const working = await withTimeout(transport.waitFor(stateIs("working")), timeoutMs, "working");
411
+ control.workingOrdinal = working.ordinal;
412
+ transport.requestCancel();
413
+ control.cancellation = "protocol22_cooperative_working_action";
414
+ }
331
415
 
332
- if (options.scenario === "await-continue" || options.scenario === "cancel") {
416
+ if (
417
+ options.scenario === "await-continue" ||
418
+ options.scenario === "cancel" ||
419
+ options.scenario === "managed-cancel"
420
+ ) {
333
421
  const waiting = await withTimeout(transport.waitFor(stateIs("waiting_input")), timeoutMs, "waiting_input");
334
422
  control.waitingOrdinal = waiting.ordinal;
335
423
  if (options.scenario === "await-continue") {
@@ -337,16 +425,25 @@ export async function runNativeLifecycleAcceptance(
337
425
  await Bun.sleep(25);
338
426
  active.pty.write("\r");
339
427
  control.continuation = "pty_input";
340
- } else {
428
+ } else if (options.scenario === "cancel") {
341
429
  active.pty.interrupt();
342
430
  control.cancellation = "pty_process_group_sigint";
431
+ } else {
432
+ transport.requestCancel();
433
+ control.cancellation = "protocol22_cooperative_action";
343
434
  }
344
435
  }
345
436
 
346
437
  const terminalAttempt = await withTimeout(transport.waitFor(terminal), timeoutMs, "terminal turn report");
347
438
  control.terminalOrdinal = terminalAttempt.ordinal;
348
439
  const expectedTerminal =
349
- options.scenario === "failure" ? "failed" : options.scenario === "cancel" ? "cancelled" : "completed";
440
+ options.scenario === "failure"
441
+ ? "failed"
442
+ : options.scenario === "cancel" ||
443
+ options.scenario === "managed-cancel" ||
444
+ options.scenario === "managed-working-cancel"
445
+ ? "cancelled"
446
+ : "completed";
350
447
  if (terminalAttempt.params.state !== expectedTerminal) {
351
448
  throw new Error(
352
449
  `Native child settled ${String(terminalAttempt.params.state)} instead of ${expectedTerminal}: ${active.outputTail()}`,
@@ -406,7 +503,14 @@ export async function runNativeLifecycleAcceptance(
406
503
  fixture,
407
504
  session,
408
505
  childRuns,
409
- turnAttempts: transport.attempts,
506
+ turnAttempts: transport.attempts.map(attempt => ({
507
+ ...attempt,
508
+ params: redactNativeLifecycleRequest(attempt.params),
509
+ })),
510
+ actionAttempts: transport.actionAttempts.map(attempt => ({
511
+ ...attempt,
512
+ params: redactNativeLifecycleRequest(attempt.params),
513
+ })),
410
514
  control,
411
515
  };
412
516
  } catch (error) {
@@ -5,12 +5,14 @@
5
5
  * reporter frames or supply an offline model: callers must provide a normally
6
6
  * configured model and inspect the child's JSON stream and session file.
7
7
  */
8
- export const NATIVE_LIFECYCLE_DRIVER_VERSION = 1;
8
+ export const NATIVE_LIFECYCLE_DRIVER_VERSION = 2;
9
9
  export const NATIVE_LIFECYCLE_SCENARIOS = [
10
10
  "success",
11
11
  "failure",
12
12
  "await-continue",
13
13
  "cancel",
14
+ "managed-cancel",
15
+ "managed-working-cancel",
14
16
  "reply-loss-replay",
15
17
  ] as const;
16
18
  export type NativeLifecycleScenario = (typeof NATIVE_LIFECYCLE_SCENARIOS)[number];
@@ -53,7 +55,10 @@ export function nativeLifecycleContract(): Record<string, unknown> {
53
55
  version: NATIVE_LIFECYCLE_DRIVER_VERSION,
54
56
  transport: "xcsh-json-session-v3",
55
57
  session_id: "^[0-9a-f]{16}$",
58
+ session_dir: "absolute directory containing the canonical JSONL session",
56
59
  session_path: "<session-dir>/<timestamp>_<session-id>.jsonl",
60
+ session_header_sha256: "SHA-256 of the exact first JSONL header line including its terminating LF byte",
61
+ model: "configured non-secret model identifier",
57
62
  child: {
58
63
  modes: { non_interactive: "json", pty: "interactive" },
59
64
  reduced_discovery_flags: ["--no-memories", "--no-skills", "--no-rules", "--no-mcp", "--no-lsp"],
@@ -61,10 +66,18 @@ export function nativeLifecycleContract(): Record<string, unknown> {
61
66
  controls: {
62
67
  resume: "--resume <exact-session-path>",
63
68
  cancel: "PtySession.interrupt() sends SIGINT to the native child process group",
69
+ managed_cancel:
70
+ "protocol 22 agent.turn.action.get/ack cooperatively aborts the active ExtensionUIController and AgentSession",
64
71
  await_user: "--native-lifecycle-control await-user uses the interactive ExtensionUiController",
65
72
  continuation: "write the continuation and Enter to the same native PTY",
66
73
  replay: "restart --resume <exact-session-path> with the same authenticated binding",
67
74
  },
75
+ reporter: {
76
+ protocol: 22,
77
+ capability_env: "HERDR_NATIVE_CAPABILITY",
78
+ capability_persistence: "never",
79
+ actions: ["cancel:1:requested", "cancel:1:safe_point", "cancel:1:timed_out"],
80
+ },
68
81
  scenarios: NATIVE_LIFECYCLE_SCENARIOS,
69
82
  };
70
83
  }