@f5-sales-demo/xcsh 21.19.5 → 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.19.5",
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.19.5",
66
- "@f5-sales-demo/pi-ai": "21.19.5",
67
- "@f5-sales-demo/pi-natives": "21.19.5",
68
- "@f5-sales-demo/pi-resource-management": "21.19.5",
69
- "@f5-sales-demo/pi-tui": "21.19.5",
70
- "@f5-sales-demo/pi-utils": "21.19.5",
71
- "@f5-sales-demo/xcsh-stats": "21.19.5",
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",
package/src/cli.ts CHANGED
@@ -73,6 +73,7 @@ const commands: CommandEntry[] = [
73
73
  syntax: { args: sandboxArgs, flags: sandboxFlags },
74
74
  },
75
75
  { name: "jupyter", load: () => import("./commands/jupyter").then(m => m.default) },
76
+ { name: "lifecycle", load: () => import("./commands/lifecycle").then(m => m.default) },
76
77
  { name: "manager", load: () => import("./commands/manager").then(m => m.default) },
77
78
  { name: "office", load: () => import("./commands/office").then(m => m.default) },
78
79
  { name: "plugin", load: () => import("./commands/plugin").then(m => m.default) },
@@ -0,0 +1,48 @@
1
+ import * as path from "node:path";
2
+ import { Command, Flags } from "@f5-sales-demo/pi-utils/cli";
3
+ import { nativeLifecycleContract } from "../lifecycle/native-acceptance";
4
+ import {
5
+ NATIVE_LIFECYCLE_SCENARIOS,
6
+ type NativeLifecycleScenario,
7
+ runNativeLifecycleAcceptance,
8
+ } from "../lifecycle/native-acceptance-driver";
9
+
10
+ /** Print the versioned producer contract consumed by native lifecycle drivers. */
11
+ export default class Lifecycle extends Command {
12
+ static description = "Describe or execute the producer-native lifecycle acceptance driver";
13
+
14
+ static flags = {
15
+ json: Flags.boolean({ description: "Print the machine-readable contract", default: false }),
16
+ scenario: Flags.string({
17
+ description: `Execute one native scenario (${NATIVE_LIFECYCLE_SCENARIOS.join(", ")})`,
18
+ }),
19
+ model: Flags.string({ description: "Normally configured model used by the native child" }),
20
+ "session-dir": Flags.string({ description: "Fresh absolute directory for child sessions and fixtures" }),
21
+ continuation: Flags.string({ description: "PTY continuation label for await-continue" }),
22
+ timeout: Flags.integer({ description: "Scenario timeout in milliseconds", default: 90_000 }),
23
+ };
24
+
25
+ async run(): Promise<void> {
26
+ const { flags } = await this.parse(Lifecycle);
27
+ if (!flags.json) throw new Error("xcsh lifecycle requires --json");
28
+ if (!flags.scenario) {
29
+ process.stdout.write(`${JSON.stringify(nativeLifecycleContract())}\n`);
30
+ return;
31
+ }
32
+ if (!NATIVE_LIFECYCLE_SCENARIOS.includes(flags.scenario as NativeLifecycleScenario)) {
33
+ throw new Error(`Unsupported native lifecycle scenario: ${flags.scenario}`);
34
+ }
35
+ if (!flags.model) throw new Error("--model is required when --scenario is used");
36
+ if (!flags["session-dir"] || !path.isAbsolute(flags["session-dir"])) {
37
+ throw new Error("--session-dir must be an absolute path when --scenario is used");
38
+ }
39
+ const receipt = await runNativeLifecycleAcceptance({
40
+ scenario: flags.scenario as NativeLifecycleScenario,
41
+ model: flags.model,
42
+ sessionDir: flags["session-dir"],
43
+ timeoutMs: flags.timeout,
44
+ continuation: flags.continuation,
45
+ });
46
+ process.stdout.write(`${JSON.stringify(receipt)}\n`);
47
+ }
48
+ }
@@ -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> =>
@@ -545,6 +857,13 @@ export default function herdrReporter(pi: ExtensionAPI): void {
545
857
  startHeartbeat();
546
858
  await report("idle");
547
859
  await reportSession(ctx);
860
+ // An argv prompt can enter before_agent_start while the asynchronous
861
+ // session_start extension callback is still draining. In that case the
862
+ // reporter has already appended this process's revision-0/starting entries;
863
+ // treating those in-memory entries as restart residue would immediately
864
+ // interrupt the live turn. Startup replay is only for a process that has
865
+ // not begun a semantic turn of its own.
866
+ if (activeSemanticTurn) return;
548
867
  const persisted = persistedTurns(ctx);
549
868
  const byRevision = new Map<string, PersistedTurn>();
550
869
  for (const event of persisted) {
@@ -564,7 +883,15 @@ export default function herdrReporter(pi: ExtensionAPI): void {
564
883
  onError(new Error("Persisted Herdr turn binding does not match this execution"));
565
884
  return false;
566
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.
567
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);
568
895
  const last = events.at(-1);
569
896
  const terminal = last && ["completed", "failed", "cancelled", "interrupted"].includes(last.state ?? "");
570
897
  if (last && !terminal) {
@@ -744,6 +1071,7 @@ export default function herdrReporter(pi: ExtensionAPI): void {
744
1071
  // Relinquish pane authority so herdr stops showing xcsh once we exit.
745
1072
  pi.on("session_shutdown", async () => {
746
1073
  stopHeartbeat();
1074
+ stopActionPolling();
747
1075
  await finishSemanticTurn("interrupted", { reason: "XCSH shut down before semantic settlement" });
748
1076
  await send(RELEASE_METHOD, {
749
1077
  pane_id: paneId,
@@ -0,0 +1,102 @@
1
+ import { postmortem } from "@f5-sales-demo/pi-utils";
2
+ import type { ExtensionAPI, ExtensionContext } from "@f5-sales-demo/xcsh";
3
+
4
+ export const NATIVE_LIFECYCLE_CONTROL_FLAG = "--native-lifecycle-control";
5
+ export const NATIVE_LIFECYCLE_CONTINUATION_TITLE = "Native lifecycle continuation";
6
+
7
+ type NativeLifecycleControl = "await-user";
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
+
23
+ function configuredControl(pi: ExtensionAPI): NativeLifecycleControl | undefined {
24
+ const value = pi.getFlag(NATIVE_LIFECYCLE_CONTROL_FLAG);
25
+ return value === "await-user" ? value : undefined;
26
+ }
27
+
28
+ /**
29
+ * Explicit acceptance-only control loaded from the compiled XCSH bundle.
30
+ *
31
+ * The extension is inert unless its registered flag is present. It asks through
32
+ * the ordinary interactive ExtensionUiController, so TurnPhaseController and the
33
+ * bundled reporter observe the same awaiting-user boundary as any other native
34
+ * extension prompt. SIGINT aborts that prompt and the active AgentSession; it
35
+ * never manufactures a turn-phase or semantic-journal frame.
36
+ */
37
+ export default function nativeLifecycleControl(pi: ExtensionAPI): void {
38
+ pi.registerFlag(NATIVE_LIFECYCLE_CONTROL_FLAG, {
39
+ type: "string",
40
+ description: "Acceptance-only native lifecycle control (supported: await-user)",
41
+ });
42
+
43
+ let activeController: AbortController | undefined;
44
+ let activeContext: ExtensionContext | undefined;
45
+ let removeSigintInterceptor: (() => void) | undefined;
46
+
47
+ const onSigint = (): void => {
48
+ activeController?.abort("native lifecycle SIGINT");
49
+ activeContext?.abort();
50
+ };
51
+
52
+ pi.on("before_agent_start", async (_event, ctx) => {
53
+ if (configuredControl(pi) !== "await-user") return;
54
+ if (!ctx.hasUI) {
55
+ ctx.abort();
56
+ throw new Error("--native-lifecycle-control await-user requires interactive mode");
57
+ }
58
+
59
+ const controller = new AbortController();
60
+ activeController = controller;
61
+ activeContext = ctx;
62
+ const managedCancellation = (reason: string): void => {
63
+ controller.abort(reason);
64
+ };
65
+ activeManagedCancellation = managedCancellation;
66
+ removeSigintInterceptor = postmortem.interceptSignal(postmortem.Reason.SIGINT, () => {
67
+ onSigint();
68
+ return true;
69
+ });
70
+ try {
71
+ const continuation = await ctx.ui.input(NATIVE_LIFECYCLE_CONTINUATION_TITLE, "Enter the continuation label", {
72
+ signal: controller.signal,
73
+ });
74
+ if (continuation === undefined) {
75
+ ctx.abort();
76
+ return;
77
+ }
78
+ return {
79
+ message: {
80
+ customType: "native-lifecycle-continuation",
81
+ content: `Native lifecycle continuation: ${continuation}`,
82
+ display: false,
83
+ },
84
+ };
85
+ } finally {
86
+ if (activeManagedCancellation === managedCancellation) activeManagedCancellation = undefined;
87
+ removeSigintInterceptor?.();
88
+ removeSigintInterceptor = undefined;
89
+ activeController = undefined;
90
+ activeContext = undefined;
91
+ }
92
+ });
93
+
94
+ pi.on("session_shutdown", () => {
95
+ activeManagedCancellation = undefined;
96
+ removeSigintInterceptor?.();
97
+ removeSigintInterceptor = undefined;
98
+ activeController?.abort("native lifecycle shutdown");
99
+ activeController = undefined;
100
+ activeContext = undefined;
101
+ });
102
+ }
@@ -21,6 +21,7 @@ import { getAllPluginExtensionPaths } from "../plugins/loader";
21
21
  import { resolvePath } from "../utils";
22
22
  import herdrReporter from "./bundled/herdr-reporter";
23
23
  import herdrTerminal from "./bundled/herdr-terminal";
24
+ import nativeLifecycleControl from "./bundled/native-lifecycle-control";
24
25
  import sandboxGuard from "./bundled/sandbox-guard";
25
26
  import type {
26
27
  Extension,
@@ -501,6 +502,10 @@ async function discoverExtensionsInDir(dir: string): Promise<string[]> {
501
502
  */
502
503
  /** Extensions bundled with xcsh and loaded by default (before user extensions). */
503
504
  const BUNDLED_EXTENSIONS: ReadonlyArray<{ name: string; factory: ExtensionFactory }> = [
505
+ // First here means last after loadBundledExtensions' prepend. The reporter's
506
+ // before_agent_start handler must establish its semantic turn before this
507
+ // acceptance-only extension can pause inside the native UI prompt.
508
+ { name: "native-lifecycle-control", factory: nativeLifecycleControl },
504
509
  { name: "herdr-reporter", factory: herdrReporter },
505
510
  { name: "herdr-terminal", factory: herdrTerminal },
506
511
  { name: "sandbox-guard", factory: sandboxGuard },