@f5-sales-demo/xcsh 21.19.5 → 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/package.json +8 -8
- package/src/cli.ts +1 -0
- package/src/commands/lifecycle.ts +48 -0
- package/src/extensibility/extensions/bundled/herdr-reporter.ts +7 -0
- package/src/extensibility/extensions/bundled/native-lifecycle-control.ts +82 -0
- package/src/extensibility/extensions/loader.ts +5 -0
- package/src/internal-urls/build-info.generated.ts +8 -8
- package/src/internal-urls/docs-index.generated.ts +1 -1
- package/src/lifecycle/native-acceptance-driver.ts +428 -0
- package/src/lifecycle/native-acceptance.ts +70 -0
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"type": "module",
|
|
3
3
|
"name": "@f5-sales-demo/xcsh",
|
|
4
|
-
"version": "21.
|
|
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.
|
|
66
|
-
"@f5-sales-demo/pi-ai": "21.
|
|
67
|
-
"@f5-sales-demo/pi-natives": "21.
|
|
68
|
-
"@f5-sales-demo/pi-resource-management": "21.
|
|
69
|
-
"@f5-sales-demo/pi-tui": "21.
|
|
70
|
-
"@f5-sales-demo/pi-utils": "21.
|
|
71
|
-
"@f5-sales-demo/xcsh-stats": "21.
|
|
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.
|
|
21
|
-
"commit": "
|
|
22
|
-
"shortCommit": "
|
|
20
|
+
"version": "21.20.0",
|
|
21
|
+
"commit": "f7b6a95e7675dbb7aa2f3d59617d17b3a497a0e1",
|
|
22
|
+
"shortCommit": "f7b6a95",
|
|
23
23
|
"branch": "main",
|
|
24
|
-
"tag": "v21.
|
|
25
|
-
"commitDate": "2026-09-
|
|
26
|
-
"buildDate": "2026-09-
|
|
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/
|
|
32
|
-
"releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.
|
|
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
|
};
|
|
@@ -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
|
+
}
|