@f5-sales-demo/xcsh 21.19.4 → 21.20.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/CHANGELOG.md CHANGED
@@ -48,6 +48,9 @@
48
48
 
49
49
  ### Fixed
50
50
 
51
+ - Kept `/login` honest after live validation by reporting reachable keyless vLLM services as
52
+ `keyless configured` and unreachable keyless services as `unreachable`
53
+ ([#3783](https://github.com/f5-sales-demo/xcsh/issues/3783)).
51
54
  - Made the session picker, extension dashboard, and debug-log viewer fullscreen and mouse-aware while
52
55
  retaining their keyboard behavior, pinned chrome, and non-action row semantics
53
56
  ([#3748](https://github.com/f5-sales-demo/xcsh/issues/3748)).
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.4",
4
+ "version": "21.20.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.4",
66
- "@f5-sales-demo/pi-ai": "21.19.4",
67
- "@f5-sales-demo/pi-natives": "21.19.4",
68
- "@f5-sales-demo/pi-resource-management": "21.19.4",
69
- "@f5-sales-demo/pi-tui": "21.19.4",
70
- "@f5-sales-demo/pi-utils": "21.19.4",
71
- "@f5-sales-demo/xcsh-stats": "21.19.4",
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",
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
+ }
@@ -545,6 +545,13 @@ export default function herdrReporter(pi: ExtensionAPI): void {
545
545
  startHeartbeat();
546
546
  await report("idle");
547
547
  await reportSession(ctx);
548
+ // An argv prompt can enter before_agent_start while the asynchronous
549
+ // session_start extension callback is still draining. In that case the
550
+ // reporter has already appended this process's revision-0/starting entries;
551
+ // treating those in-memory entries as restart residue would immediately
552
+ // interrupt the live turn. Startup replay is only for a process that has
553
+ // not begun a semantic turn of its own.
554
+ if (activeSemanticTurn) return;
548
555
  const persisted = persistedTurns(ctx);
549
556
  const byRevision = new Map<string, PersistedTurn>();
550
557
  for (const event of persisted) {
@@ -0,0 +1,82 @@
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
+ function configuredControl(pi: ExtensionAPI): NativeLifecycleControl | undefined {
10
+ const value = pi.getFlag(NATIVE_LIFECYCLE_CONTROL_FLAG);
11
+ return value === "await-user" ? value : undefined;
12
+ }
13
+
14
+ /**
15
+ * Explicit acceptance-only control loaded from the compiled XCSH bundle.
16
+ *
17
+ * The extension is inert unless its registered flag is present. It asks through
18
+ * the ordinary interactive ExtensionUiController, so TurnPhaseController and the
19
+ * bundled reporter observe the same awaiting-user boundary as any other native
20
+ * extension prompt. SIGINT aborts that prompt and the active AgentSession; it
21
+ * never manufactures a turn-phase or semantic-journal frame.
22
+ */
23
+ export default function nativeLifecycleControl(pi: ExtensionAPI): void {
24
+ pi.registerFlag(NATIVE_LIFECYCLE_CONTROL_FLAG, {
25
+ type: "string",
26
+ description: "Acceptance-only native lifecycle control (supported: await-user)",
27
+ });
28
+
29
+ let activeController: AbortController | undefined;
30
+ let activeContext: ExtensionContext | undefined;
31
+ let removeSigintInterceptor: (() => void) | undefined;
32
+
33
+ const onSigint = (): void => {
34
+ activeController?.abort("native lifecycle SIGINT");
35
+ activeContext?.abort();
36
+ };
37
+
38
+ pi.on("before_agent_start", async (_event, ctx) => {
39
+ if (configuredControl(pi) !== "await-user") return;
40
+ if (!ctx.hasUI) {
41
+ ctx.abort();
42
+ throw new Error("--native-lifecycle-control await-user requires interactive mode");
43
+ }
44
+
45
+ const controller = new AbortController();
46
+ activeController = controller;
47
+ activeContext = ctx;
48
+ removeSigintInterceptor = postmortem.interceptSignal(postmortem.Reason.SIGINT, () => {
49
+ onSigint();
50
+ return true;
51
+ });
52
+ try {
53
+ const continuation = await ctx.ui.input(NATIVE_LIFECYCLE_CONTINUATION_TITLE, "Enter the continuation label", {
54
+ signal: controller.signal,
55
+ });
56
+ if (continuation === undefined) {
57
+ ctx.abort();
58
+ return;
59
+ }
60
+ return {
61
+ message: {
62
+ customType: "native-lifecycle-continuation",
63
+ content: `Native lifecycle continuation: ${continuation}`,
64
+ display: false,
65
+ },
66
+ };
67
+ } finally {
68
+ removeSigintInterceptor?.();
69
+ removeSigintInterceptor = undefined;
70
+ activeController = undefined;
71
+ activeContext = undefined;
72
+ }
73
+ });
74
+
75
+ pi.on("session_shutdown", () => {
76
+ removeSigintInterceptor?.();
77
+ removeSigintInterceptor = undefined;
78
+ activeController?.abort("native lifecycle shutdown");
79
+ activeController = undefined;
80
+ activeContext = undefined;
81
+ });
82
+ }
@@ -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 },
@@ -17,17 +17,17 @@ export interface BuildInfo {
17
17
  }
18
18
 
19
19
  export const BUILD_INFO: BuildInfo = {
20
- "version": "21.19.4",
21
- "commit": "b291e0bd13af2a6210f33dc820ce9a2ebf36419b",
22
- "shortCommit": "b291e0b",
20
+ "version": "21.20.0",
21
+ "commit": "f7b6a95e7675dbb7aa2f3d59617d17b3a497a0e1",
22
+ "shortCommit": "f7b6a95",
23
23
  "branch": "main",
24
- "tag": "v21.19.4",
25
- "commitDate": "2026-09-09T03:22:46+00:00",
26
- "buildDate": "2026-09-09T04:17:49.325Z",
24
+ "tag": "v21.20.0",
25
+ "commitDate": "2026-09-09T08:44:55+00:00",
26
+ "buildDate": "2026-09-09T09:39:35.157Z",
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/b291e0bd13af2a6210f33dc820ce9a2ebf36419b",
32
- "releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.19.4"
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"
33
33
  };
@@ -17,7 +17,7 @@ export const EMBEDDED_DOCS: Readonly<Record<string, string>> = {
17
17
  "en/architecture-contribution/tui-runtime.mdx": "---\ntitle: \"TUI runtime\"\ndescription: \"Trace component contracts, differential rendering, terminal input, modal UI, and custom tool renderers.\"\nsidebar:\n order: 8\n label: \"TUI runtime\"\n---\n\nThe terminal user interface (TUI) renders session and runtime state through components. Components return terminal cells and semantic styles; the renderer computes a differential update instead of repainting unrelated rows.\n\n## How are input and rendering routed?\n\nTerminal decoding turns bytes and escape sequences into key events. Focused overlays receive input before the prompt editor and global actions. State changes schedule a render, layout produces the next frame, and the diff layer emits only changed terminal regions.\n\n## How do I extend interactive surfaces?\n\nExtensions can open a modal through `ctx.ui.custom` only when an interactive UI host exists. Custom tools may provide renderers for calls and results while preserving a plain-text representation for headless clients. A renderer must not become the only copy of durable tool output.\n\nRead `packages/tui/src` for the component and rendering contracts, and `packages/coding-agent/src/tui` for the session-aware components built on them.\n",
18
18
  "en/architecture-contribution/upstream-pi.mdx": "---\ntitle: \"Relationship to pi\"\ndescription: \"Understand what xcsh inherits from pi and where the project deliberately specializes.\"\nsidebar:\n order: 9\n label: \"Relationship to pi\"\n---\n\nxcsh is derived from the open-source pi coding agent and adds F5 Distributed Cloud resource workflows, integrations, packaging, and project-specific governance.\n\n## Which upstream range was reviewed?\n\nThe last proven sync with `can1357/oh-my-pi` was `d350ea60e` on April 9, 2026. The first-pass\nsecurity and shared-runtime audit reviewed the divergent line through `b2f25dbfe1` on September 5,\n2026. The second-pass TUI and renderer audit extends that lineage through the frozen tip\n`6d3bc569d16cd7351073eaa767caed51021befbb` on September 6, 2026.\nThe third-pass terminal-interaction audit extends the reviewed lineage through\n`a1b254047d12e143b7c6011536e918c6c35c5906`, also frozen on September 6, 2026.\nThe fourth-pass hyperlink, login-launch, and transcript-copy audit extends the reviewed lineage\nthrough `6e48b5ce564aa1d7eff60ffe92748f451385ad7d`, frozen on September 7, 2026.\nBecause the repositories no longer share a usable linear history, accepted changes are semantic\nports with adapted regressions rather than merges or ancestry-based cherry-picks.\n\n## Which changes were accepted?\n\nThe four implementation waves accepted these upstream pull requests:\n\n| Wave | Upstream pull requests | xcsh delivery |\n| --- | --- | --- |\n| Provider and prompt security | #2147, the opaque-thinking portion of #3239, #7067, and #8727 | #3710 |\n| Configuration and execution security | #7362 and #5636 | #3720 |\n| Core runtime | #7743, #10415, #10523, #10325, and #10550 | #3723 |\n| Terminal and platform | #10613, #10997, #10492, #9233, and #7634 | #3724 |\n| TUI and renderer crash containment | #1989, #4497, #4529, #2047, #5837, and #6788 | #3743 |\n| Herdr, signals, and mouse interaction | #7810, #8433, #11054, #4121, #3463, #3402, and #11045 | #3748 |\n| Hyperlinks, login launch, and copy picker | #10196, #10606, #11002, #10922, #11086, #5887, and #6282 | #3758 |\n\nThese ports protect provider-bound secrets and compaction boundaries, enforce exact-case\nenvironment references and complete protocol tails, repair Responses replay and shared MCP\nresults, improve rate-limit and retained-string behavior, chain directory completion, extend\npower assertions across supported platforms, and harden stats persistence and network exposure.\nThe source pull requests remain attributable to `can1357/oh-my-pi`; the xcsh deliveries link the\nexact commits and regression evidence.\n\nThe second-pass renderer work normalizes malformed task result data, accepts only strings at path\nboundaries, bounds ANSI-heavy rows before width measurement, and treats terminal disconnect\ncleanup as best effort before SIGHUP. Upstream #5438 is equivalent because `Container.render()`\nalready isolates child-render exceptions; its richer fallback display remains deferred.\n\nThe third-pass work adds a shared fullscreen/mouse framework, applies it to the session picker,\nextension dashboard, and debug-log viewer, and keeps terminal state restoration idempotent across\nnormal exit, resize, disconnect, and emergency cleanup. Herdr pane identity now participates in\nmultiplexer redraw decisions, while notifications use validated argv-only `herdr notification show`\ndelivery with terminal fallback. Interactive and signal exits share one draft-preserving teardown,\nand POSIX Ctrl-Z suspends only the xcsh process with `SIGSTOP`.\n\nThe fourth-pass work applies an immutable startup capability snapshot to `off`, `auto`, and\n`always` hyperlink policy; safely renders and physically wraps OSC 8 spans; launches local Vertex\nlogin through an HTTP(S)-only opener while retaining manual recovery; and projects the bounded copy\npicker directly from xcsh `SessionMessageEntry` history. The semantic ports correspond to upstream\nmerge commits `db2f55888b9f500b51010d7958a9cc8712e19f5c`,\n`4d13034f5dc70e93a6dad502ea7313792480760e`,\n`72767b81bd2911ebd650cfd0fdd5f92afc7470a6`,\n`4a56732e45c6b13b01e72aeaab113d0a257df0bd`,\n`43a2913d1ee2e88ceff0851a9ed9d0345f12d8c6`,\n`c081dedd3a696c872fd818f89d2b8c6c81a45b1e`, and\n`d1979782e7851b46451e956a5855d69e7781a5f5`.\n\n| Third-pass candidate | Disposition |\n| --- | --- |\n| Herdr #7810, #8433, and #11054 | Ported: scrollback-safe rendering, resize behavior, and notification delivery |\n| Herdr #10356 and #10479 | Equivalent: explicit `HERDR_KITTY_GRAPHICS` gating and synchronized rendering already cover the behavior |\n| Herdr #7554 | Not applicable: xcsh uses its compiled executable and dedicated launcher |\n| Signal #4121 (`73a12c7e`) | Ported: shared idempotent teardown and one-shot draft recovery |\n| Signal #3463 (`8506fbdf`) | Ported: interactive self-`SIGSTOP`; deliberate background process-group `SIGTSTP` remains unchanged |\n| Mouse #3402 and #11045 | Ported: shared SGR parsing/routing and horizontal-wheel rejection |\n| `cffb804d`, `27ed9f7a`, and log-viewer portion of `5fbe8876` | Ported to the session picker, extension dashboard, and debug-log viewer |\n| `7eca774c` and raw-SSE portion of `5fbe8876` | Not applicable: those surfaces do not exist in xcsh |\n| Plan Review `2976847e` | Deferred: xcsh retains its compact plan-review selector |\n| MCP, OpenCode, and unrelated renderer/UI changes | Excluded from this pass |\n\n## Where does xcsh deliberately diverge?\n\nxcsh retains its own:\n\n- F5-scoped packages, prompts-as-files, tool factories, and capability discovery;\n- SQLite multi-credential storage, multi-account authentication, and provider routing;\n- MCP, SSH, F5 Distributed Cloud, Office, and browser integrations;\n- Bun-first runtime, session semantics, release pipeline, branding, and governance.\n\nPublic interfaces use prerelease clean breaks. In this wave,\n`MacOSPowerAssertion`/`MacOSPowerAssertionOptions` became\n`PowerAssertion`/`PowerAssertionOptions` without aliases, and `power.sleepPrevention` was added with\nan `idle` default.\n\n## What remains excluded or deferred?\n\nUpstream workflows, branding, release machinery, generated model catalogs, compatibility shims,\nnew packages, and large unrelated subsystems are excluded. The security-scan subsystem in #7048\nand the native minimizer in #2176 remain deferred. The range-dashboard optimization in #9327 and\nearendil-works/pi-only fullscreen transcript, mouse, clipboard, and renderer subsystems also remain\noutside this campaign. MCP, OpenCode, Herdr, #10625, and #10491 were explicitly excluded from the\nsecond-pass batch; the Herdr work is now covered by the third pass. Commits after the new frozen\nsource tip require a later audit.\n\n## How do I decide where a fix belongs?\n\nTrace the affected module and compare it with the pinned upstream lineage. A generic agent-loop\ndefect may belong upstream; an xcsh resource command, integration, or packaging change belongs\nhere.\n\n## How do I preserve attribution?\n\nKeep upstream license notices and document imported changes. Avoid copying a patch blindly across\ndiverged modules; port the behavior with tests against the current xcsh architecture.\n",
19
19
  "en/automate-extend/extensions-custom-tools.mdx": "---\ntitle: \"Build extensions and custom tools\"\ndescription: \"Add TypeScript behavior, slash commands, providers, or schema-validated tools.\"\nsidebar:\n order: 3\n label: \"Build extensions and custom tools\"\n---\n\nExtensions load TypeScript behavior with `--extension` or `--hook`; project discovery can also load extensions, tools, hooks, commands, and rules under `.xcsh/`.\n\n## How do I test an extension boundary?\n\nLoad one explicit file with `-e <PATH>` and disable discovery with `--no-extensions`. Confirm its registered command or tool, then test shutdown and error handling.\n\n## Where do hooks and rules belong?\n\nHooks observe or alter lifecycle events; rules add durable instructions. Keep each rule narrow and each hook deterministic. Use `--no-rules` to prove whether a rule changes the result.\n",
20
- "en/automate-extend/headless-protocols.mdx": "---\ntitle: \"Headless modes\"\ndescription: \"Integrate xcsh with scripts through print, JSON, JSON-RPC, agent client protocol, manager, and worker modes.\"\nsidebar:\n order: 1\n label: \"Headless modes\"\n---\n\nHeadless integrations select `json`, `rpc`, or `acp` with `--mode`: a JavaScript Object Notation (JSON) event stream, JSON remote procedure call (RPC), or the agent client protocol (ACP). Each mode has a different framing contract; consumers must parse that protocol rather than decorated terminal text.\n\n## How do I start with the smallest surface?\n\n```bash\nxcsh --mode json --no-session --no-tools -p \"Return one sentence\"\n```\n\nCapture stdout as protocol data and stderr as diagnostics. Pin the xcsh version in automation and test framing against the exact release.\n\n## When do I use the software development kit (SDK) instead?\n\nUse the SDK when the host process needs in-memory session control, tool registration, or provider events. See [SDK automation](./sdk/).\n",
20
+ "en/automate-extend/headless-protocols.mdx": "---\ntitle: \"Headless modes\"\ndescription: \"Integrate xcsh with scripts through print, JSON, JSON-RPC, agent client protocol, manager, and worker modes.\"\nsidebar:\n order: 1\n label: \"Headless modes\"\n---\n\nHeadless integrations select `json`, `rpc`, or `acp` with `--mode`: a JavaScript Object Notation (JSON) event stream, JSON remote procedure call (RPC), or the agent client protocol (ACP). Each mode has a different framing contract; consumers must parse that protocol rather than decorated terminal text.\n\n## How do I start with the smallest surface?\n\n```bash\nxcsh --mode json --no-session --no-tools -p \"Return one sentence\"\n```\n\nCapture stdout as protocol data and stderr as diagnostics. Pin the xcsh version in automation and test framing against the exact release.\n\n## How do I retain and resume a JSON-mode session?\n\nUse a dedicated session directory when the JSON stream must survive process loss:\n\n```bash\nxcsh --mode json --session-dir /var/lib/my-controller/xcsh-sessions -p \"Return one sentence\"\n```\n\nThe first stdout line is a `SessionHeader`. Its `id` is a 16-character lowercase hexadecimal XCSH session ID.\nWith `--session-dir`, xcsh atomically writes and fsyncs the matching `<timestamp>_<id>.jsonl` file before\nemitting that header. The header's persisted `cwd`, `id`, and timestamp are the resumable record. Keep the path\ndiscovered in the session directory (or resolve the ID there), then continue through the documented resume argument:\n\n```bash\nxcsh --resume /var/lib/my-controller/xcsh-sessions/<timestamp>_<id>.jsonl \"Continue the task\"\n```\n\n`--no-session` deliberately produces no resumable file or session header. The stream's wire-only `model`, `provider`, and `thinking` fields describe the launch; they are not additional persisted session-header fields.\n\n## When do I use the software development kit (SDK) instead?\n\nUse the SDK when the host process needs in-memory session control, tool registration, or provider events. See [SDK automation](./sdk/).\n",
21
21
  "en/automate-extend/hooks-rules.mdx": "---\ntitle: \"Apply hooks and rules\"\ndescription: \"Choose event-driven mutation or declarative prompt guidance and understand discovery precedence.\"\nsidebar:\n order: 4\n label: \"Hooks and rules\"\n---\n\nRules contribute normalized instructions to the prompt. Hooks execute code at named lifecycle events. Use rules for guidance that does not need side effects; use a hook only when an event must inspect, transform, or reject runtime data.\n\n## How are rules discovered and classified?\n\nRule providers scan project and user roots, parse frontmatter, normalize identifiers, then deduplicate by precedence. Classification separates ordinary rulebook entries, always-apply guidance, and time-to-self-reflect material. The `rule://` handler resolves the final normalized item rather than reading an arbitrary path.\n\n## What determines hook execution order?\n\nA hook module exports handlers for supported events. Discovery determines the module set, and registration order determines sequential mutation when more than one handler sees the same payload. A thrown error follows the event's propagation contract; it is not converted into a successful empty result.\n\n## How do I test the hook boundary?\n\nExercise each of these separately:\n\n1. Discovery, so the module set is the one you expect.\n2. The exact event, with a representative payload.\n3. Mutation ordering, with more than one handler registered.\n4. Cancellation.\n5. A handler that throws.\n\nInterface calls made by hooks require an interactive host, so a headless integration must not assume a modal interface exists.\n",
22
22
  "en/automate-extend/index.mdx": "---\ntitle: \"Automate and extend\"\ndescription: \"Add skills, plugins, MCP servers, custom tools, hooks, rules, SDK integrations, and headless workers.\"\nsidebar:\n order: 0\n label: \"Overview\"\n---\n\nExtend xcsh only when a built-in command or tool cannot express the task.\n\n## Which extension mechanism fits?\n\n- [Headless modes](./headless-protocols/) drive xcsh from a script over a process boundary.\n- [Software development kit (SDK) automation](./sdk/) embeds sessions in a host application.\n- [Extensions and custom tools](./extensions-custom-tools/) run TypeScript hooks or tools.\n- [Hooks and rules](./hooks-rules/) choose between lifecycle code and declarative guidance.\n- [Skills](./skills/) add discoverable instructions.\n- [Plugins and marketplaces](./plugins-marketplaces/) package installable capabilities.\n- [Model Context Protocol (MCP) quickstart](./mcp-quickstart/) connects one out-of-process server.\n- [MCP configuration](./mcp-configuration/) declares transports, variables, and disabled servers.\n- [MCP runtime and authoring](./mcp-runtime-authoring/) traces connection lifecycle and server contracts.\n",
23
23
  "en/automate-extend/mcp-configuration.mdx": "---\ntitle: \"Configure MCP servers\"\ndescription: \"Declare transports, variables, authentication, and disabled discovered servers in mcp.json.\"\nsidebar:\n order: 8\n label: \"MCP configuration\"\n---\n\nModel Context Protocol (MCP) configuration is discovered from user and project roots and normalized before any connection starts. Use `xcsh mcp list` to see the effective server set instead of inferring it from one file.\n\n## Which transport and lifecycle should I declare?\n\nA local server uses a command plus arguments and communicates over stdio. A remote server declares an HTTP-capable uniform resource locator (URL) and the supported transport options. The runtime selects from the declared shape; it does not silently reinterpret a malformed local entry as a remote one.\n\n## How do I resolve variables without embedding secrets?\n\nConfiguration values can reference environment-backed variables. Credential resolution happens before connection establishment, and unresolved required variables fail that server without printing the secret. Keep tokens outside committed `mcp.json` files.\n\n## How do I disable a discovered server?\n\nAdd its normalized identifier to `disabledServers` when a higher-precedence discovery source should remain visible but inactive. Validate the resulting set with `xcsh mcp list`, then use the MCP management commands to reconnect or reload after a file change.\n",
@@ -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\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 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",
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",
@@ -0,0 +1,428 @@
1
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
2
+ import * as fs from "node:fs/promises";
3
+ import * as net from "node:net";
4
+ import * as path from "node:path";
5
+ import { type PtyRunResult, PtySession, sanitizeText } from "@f5-sales-demo/pi-natives";
6
+ import { buildXcshCommand } from "../commands/herdr";
7
+ import { NATIVE_LIFECYCLE_CONTROL_FLAG } from "../extensibility/extensions/bundled/native-lifecycle-control";
8
+ import {
9
+ NATIVE_LIFECYCLE_DRIVER_VERSION,
10
+ NATIVE_LIFECYCLE_SCENARIOS,
11
+ type NativeLifecycleScenario,
12
+ nativeLifecycleChildArgv,
13
+ } from "./native-acceptance";
14
+
15
+ export type { NativeLifecycleScenario };
16
+ export { NATIVE_LIFECYCLE_SCENARIOS };
17
+
18
+ interface TurnAttempt {
19
+ ordinal: number;
20
+ params: Record<string, unknown>;
21
+ replyLost: boolean;
22
+ }
23
+
24
+ interface ReporterTransport {
25
+ socketPath: string;
26
+ attempts: TurnAttempt[];
27
+ requests: string[];
28
+ waitFor: (predicate: (attempt: TurnAttempt) => boolean, afterOrdinal?: number) => Promise<TurnAttempt>;
29
+ close: () => Promise<void>;
30
+ }
31
+
32
+ interface RunningChild {
33
+ pty: PtySession;
34
+ finished: Promise<PtyRunResult>;
35
+ outputTail: () => string;
36
+ }
37
+
38
+ export interface NativeLifecycleDriverOptions {
39
+ scenario: NativeLifecycleScenario;
40
+ model: string;
41
+ sessionDir: string;
42
+ timeoutMs?: number;
43
+ continuation?: string;
44
+ fixturePath?: string;
45
+ fixtureValue?: string;
46
+ }
47
+
48
+ export interface NativeLifecycleReceipt {
49
+ version: number;
50
+ scenario: NativeLifecycleScenario;
51
+ status: "passed";
52
+ evidenceClass: "source_native_child";
53
+ fixture: { path: string; value: string };
54
+ session: { id: string; path: string };
55
+ childRuns: Array<{ exitCode?: number; cancelled: boolean; timedOut: boolean }>;
56
+ turnAttempts: TurnAttempt[];
57
+ control: Record<string, unknown>;
58
+ }
59
+
60
+ const TERMINAL_STATES = new Set(["completed", "failed", "cancelled", "interrupted"]);
61
+
62
+ function isRecord(value: unknown): value is Record<string, unknown> {
63
+ return typeof value === "object" && value !== null && !Array.isArray(value);
64
+ }
65
+
66
+ function sameTurnFrame(left: Record<string, unknown>, right: Record<string, unknown>): boolean {
67
+ return JSON.stringify(left) === JSON.stringify(right);
68
+ }
69
+
70
+ export function currentXcshCommand(args: string[], argv = process.argv, execPath = process.execPath): string {
71
+ const script = argv[1];
72
+ const executable = path.basename(execPath).toLowerCase();
73
+ const prefix =
74
+ executable.startsWith("bun") && script && /\.(?:ts|js|mjs)$/u.test(script) ? [path.resolve(script)] : [];
75
+ return buildXcshCommand(execPath, [...prefix, ...args]);
76
+ }
77
+
78
+ async function startReporterTransport(
79
+ directory: string,
80
+ options: { loseFirstTurnReply: boolean },
81
+ ): Promise<ReporterTransport> {
82
+ const socketPath = path.join(directory, `.native-lifecycle-${randomUUID()}.sock`);
83
+ const attempts: TurnAttempt[] = [];
84
+ const requests: string[] = [];
85
+ const sockets = new Set<net.Socket>();
86
+ const waiters = new Set<{
87
+ predicate: (attempt: TurnAttempt) => boolean;
88
+ afterOrdinal: number;
89
+ resolve: (attempt: TurnAttempt) => void;
90
+ reject: (error: Error) => void;
91
+ }>();
92
+ let handshakeComplete = false;
93
+ let lostReply = false;
94
+
95
+ const publish = (attempt: TurnAttempt): void => {
96
+ for (const waiter of waiters) {
97
+ if (attempt.ordinal <= waiter.afterOrdinal || !waiter.predicate(attempt)) continue;
98
+ waiters.delete(waiter);
99
+ waiter.resolve(attempt);
100
+ }
101
+ };
102
+
103
+ const server = net.createServer(socket => {
104
+ sockets.add(socket);
105
+ socket.on("close", () => sockets.delete(socket));
106
+ socket.on("error", () => {});
107
+ let buffer = "";
108
+ socket.on("data", chunk => {
109
+ buffer += chunk.toString("utf8");
110
+ let newline = buffer.indexOf("\n");
111
+ while (newline >= 0) {
112
+ const line = buffer.slice(0, newline);
113
+ buffer = buffer.slice(newline + 1);
114
+ newline = buffer.indexOf("\n");
115
+ if (!line.trim()) continue;
116
+ const request = JSON.parse(line) as { id: string; method: string; params?: unknown };
117
+ requests.push(request.method);
118
+ if (request.method === "ping") {
119
+ handshakeComplete = true;
120
+ socket.end(
121
+ `${JSON.stringify({ id: request.id, result: { type: "pong", protocol: 20, version: "native-lifecycle", capabilities: { agent_turn_journal: true } } })}\n`,
122
+ );
123
+ continue;
124
+ }
125
+ if (!handshakeComplete) {
126
+ socket.end(
127
+ `${JSON.stringify({ id: request.id, error: { code: "handshake_required", message: "ping required" } })}\n`,
128
+ );
129
+ continue;
130
+ }
131
+ if (request.method === "agent.turn.report" && isRecord(request.params)) {
132
+ const replyLost = options.loseFirstTurnReply && !lostReply;
133
+ lostReply ||= replyLost;
134
+ const attempt = { ordinal: attempts.length + 1, params: request.params, replyLost };
135
+ attempts.push(attempt);
136
+ publish(attempt);
137
+ if (replyLost) {
138
+ socket.destroy();
139
+ continue;
140
+ }
141
+ }
142
+ socket.end(`${JSON.stringify({ id: request.id, result: {} })}\n`);
143
+ }
144
+ });
145
+ });
146
+
147
+ await new Promise<void>((resolve, reject) => {
148
+ server.once("error", reject);
149
+ server.listen(socketPath, () => {
150
+ server.off("error", reject);
151
+ resolve();
152
+ });
153
+ });
154
+
155
+ return {
156
+ socketPath,
157
+ attempts,
158
+ requests,
159
+ waitFor: (predicate, afterOrdinal = 0) => {
160
+ const existing = attempts.find(attempt => attempt.ordinal > afterOrdinal && predicate(attempt));
161
+ if (existing) return Promise.resolve(existing);
162
+ return new Promise<TurnAttempt>((resolve, reject) => {
163
+ waiters.add({ predicate, afterOrdinal, resolve, reject });
164
+ });
165
+ },
166
+ close: async () => {
167
+ for (const waiter of waiters) waiter.reject(new Error("reporter transport closed"));
168
+ waiters.clear();
169
+ for (const socket of sockets) socket.destroy();
170
+ await new Promise<void>(resolve => server.close(() => resolve()));
171
+ await fs.rm(socketPath, { force: true });
172
+ },
173
+ };
174
+ }
175
+
176
+ async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
177
+ let timer: ReturnType<typeof setTimeout> | undefined;
178
+ try {
179
+ return await Promise.race([
180
+ promise,
181
+ new Promise<T>((_resolve, reject) => {
182
+ timer = setTimeout(() => reject(new Error(`Timed out waiting for ${label}`)), timeoutMs);
183
+ }),
184
+ ]);
185
+ } finally {
186
+ if (timer !== undefined) clearTimeout(timer);
187
+ }
188
+ }
189
+
190
+ function startChild(args: string[], cwd: string, env: Record<string, string>, timeoutMs: number): RunningChild {
191
+ const pty = new PtySession();
192
+ let tail = "";
193
+ const finished = pty.start(
194
+ {
195
+ command: currentXcshCommand(args),
196
+ cwd,
197
+ env,
198
+ timeoutMs,
199
+ cols: 120,
200
+ rows: 40,
201
+ },
202
+ (_error, chunk) => {
203
+ tail = `${tail}${chunk ?? ""}`.slice(-8000);
204
+ },
205
+ );
206
+ return { pty, finished, outputTail: () => tail };
207
+ }
208
+
209
+ async function stopInteractiveChild(child: RunningChild, timeoutMs: number): Promise<PtyRunResult> {
210
+ try {
211
+ await Bun.sleep(100);
212
+ child.pty.write("\x04");
213
+ return await withTimeout(child.finished, Math.min(timeoutMs, 5000), "native child shutdown");
214
+ } catch {
215
+ try {
216
+ child.pty.kill();
217
+ } catch {}
218
+ return await withTimeout(child.finished, Math.min(timeoutMs, 5000), "forced native child shutdown");
219
+ }
220
+ }
221
+
222
+ async function prepareFixture(options: NativeLifecycleDriverOptions): Promise<{ path: string; value: string }> {
223
+ if (options.fixturePath !== undefined || options.fixtureValue !== undefined) {
224
+ if (!options.fixturePath || options.fixtureValue === undefined) {
225
+ throw new Error("fixturePath and fixtureValue must be supplied together");
226
+ }
227
+ const actual = (await fs.readFile(options.fixturePath, "utf8")).replace(/\n$/u, "");
228
+ if (actual !== options.fixtureValue) throw new Error("fixture value does not match the supplied file");
229
+ return { path: path.resolve(options.fixturePath), value: actual };
230
+ }
231
+ const value = `xcsh-native-${randomBytes(24).toString("base64url")}`;
232
+ const fixturePath = path.join(options.sessionDir, `fixture-${randomBytes(8).toString("hex")}.txt`);
233
+ await fs.writeFile(fixturePath, `${value}\n`, { mode: 0o600, flag: "wx" });
234
+ return { path: fixturePath, value };
235
+ }
236
+
237
+ async function readCanonicalSession(sessionDir: string): Promise<{ id: string; path: string }> {
238
+ const entries = await fs.readdir(sessionDir, { withFileTypes: true });
239
+ const candidates: Array<{ id: string; path: string }> = [];
240
+ for (const entry of entries) {
241
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
242
+ const sessionPath = path.join(sessionDir, entry.name);
243
+ const first = (await fs.readFile(sessionPath, "utf8")).split("\n", 1)[0];
244
+ if (!first) continue;
245
+ const header = JSON.parse(first) as Record<string, unknown>;
246
+ if (header.type === "session" && typeof header.id === "string" && /^[0-9a-f]{16}$/u.test(header.id)) {
247
+ candidates.push({ id: header.id, path: sessionPath });
248
+ }
249
+ }
250
+ if (candidates.length !== 1) throw new Error(`Expected exactly one canonical session, found ${candidates.length}`);
251
+ return candidates[0]!;
252
+ }
253
+
254
+ function sessionProbeArgs(options: NativeLifecycleDriverOptions): string[] {
255
+ return [
256
+ "--model",
257
+ options.model,
258
+ "--mode",
259
+ "json",
260
+ "--session-dir",
261
+ options.sessionDir,
262
+ "--no-memories",
263
+ "--no-skills",
264
+ "--no-rules",
265
+ "--no-mcp",
266
+ "--no-lsp",
267
+ "--no-tools",
268
+ ];
269
+ }
270
+
271
+ function baseChildArgs(
272
+ options: NativeLifecycleDriverOptions,
273
+ fixture: { path: string; value: string },
274
+ sessionPath: string,
275
+ ): string[] {
276
+ const prompt = `Use the read tool to read ${fixture.path}. Return only its exact contents without the trailing newline.`;
277
+ return nativeLifecycleChildArgv({
278
+ model: options.model,
279
+ sessionDir: options.sessionDir,
280
+ prompt,
281
+ tools: "read",
282
+ resume: sessionPath,
283
+ interactive: true,
284
+ });
285
+ }
286
+
287
+ function stateIs(state: string): (attempt: TurnAttempt) => boolean {
288
+ return attempt => attempt.params.state === state;
289
+ }
290
+
291
+ function terminal(attempt: TurnAttempt): boolean {
292
+ return typeof attempt.params.state === "string" && TERMINAL_STATES.has(attempt.params.state);
293
+ }
294
+
295
+ export async function runNativeLifecycleAcceptance(
296
+ options: NativeLifecycleDriverOptions,
297
+ ): Promise<NativeLifecycleReceipt> {
298
+ const timeoutMs = options.timeoutMs ?? 90_000;
299
+ await fs.mkdir(options.sessionDir, { recursive: true, mode: 0o700 });
300
+ const fixture = await prepareFixture(options);
301
+ const transport = await startReporterTransport(options.sessionDir, {
302
+ loseFirstTurnReply: options.scenario === "reply-loss-replay",
303
+ });
304
+ const executionId = `xcsh-native-${randomUUID()}`;
305
+ const paneId = `native:${randomUUID()}`;
306
+ const environment = {
307
+ HERDR_PANE_ID: paneId,
308
+ HERDR_SOCKET_PATH: transport.socketPath,
309
+ HERDR_EXECUTION_ID: executionId,
310
+ HERDR_EXECUTION_GENERATION: "0",
311
+ };
312
+ const childRuns: NativeLifecycleReceipt["childRuns"] = [];
313
+ const control: Record<string, unknown> = {};
314
+ let active: RunningChild | undefined;
315
+
316
+ try {
317
+ const probe = startChild(sessionProbeArgs(options), path.dirname(fixture.path), {}, timeoutMs);
318
+ const probeResult = await withTimeout(probe.finished, timeoutMs, "canonical JSON session probe");
319
+ if (probeResult.timedOut || probeResult.exitCode !== 0) {
320
+ throw new Error(`Canonical JSON session probe failed: ${sanitizeText(probe.outputTail()).trim()}`);
321
+ }
322
+ childRuns.push(probeResult);
323
+ const session = await readCanonicalSession(options.sessionDir);
324
+
325
+ let args = baseChildArgs(options, fixture, session.path);
326
+ if (options.scenario === "await-continue" || options.scenario === "cancel") {
327
+ args = [...args, NATIVE_LIFECYCLE_CONTROL_FLAG, "await-user"];
328
+ }
329
+ if (options.scenario === "failure") args = [...args, "--api-key", "native-lifecycle-invalid-credential"];
330
+ active = startChild(args, path.dirname(fixture.path), environment, timeoutMs);
331
+
332
+ if (options.scenario === "await-continue" || options.scenario === "cancel") {
333
+ const waiting = await withTimeout(transport.waitFor(stateIs("waiting_input")), timeoutMs, "waiting_input");
334
+ control.waitingOrdinal = waiting.ordinal;
335
+ if (options.scenario === "await-continue") {
336
+ active.pty.write(options.continuation ?? "continue");
337
+ await Bun.sleep(25);
338
+ active.pty.write("\r");
339
+ control.continuation = "pty_input";
340
+ } else {
341
+ active.pty.interrupt();
342
+ control.cancellation = "pty_process_group_sigint";
343
+ }
344
+ }
345
+
346
+ const terminalAttempt = await withTimeout(transport.waitFor(terminal), timeoutMs, "terminal turn report");
347
+ control.terminalOrdinal = terminalAttempt.ordinal;
348
+ const expectedTerminal =
349
+ options.scenario === "failure" ? "failed" : options.scenario === "cancel" ? "cancelled" : "completed";
350
+ if (terminalAttempt.params.state !== expectedTerminal) {
351
+ throw new Error(
352
+ `Native child settled ${String(terminalAttempt.params.state)} instead of ${expectedTerminal}: ${active.outputTail()}`,
353
+ );
354
+ }
355
+ if (expectedTerminal === "completed") {
356
+ if (terminalAttempt.params.result !== fixture.value) {
357
+ throw new Error("Native child completed without returning the exact randomized fixture value");
358
+ }
359
+ const digest = createHash("sha256").update(fixture.value).digest("hex");
360
+ if (terminalAttempt.params.result_digest !== digest) {
361
+ throw new Error("Native child completed with an invalid result digest");
362
+ }
363
+ }
364
+ childRuns.push(await stopInteractiveChild(active, timeoutMs));
365
+ active = undefined;
366
+
367
+ if (terminalAttempt.params.session_id !== session.id) {
368
+ throw new Error("Reporter session identity does not match the persisted SessionHeader");
369
+ }
370
+
371
+ if (options.scenario === "reply-loss-replay") {
372
+ const lost = transport.attempts.find(attempt => attempt.replyLost);
373
+ if (!lost) throw new Error("Reporter transport did not lose the configured reply");
374
+ const beforeRestart = transport.attempts.length;
375
+ active = startChild(
376
+ nativeLifecycleChildArgv({
377
+ model: options.model,
378
+ sessionDir: options.sessionDir,
379
+ prompt: "",
380
+ tools: "read",
381
+ resume: session.path,
382
+ interactive: true,
383
+ }),
384
+ path.dirname(fixture.path),
385
+ environment,
386
+ timeoutMs,
387
+ );
388
+ const replay = await withTimeout(
389
+ transport.waitFor(attempt => sameTurnFrame(attempt.params, lost.params), beforeRestart),
390
+ timeoutMs,
391
+ "exact persisted reporter redelivery",
392
+ );
393
+ control.replyLossOrdinal = lost.ordinal;
394
+ control.redeliveryOrdinal = replay.ordinal;
395
+ control.exactRedelivery = true;
396
+ control.resumePath = session.path;
397
+ childRuns.push(await stopInteractiveChild(active, timeoutMs));
398
+ active = undefined;
399
+ }
400
+
401
+ return {
402
+ version: NATIVE_LIFECYCLE_DRIVER_VERSION,
403
+ scenario: options.scenario,
404
+ status: "passed",
405
+ evidenceClass: "source_native_child",
406
+ fixture,
407
+ session,
408
+ childRuns,
409
+ turnAttempts: transport.attempts,
410
+ control,
411
+ };
412
+ } catch (error) {
413
+ const message = error instanceof Error ? error.message : String(error);
414
+ const tail = active ? sanitizeText(active.outputTail()).trim().slice(-2000) : "";
415
+ const diagnostic = `Reporter requests: ${transport.requests.join(", ") || "none"}; turn states: ${transport.attempts.map(attempt => String(attempt.params.state)).join(", ") || "none"}`;
416
+ throw new Error(
417
+ tail ? `${message}\n${diagnostic}\nNative child output tail:\n${tail}` : `${message}\n${diagnostic}`,
418
+ );
419
+ } finally {
420
+ if (active) {
421
+ try {
422
+ active.pty.kill();
423
+ } catch {}
424
+ await active.finished.catch(() => undefined);
425
+ }
426
+ await transport.close();
427
+ }
428
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Stable argv contract for the producer-owned native lifecycle driver.
3
+ *
4
+ * This deliberately drives an ordinary xcsh child. It does not manufacture
5
+ * reporter frames or supply an offline model: callers must provide a normally
6
+ * configured model and inspect the child's JSON stream and session file.
7
+ */
8
+ export const NATIVE_LIFECYCLE_DRIVER_VERSION = 1;
9
+ export const NATIVE_LIFECYCLE_SCENARIOS = [
10
+ "success",
11
+ "failure",
12
+ "await-continue",
13
+ "cancel",
14
+ "reply-loss-replay",
15
+ ] as const;
16
+ export type NativeLifecycleScenario = (typeof NATIVE_LIFECYCLE_SCENARIOS)[number];
17
+
18
+ export interface NativeLifecycleChildOptions {
19
+ model: string;
20
+ sessionDir: string;
21
+ prompt: string;
22
+ tools: string;
23
+ resume?: string;
24
+ interactive?: boolean;
25
+ }
26
+
27
+ /** Build the exact low-discovery argv used by lifecycle acceptance children. */
28
+ export function nativeLifecycleChildArgv(options: NativeLifecycleChildOptions): string[] {
29
+ return [
30
+ "--model",
31
+ options.model,
32
+ ...(options.interactive ? [] : ["--mode", "json"]),
33
+ "--session-dir",
34
+ options.sessionDir,
35
+ "--no-memories",
36
+ "--no-skills",
37
+ "--no-rules",
38
+ "--no-mcp",
39
+ "--no-lsp",
40
+ "--tools",
41
+ options.tools,
42
+ ...(options.resume !== undefined
43
+ ? ["--resume", options.resume, ...(options.prompt ? [options.prompt] : [])]
44
+ : options.interactive
45
+ ? [options.prompt]
46
+ : ["--print", options.prompt]),
47
+ ];
48
+ }
49
+
50
+ /** A public, machine-readable contract for controller/acceptance drivers. */
51
+ export function nativeLifecycleContract(): Record<string, unknown> {
52
+ return {
53
+ version: NATIVE_LIFECYCLE_DRIVER_VERSION,
54
+ transport: "xcsh-json-session-v3",
55
+ session_id: "^[0-9a-f]{16}$",
56
+ session_path: "<session-dir>/<timestamp>_<session-id>.jsonl",
57
+ child: {
58
+ modes: { non_interactive: "json", pty: "interactive" },
59
+ reduced_discovery_flags: ["--no-memories", "--no-skills", "--no-rules", "--no-mcp", "--no-lsp"],
60
+ },
61
+ controls: {
62
+ resume: "--resume <exact-session-path>",
63
+ cancel: "PtySession.interrupt() sends SIGINT to the native child process group",
64
+ await_user: "--native-lifecycle-control await-user uses the interactive ExtensionUiController",
65
+ continuation: "write the continuation and Enter to the same native PTY",
66
+ replay: "restart --resume <exact-session-path> with the same authenticated binding",
67
+ },
68
+ scenarios: NATIVE_LIFECYCLE_SCENARIOS,
69
+ };
70
+ }
@@ -186,14 +186,17 @@ export class OAuthSelectorComponent extends Container {
186
186
  if (state === "invalid" || access?.status === "reauth-required") {
187
187
  return theme.fg("error", ` ${theme.status.error} re-authentication required`) + excluded;
188
188
  }
189
+ if (access?.status === "unreachable") {
190
+ return theme.fg("warning", ` ${theme.status.warning} unreachable`) + excluded;
191
+ }
192
+ if (access?.credentialSource === "keyless") {
193
+ return theme.fg("success", ` ${theme.status.success} keyless configured`) + excluded;
194
+ }
189
195
  if (state === "valid") {
190
196
  return theme.fg("success", ` ${theme.status.success} connected`) + excluded;
191
197
  }
192
198
  let label = "";
193
- if (access?.credentialSource === "keyless")
194
- label = theme.fg("success", ` ${theme.status.success} keyless configured`);
195
- else if (access?.status === "unreachable") label = theme.fg("warning", ` ${theme.status.warning} unreachable`);
196
- else if (access?.status === "configured-unverified") label = theme.fg("warning", " credential detected");
199
+ if (access?.status === "configured-unverified") label = theme.fg("warning", " credential detected");
197
200
  else if (access?.status === "connected") label = theme.fg("success", ` ${theme.status.success} connected`);
198
201
  else if (!access && this.#authStorage.hasAuth(providerId)) label = theme.fg("warning", " credential detected");
199
202
  return label + excluded;
@@ -74,6 +74,10 @@ export async function runPrintMode(session: AgentSession, options: PrintModeOpti
74
74
 
75
75
  // Emit session header for JSON mode.
76
76
  if (mode === "json") {
77
+ // A JSON header advertises a session identity to an external process. Make that
78
+ // identity resumable before it becomes observable, even when this invocation
79
+ // has no prompt and therefore would otherwise retain lazy persistence.
80
+ await session.sessionManager.ensureOnDisk();
77
81
  const line = buildJsonSessionHeaderLine(session.sessionManager.getHeader(), session.model, session.thinkingLevel);
78
82
  if (line) process.stdout.write(line);
79
83
  }