From 5907e6b1aa62844aa7ee2ef69be1e3c90b721567 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 15:52:46 -0800 Subject: [PATCH 1/2] feat: return durable session output from TypeScript adapters Let a TypeScript process adapter's start() return its confirmed native session identity and recovery warnings. The lifecycle host validates that output and forwards it in the start response, so Fabric can confirm an explicit session selection or register a new durable reference. Adapters that return nothing keep the existing null start output. When a failed start cannot be cleaned up, report cleanup_unconfirmed with the original start error code, matching the Python lifecycle host, so Fabric keeps retained state owned until cleanup is retried. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/common/src/index.ts | 2 + adapters/typescript/common/src/lifecycle.ts | 79 ++++++++++++- .../typescript/common/test/lifecycle.test.mjs | 105 ++++++++++++++++++ 3 files changed, 182 insertions(+), 4 deletions(-) diff --git a/adapters/typescript/common/src/index.ts b/adapters/typescript/common/src/index.ts index 286643d13..92571b256 100644 --- a/adapters/typescript/common/src/index.ts +++ b/adapters/typescript/common/src/index.ts @@ -8,9 +8,11 @@ export { LifecycleError, serve, + type AdapterRecoveryWarning, type AdapterRuntime, type AdapterRuntimeFactory, type AdapterStartInput, + type AdapterStartOutput, type LifecycleHostOptions, } from "./lifecycle.js"; diff --git a/adapters/typescript/common/src/lifecycle.ts b/adapters/typescript/common/src/lifecycle.ts index 23cbb09e1..59b605c27 100644 --- a/adapters/typescript/common/src/lifecycle.ts +++ b/adapters/typescript/common/src/lifecycle.ts @@ -33,8 +33,29 @@ export interface AdapterStartInput { telemetryPlan?: JsonObject; } +/** One recovery warning reported when a retained native session is reopened. */ +export interface AdapterRecoveryWarning { + stage: "start"; + code: string; + message: string; + retryable: boolean; + metadata?: JsonObject; +} + +/** + * Optional startup output for adapters that keep durable native sessions. + * + * `session_id` is the confirmed native session identity. Fabric compares it with + * an explicit selection, or registers it as a new durable reference. + */ +export interface AdapterStartOutput { + session_id: string; + recovery_warnings?: AdapterRecoveryWarning[]; +} + export interface AdapterRuntime { - start(input: AdapterStartInput): Promise; + /** Start the runtime; return session output only when it opened a durable native session. */ + start(input: AdapterStartInput): Promise; invoke(request: AgentRunRequest, context: RuntimeContext): Promise; stop(): Promise; check?(level: CheckLevel): Promise; @@ -222,6 +243,43 @@ function decodeInvocation(payload: Record): { }; } +function nonEmptyString(value: unknown): value is string { + return typeof value === "string" && value.trim().length > 0; +} + +function decodeStartOutput(value: unknown): AdapterStartOutput | null { + if (value === undefined || value === null) { + return null; + } + const invalid = () => + new LifecycleError("lifecycle_invalid_response", "Adapter returned invalid session startup output"); + if (!isRecord(value) || !nonEmptyString(value.session_id)) { + throw invalid(); + } + const warnings = value.recovery_warnings; + if (warnings !== undefined) { + if (!Array.isArray(warnings)) { + throw invalid(); + } + for (const warning of warnings) { + if ( + !isRecord(warning) || + warning.stage !== "start" || + !nonEmptyString(warning.code) || + typeof warning.message !== "string" || + typeof warning.retryable !== "boolean" || + (warning.metadata !== undefined && !isRecord(warning.metadata)) + ) { + throw invalid(); + } + } + } + return { + session_id: value.session_id, + ...(warnings === undefined ? {} : { recovery_warnings: warnings as AdapterRecoveryWarning[] }), + }; +} + async function callAdapter(operation: string, call: () => T | Promise): Promise { try { return await call(); @@ -285,13 +343,26 @@ async function dispatch( const disabled = isRecord(provenance) && provenance.enabled === false; state.passive = disabled ? undefined : new Map(); let candidate: AdapterRuntime | undefined; + let output: AdapterStartOutput | null; try { candidate = await callAdapter("start", factory); const active = candidate; - await withSoftwareObservations(state.passive, () => callAdapter("start", () => active.start(decodeStart(request.payload)))); + output = decodeStartOutput( + await withSoftwareObservations(state.passive, () => callAdapter("start", () => active.start(decodeStart(request.payload)))), + ); } catch (error) { if (candidate !== undefined) { - await stopQuietly(candidate, diagnostics); + try { + await callAdapter("stop", () => candidate!.stop()); + } catch (cleanupError) { + diagnostics.write( + `Adapter cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : "unknown error"}\n`, + ); + // Fabric keeps durable state owned until cleanup of the failed start is confirmed. + throw new LifecycleError("cleanup_unconfirmed", "Adapter startup cleanup could not be confirmed", { + metadata: error instanceof LifecycleError ? { start_error_code: error.code } : {}, + }); + } } throw error; } @@ -316,7 +387,7 @@ async function dispatch( throw new LifecycleError("lifecycle_health_unavailable", "Adapter health channel could not be started"); } } - return success("start"); + return success("start", output); } if (state.runtime === undefined || state.runtimeId === undefined) { diff --git a/adapters/typescript/common/test/lifecycle.test.mjs b/adapters/typescript/common/test/lifecycle.test.mjs index 9aaf01fbc..a3bb9472a 100644 --- a/adapters/typescript/common/test/lifecycle.test.mjs +++ b/adapters/typescript/common/test/lifecycle.test.mjs @@ -292,3 +292,108 @@ test("health endpoint survives adapter startup environment isolation", async (t) }), [start("runtime-1"), invoke("runtime-1", "inspect", "invoke-1")]); assert.equal(inspected, true); }); + +test("returns durable session output from start and keeps legacy starts null", async () => { + const warning = { + stage: "start", + code: "session_recovery_required", + message: "Inspect before continuing", + retryable: false, + metadata: { request_id: "request-1" }, + }; + const [durable] = await exchange( + () => ({ + async start() { + return { session_id: "native-1", recovery_warnings: [warning] }; + }, + async invoke() { throw new Error("unreachable"); }, + async stop() {}, + }), + [start("runtime-1")], + ); + assert.deepEqual(durable.outcome, { + status: "succeeded", + output: { session_id: "native-1", recovery_warnings: [warning] }, + }); + + const [legacy] = await exchange( + () => ({ async start() {}, async invoke() { throw new Error("unreachable"); }, async stop() {} }), + [start("runtime-2")], + ); + assert.deepEqual(legacy.outcome, { status: "succeeded", output: null }); +}); + +test("rejects invalid session startup output and cleans up the runtime", async () => { + for (const output of [ + { session_id: "" }, + { session_id: 7 }, + { session_id: "native-1", recovery_warnings: {} }, + { session_id: "native-1", recovery_warnings: [{ stage: "invoke", code: "x", message: "", retryable: false }] }, + { session_id: "native-1", recovery_warnings: [{ stage: "start", code: "x", message: "" }] }, + "native-1", + ]) { + let stopped = 0; + const [response] = await exchange( + () => ({ + async start() { return output; }, + async invoke() { throw new Error("unreachable"); }, + async stop() { stopped += 1; }, + }), + [start("runtime-1")], + ); + assert.equal(response.outcome.error.code, "lifecycle_invalid_response", JSON.stringify(output)); + assert.equal(stopped, 1); + } +}); + +test("reports unconfirmed cleanup when a failed start cannot be cleaned up", async () => { + const { LifecycleError } = await import("../dist/index.js"); + const [response] = await exchange( + () => ({ + async start() { throw new LifecycleError("session_not_found", "missing"); }, + async invoke() { throw new Error("unreachable"); }, + async stop() { throw new Error("private cleanup detail"); }, + }), + [start("runtime-1")], + ); + assert.equal(response.outcome.error.code, "cleanup_unconfirmed"); + assert.deepEqual(response.outcome.error.metadata, { start_error_code: "session_not_found" }); + assert.equal(JSON.stringify(response).includes("private"), false); +}); + +test("a recovery denial result keeps the runtime usable for an acknowledged request", async () => { + const seen = []; + const responses = await exchange( + () => ({ + async start() { return { session_id: "native-1" }; }, + async invoke(request) { + seen.push(request.acknowledge_recovery === true); + return request.acknowledge_recovery === true + ? { status: "succeeded", output: { response: "ok" }, session_id: "native-1" } + : { + status: "failed", + output: null, + session_id: "native-1", + error: { code: "session_recovery_required", message: "Acknowledge first", retryable: false }, + }; + }, + async stop() {}, + }), + [ + start("runtime-1"), + invoke("runtime-1", "one", "one"), + { + operation: "invoke", + payload: { + request: { input: "two", acknowledge_recovery: true }, + runtime_context: context("runtime-1", "two"), + }, + }, + stop("runtime-1"), + ], + ); + assert.deepEqual(seen, [false, true]); + assert.equal(responses[1].outcome.output.error.code, "session_recovery_required"); + assert.equal(responses[2].outcome.output.status, "succeeded"); + assert.equal(responses[3].outcome.status, "succeeded"); +}); From 7dd778fd8975d535904bee4fd2d423da506ee2f6 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 15:52:47 -0800 Subject: [PATCH 2/2] feat: add Pi cold resume With runtime.keep_state, keep Pi's native JSONL sessions in the Fabric state folder and return a durable SessionRef, including before the first prompt. A supplied SessionRef reopens that exact conversation in a new runtime with the same Pi session ID; omitting it starts a fresh one. - Keep native sessions in a private sessions folder with a private identity-to-file index; write a new session's header durably before returning its reference, because Pi delays file creation. - Validate a selected session file strictly before Pi loads it and fail with session_not_found or session_incompatible instead of letting Pi repair, rewrite, or replace it. - Rebuild model, credentials, tools, skills, extensions, MCP, and Relay from the current configuration and use the current workspace as cwd. - Sync a turn record before native work and after confirmed completion. When completion is uncertain, warn at start with session_recovery_required and block model work until the request sets acknowledge_recovery; never replay the earlier request. - Confirm the native identity before and after every turn and return it in every result. - Accept runtime.keep_state and declare session_resume in the descriptor. Closes #297 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/README.md | 2 +- adapters/typescript/pi/README.md | 58 +- adapters/typescript/pi/pi.fabric-adapter.json | 6 +- adapters/typescript/pi/src/pi-sdk.ts | 118 ++- adapters/typescript/pi/src/runtime.ts | 107 ++- adapters/typescript/pi/src/sessions.ts | 685 ++++++++++++++++++ adapters/typescript/pi/test/sessions.test.mjs | 637 ++++++++++++++++ .../nemo_fabric_adapter_catalog/catalog.json | 6 +- tests/adapters/test_pi_adapter.py | 2 + tests/e2e/test_pi_resume.py | 218 ++++++ 10 files changed, 1819 insertions(+), 20 deletions(-) create mode 100644 adapters/typescript/pi/src/sessions.ts create mode 100644 adapters/typescript/pi/test/sessions.test.mjs create mode 100644 tests/e2e/test_pi_resume.py diff --git a/adapters/README.md b/adapters/README.md index 6b4f7d096..319d90bc1 100644 --- a/adapters/README.md +++ b/adapters/README.md @@ -214,7 +214,7 @@ Agent Trajectory Interchange Format (ATIF). | [Cline](typescript/cline/README.md) | Local `ClineCore` and interactive Cline session | Not supported | Initializes without a prompt at runtime startup, then calls `send()` with the retained session ID | Stops the session, disposes the core, and removes runtime-scoped plugin and data directories | Not implemented | | [Factory Droid](typescript/droid/README.md) | TypeScript SDK `DroidSession` | Not supported | Calls `stream()` for each ordered prompt on the retained session | Closes the session and its caller-installed CLI subprocess | Not implemented | | [OpenCode](typescript/opencode/README.md) | Embedded OpenCode host and session | Not supported | Reuses the session and calls `prompt()`, `wait()`, and `context()` for ordered text input | Removes the session and closes the host | Not implemented | -| [Pi](typescript/pi/README.md) | In-memory Pi `AgentSession` | Runtime-owned Relay 0.9–0.11 CLI gateway and explicit Pi extension | Reuses the session and calls `prompt()` for ordered text input; with `streaming=True`, routes per-invocation model-turn ATOF for successful redirects through the embedded collector; startup `model_redirect` marks remain in configured Relay ATOF artifacts and are not included in `invoke_stream()`; `relay_artifacts` does not include local ATIF | Aborts work, emits extension shutdown so local ATIF finalizes on disk, disposes the session, and then stops the gateway | Not implemented | +| [Pi](typescript/pi/README.md) | Pi `AgentSession`, in memory or retained for cold resume with `runtime.keep_state` | Runtime-owned Relay 0.9–0.11 CLI gateway and explicit Pi extension | Reuses the session and calls `prompt()` for ordered text input; with `streaming=True`, routes per-invocation model-turn ATOF for successful redirects through the embedded collector; startup `model_redirect` marks remain in configured Relay ATOF artifacts and are not included in `invoke_stream()`; `relay_artifacts` does not include local ATIF | Aborts work, emits extension shutdown so local ATIF finalizes on disk, disposes the session, and then stops the gateway | Not implemented | | [Qwen Code](typescript/qwen/README.md) | SDK query and bundled Qwen CLI child process | Not supported | Reuses one live SDK query across ordered text turns | Closes the query and removes isolated temporary settings | Not implemented | | [Kiro](typescript/kiro/README.md) | Kiro CLI V3 child process and ACP session | Not supported | Reuses one ACP session and submits ordered text prompts | Closes the ACP session and terminates the Kiro child process | Not implemented | | [Strands](typescript/strands/README.md) | Strands CLI ACP child process and session | Not supported | Ordered text prompts retain one bounded conversation | Terminates the child process and removes temporary CLI state | Not implemented | diff --git a/adapters/typescript/pi/README.md b/adapters/typescript/pi/README.md index f0dec61b1..2a8788a26 100644 --- a/adapters/typescript/pi/README.md +++ b/adapters/typescript/pi/README.md @@ -7,7 +7,8 @@ SPDX-License-Identifier: Apache-2.0 This package provides a Pi harness adapter for NVIDIA NeMo Fabric. It embeds the Pi SDK in the Node process of the adapter and maps one NeMo Fabric runtime to one -in-memory Pi session. +Pi session. The session is in memory unless `runtime.keep_state` retains it for +[cold resume](#cold-resume). The adapter supports: @@ -39,6 +40,8 @@ The adapter supports: `invoke_stream()` records - Ordered plain-text invocations with a `{ "response": "..." }` terminal output, Relay runtime details, and collected ATOF and OTLP artifacts +- Durable native sessions with `runtime.keep_state` and explicit `SessionRef` + cold resume Ambient Pi settings, context files, packages, extensions, skills, prompts, themes, model files, credentials, and session files are disabled. Explicitly @@ -296,6 +299,59 @@ redirects, then prints one JSON document containing `atof_records` and the separate terminal `result`. Redirect-decision marks remain in configured Relay ATOF artifacts; Pi's startup marks are not included in `atof_records`. +## Cold Resume + +Without `runtime.keep_state`, each runtime uses an in-memory Pi session and +returns no `session_ref`. With `runtime.keep_state` and an artifact directory, +NeMo Fabric supplies the agent's state folder and the adapter stores Pi's native +JSONL sessions in its private `sessions` folder. A start without a reference +creates a new conversation and returns a durable `Runtime.session_ref`, including +before the first prompt: + +```yaml +runtime: + keep_state: true + artifacts: ./artifacts +``` + +Save `Runtime.session_ref.to_mapping()` in caller-owned storage. Pass +`session_ref=SessionRef.from_mapping(saved_reference)` to +`Fabric.start_runtime()` to reopen that exact conversation. The caller must also +retain the full artifact state tree, including NeMo Fabric's private relative +bindings in `.fabric/state/nvidia.fabric.pi/.sessions`, and the workspace. A +corrected agent name can select the same reference. A different adapter cannot. +Omitting `session_ref` always starts a fresh conversation. + +The replacement runtime has a new runtime ID and the same Pi session ID. +`RunResult.session_ref` confirms the selected conversation. The adapter +validates the complete session file before Pi loads it and accepts Pi 1.0.3 +session format version 3. A missing, empty, malformed, truncated, symlinked, or +identity-mismatched file fails with `session_not_found` or +`session_incompatible` and is never rewritten or replaced by a fresh +conversation. Pi rebuilds the active history, including tool results and +compaction; branch selection and session switching are not supported. + +Resume restores conversation history only. The model, credentials, system +instruction, tool policy, skills, extensions, MCP servers, and Relay setup come +from the current configuration, and the current workspace becomes the session's +working directory. Absolute paths inside earlier messages are not rewritten. +Retain externally installed extension and skill files separately. + +Before each turn, the adapter durably records the turn's start. If a runtime +stops before native history shows a terminal response with every tool result, +resume returns a `session_recovery_required` startup warning, and NeMo Fabric +blocks ordinary invocations before any model call. The same gate applies within +a running runtime after a turn ends without confirmed completion. Inspect the +native history and external effects, then send a new `RunRequest` with +`acknowledge_recovery=True`. Acknowledgment sends only the new request. It does +not replay or undo the earlier request, and the model can still act on +unfinished history. + +The NeMo Fabric state lock allows one writer for the retained state. A failed +startup cleanup reports `cleanup_unconfirmed` and keeps the state owned until +cleanup is retried. The adapter keeps its folders mode `0700` and its files mode +`0600` and syncs native history before stop completes. + ## Runtime Health Local SDK callers can use `Fabric.check()` with the runtime's environment and diff --git a/adapters/typescript/pi/pi.fabric-adapter.json b/adapters/typescript/pi/pi.fabric-adapter.json index 1cae737c4..ab0507285 100644 --- a/adapters/typescript/pi/pi.fabric-adapter.json +++ b/adapters/typescript/pi/pi.fabric-adapter.json @@ -19,7 +19,8 @@ "tools.blocked", "skills", "mcp", - "mcp.tool_filters" + "mcp.tool_filters", + "runtime.keep_state" ], "system_instruction_modes": ["replace"] }, @@ -201,6 +202,7 @@ "streaming": false, "cancellation": false, "updates": false, - "service": false + "service": false, + "session_resume": true } } diff --git a/adapters/typescript/pi/src/pi-sdk.ts b/adapters/typescript/pi/src/pi-sdk.ts index 31c874d04..9d3bf730e 100644 --- a/adapters/typescript/pi/src/pi-sdk.ts +++ b/adapters/typescript/pi/src/pi-sdk.ts @@ -2,8 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 // Pi SDK integration boundary. It translates normalized adapter configuration -// into a controlled in-memory Pi session, including model credentials, skills, -// extensions, custom tools, and workspace containment. +// into a controlled Pi session, including model credentials, skills, extensions, +// custom tools, and workspace containment. The session is in memory unless +// Fabric supplies a retained state folder, which holds durable native sessions. import { mkdtemp, realpath, rm, stat } from "node:fs/promises"; import { homedir, tmpdir } from "node:os"; @@ -29,7 +30,17 @@ import { type PiRelayRuntime, } from "./relay.js"; import { invocationUsage } from "./usage.js"; -import type { PiPromptOutcome, PiSessionFactory, PiSessionHandle } from "./runtime.js"; +import type { PiDurableSession, PiPromptOutcome, PiSessionFactory, PiSessionHandle } from "./runtime.js"; +import { + PI_ADAPTER_ID, + PiTurnTracker, + createSession, + openSession, + selectSession, + sessionStore, + type PiSessionStore, + type ValidatedSession, +} from "./sessions.js"; // ProviderConfigInput isn't re-exported from pi's public entrypoint; derive it from // registerProvider's param type (ModelRuntime's constructor is private, so no InstanceType). @@ -868,8 +879,76 @@ function unsupportedSessionAction(name: string): never { throw new LifecycleError("pi_unsupported_session_operation", `Pi session operation ${name} is not supported`); } +interface NativeSessionPlan { + store: PiSessionStore; + selected?: ValidatedSession; +} + +/** + * Validate durable session storage and any explicit selection before startup + * creates Relay, MCP, or Pi resources. Without a Fabric state folder the adapter + * keeps its in-memory session and returns no durable identity. + */ +async function planNativeSession(input: AdapterStartInput): Promise { + const stateDir = input.runtimeContext.state_dir ?? undefined; + const reference = input.runtimeContext.session_ref ?? undefined; + if (stateDir === undefined) { + if (reference !== undefined) { + throw new LifecycleError("session_storage_required", "Durable Pi sessions require retained storage"); + } + return undefined; + } + if (reference !== undefined && reference.adapter_id !== PI_ADAPTER_ID) { + throw new LifecycleError("session_adapter_mismatch", "Session reference targets another adapter"); + } + const store = await sessionStore(stateDir, reference === undefined); + return { + store, + ...(reference === undefined ? {} : { selected: await selectSession(store, reference.session_id) }), + }; +} + +class PiSdkDurableSession implements PiDurableSession { + private readonly session: AgentSession; + private readonly tracker: PiTurnTracker; + + constructor(session: AgentSession, tracker: PiTurnTracker) { + this.session = session; + this.tracker = tracker; + } + + get sessionId(): string { + return this.tracker.sessionId; + } + + get recoveryWarnings() { + return this.tracker.warnings; + } + + confirmIdentity(): void { + this.tracker.confirmIdentity(this.session.sessionId); + } + + beginTurn(identity: { requestId?: string; invocationId?: string }, acknowledgeRecovery: boolean): Promise { + return this.tracker.begin(identity, acknowledgeRecovery); + } + + markUncertain(): void { + this.tracker.markUncertain(); + } + + finishTurn(): Promise { + return this.tracker.finish(); + } + + sync(): Promise { + return this.tracker.sync(); + } +} + class PiSdkSessionHandle implements PiSessionHandle { readonly relay?: PiRelayRuntime; + readonly durable?: PiSdkDurableSession; private readonly session: AgentSession; private readonly state: { shutdownRequested: boolean }; private readonly unsubscribeTurnCounter: () => void; @@ -885,11 +964,12 @@ class PiSdkSessionHandle implements PiSessionHandle { constructor(session: AgentSession, state: { shutdownRequested: boolean }, runtimeDir: string, modelRuntime: PiModelRuntime, expectedModel: { id: string; provider: string }, - connections: Map, relay?: PiRelayRuntime) { + connections: Map, relay?: PiRelayRuntime, tracker?: PiTurnTracker) { this.session = session; this.state = state; this.runtimeDir = runtimeDir; this.relay = relay; + this.durable = tracker === undefined ? undefined : new PiSdkDurableSession(session, tracker); this.modelRuntime = modelRuntime; this.expectedModel = expectedModel; this.connections = connections; @@ -1013,7 +1093,15 @@ class PiSdkSessionHandle implements PiSessionHandle { } catch (error) { failure ??= error; } + try { + // Retained native history must be durable before Fabric releases ownership. + await this.durable?.sync(); + } catch (error) { + failure ??= error; + } } finally { + // Only per-runtime material lives here; the native session store is in the + // Fabric state folder and is never removed. await rm(this.runtimeDir, { recursive: true, force: true }); } if (failure !== undefined) { @@ -1059,6 +1147,9 @@ export class PiSdkSessionFactory implements PiSessionFactory { } catch { throw new LifecycleError("pi_workspace_invalid", "The Fabric runtime workspace must be a directory"); } + // Fabric has already resolved the state folder inside the artifact root and + // holds its writer lock, so native state is read only after that point. + const nativeSession = await planNativeSession(input); const selected = selectModel(input.config); const apiKeyEnv = selected.api_key_env; if (apiKeyEnv === undefined || apiKeyEnv === null || apiKeyEnv.length === 0) { @@ -1227,20 +1318,35 @@ export class PiSdkSessionFactory implements PiSessionFactory { const enabled = input.config.tools?.enabled; const blocked = input.config.tools?.blocked ?? []; const state = { shutdownRequested: false }; + let sessionManager = pi.SessionManager.inMemory(workspace); + let tracker: PiTurnTracker | undefined; + if (nativeSession !== undefined) { + const native = nativeSession.selected + ?? await createSession(nativeSession.store, workspace, pi.SessionManager); + // The current workspace replaces the saved cwd so a moved mount does not + // restore an obsolete working directory. + sessionManager = openSession(pi.SessionManager, nativeSession.store, native, workspace); + tracker = await PiTurnTracker.open(nativeSession.store, native, sessionManager); + } + // Model, credentials, tools, skills, extensions, MCP, and Relay all come from + // the current Fabric configuration; only conversation history is restored. const { session } = await pi.createAgentSession({ cwd: workspace, agentDir, model, modelRuntime, resourceLoader, - sessionManager: pi.SessionManager.inMemory(workspace), + sessionManager, settingsManager: settings, customTools, tools: enabled === null ? undefined : enabled, excludeTools: blocked, }); handle = new PiSdkSessionHandle(session, state, runtimeDir, modelRuntime, - { id: model.id, provider: model.provider }, mcpConnections, relay); + { id: model.id, provider: model.provider }, mcpConnections, relay, tracker); + if (tracker !== undefined && session.sessionId !== tracker.sessionId) { + throw new LifecycleError("session_resume_unconfirmed", "Pi did not confirm the selected native session"); + } const blockedNames = new Set(blocked); const availableNames = new Set(session.getAllTools().map((tool) => tool.name)); const missing = (enabled ?? []).filter((name) => !blockedNames.has(name) && !availableNames.has(name)); diff --git a/adapters/typescript/pi/src/runtime.ts b/adapters/typescript/pi/src/runtime.ts index e16a3665d..5881e6004 100644 --- a/adapters/typescript/pi/src/runtime.ts +++ b/adapters/typescript/pi/src/runtime.ts @@ -3,10 +3,19 @@ // Pi lifecycle state machine. It maps NeMo Fabric start, invoke, and stop calls // to a PiSessionHandle and normalized results while keeping SDK construction -// behind a factory for focused lifecycle testing. +// behind a factory for focused lifecycle testing. With a durable native session +// it reports the confirmed identity at start, records each turn, and blocks new +// work after an uncertain turn until the caller acknowledges recovery. import type { AdapterCheckResult, CheckLevel, AgentRunRequest, AgentRunResult, AgentUsage, JsonObject, RuntimeContext } from "nemo-fabric-adapter-contract"; -import { LifecycleError, unobservedHealth, type AdapterRuntime, type AdapterStartInput } from "nemo-fabric-adapters-common"; +import { + LifecycleError, + unobservedHealth, + type AdapterRecoveryWarning, + type AdapterRuntime, + type AdapterStartInput, + type AdapterStartOutput, +} from "nemo-fabric-adapters-common"; import { collectRelayArtifacts, type RelayArtifact } from "./relay-config.js"; import type { PiRelayRuntime } from "./relay.js"; @@ -24,9 +33,24 @@ export interface PiPromptOutcome { shutdownRequested?: boolean; } +/** Durable native-session controls, present only with a retained Fabric state folder. */ +export interface PiDurableSession { + readonly sessionId: string; + readonly recoveryWarnings: AdapterRecoveryWarning[]; + /** Throw `session_identity_changed` unless Pi still writes the selected session. */ + confirmIdentity(): void; + /** Record a turn before native work; false while an uncertain turn awaits acknowledgment. */ + beginTurn(identity: { requestId?: string; invocationId?: string }, acknowledgeRecovery: boolean): Promise; + /** Keep the recovery gate closed after Pi failed without confirmed completion. */ + markUncertain(): void; + /** Persist confirmed completion; false leaves the recovery gate closed. */ + finishTurn(): Promise; +} + export interface PiSessionHandle { readonly relay?: PiRelayRuntime; readonly turnCount?: number; + readonly durable?: PiDurableSession; prompt(text: string): Promise; stop(): Promise; check(level: CheckLevel): Promise; @@ -83,7 +107,7 @@ export class PiAdapterRuntime implements AdapterRuntime { this.factory = factory; } - async start(input: AdapterStartInput): Promise { + async start(input: AdapterStartInput): Promise { if (this.session !== undefined) { throw new LifecycleError("pi_already_started", "Pi adapter runtime is already started"); } @@ -92,15 +116,39 @@ export class PiAdapterRuntime implements AdapterRuntime { this.stopping = false; this.turnCount = 0; this.unusable = false; + const durable = this.session.durable; + if (durable === undefined) { + return undefined; + } + return { + session_id: durable.sessionId, + recovery_warnings: durable.recoveryWarnings.map((warning) => ({ ...warning })), + }; } - async invoke(request: AgentRunRequest, _context: RuntimeContext): Promise { + async invoke(request: AgentRunRequest, context: RuntimeContext): Promise { + const result = await this.invokeSession(request, context); + const durable = this.session?.durable; + // Fabric rejects a result that does not confirm the bound native session. + return durable === undefined ? result : { ...result, session_id: durable.sessionId }; + } + + private async invokeSession(request: AgentRunRequest, context: RuntimeContext): Promise { if (this.session === undefined) { throw new LifecycleError("pi_not_started", "Pi adapter runtime is not started"); } if (this.unusable) { throw new LifecycleError("pi_runtime_unusable", "Pi adapter runtime cannot accept another invocation"); } + const durable = this.session.durable; + if (durable !== undefined) { + try { + durable.confirmIdentity(); + } catch (error) { + this.unusable = true; + throw error; + } + } if (typeof request.input !== "string") { const observedTurnCount = this.session.turnCount; if (observedTurnCount !== undefined) { @@ -118,7 +166,32 @@ export class PiAdapterRuntime implements AdapterRuntime { } const relay = this.session.relay; - const outcome = await this.session.prompt(request.input); + if ( + durable !== undefined && + !(await durable.beginTurn( + { requestId: context.request_id, invocationId: context.invocation_id }, + request.acknowledge_recovery === true, + )) + ) { + // Denied before any model call; the runtime stays usable for an + // acknowledged request. Acknowledgment never replays the earlier request. + return withRelayOutput( + failed( + "session_recovery_required", + "Earlier turn completion is uncertain. Inspect native and external state, then set acknowledge_recovery to continue.", + ), + relay, + false, + this.turnCount, + ); + } + let outcome: PiPromptOutcome; + try { + outcome = await this.session.prompt(request.input); + } catch (error) { + durable?.markUncertain(); + throw error; + } const annotate = (result: AgentRunResult) => withRelayOutput( { ...result, ...(outcome.usage === undefined ? {} : { usage: outcome.usage }) }, relay, outcome.turnStarted, outcome.turnCount, @@ -128,18 +201,36 @@ export class PiAdapterRuntime implements AdapterRuntime { outcome.turnCount < this.turnCount || (outcome.turnStarted ? outcome.turnCount === this.turnCount : outcome.turnCount !== this.turnCount) ) { + durable?.markUncertain(); throw new LifecycleError("pi_invalid_turn_count", "Pi returned an invalid cumulative turn count"); } this.turnCount = outcome.turnCount; + if (outcome.shutdownRequested) { + this.unusable = true; + } + if (durable !== undefined) { + try { + durable.confirmIdentity(); + } catch (error) { + this.unusable = true; + throw error; + } + if (!(await durable.finishTurn())) { + return annotate({ + ...failed( + "session_recovery_required", + "Native turn completion could not be confirmed. Inspect native and external state before explicitly continuing.", + ), + ...(outcome.text === undefined || outcome.text.length === 0 ? {} : { output: { response: outcome.text } }), + }); + } + } if (!outcome.accepted) { return annotate( failed("pi_prompt_rejected", "Pi rejected the prompt before starting an agent run"), ); } if (outcome.shutdownRequested || outcome.stopReason === "aborted") { - if (outcome.shutdownRequested) { - this.unusable = true; - } return annotate( { status: "cancelled", diff --git a/adapters/typescript/pi/src/sessions.ts b/adapters/typescript/pi/src/sessions.ts new file mode 100644 index 000000000..0ebf14387 --- /dev/null +++ b/adapters/typescript/pi/src/sessions.ts @@ -0,0 +1,685 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Durable Pi native sessions. Fabric supplies an agent state folder and holds +// its writer lock; this module keeps Pi's native JSONL sessions inside it, maps +// native identities to session files through a private index, validates a +// selected file strictly before Pi loads it, and records turn boundaries so a +// replacement runtime can tell whether an earlier turn finished. + +import { constants } from "node:fs"; +import { lstat, mkdir, open, readFile, realpath, rename, rm } from "node:fs/promises"; +import { basename, dirname, join, relative, sep, isAbsolute } from "node:path"; +import { randomUUID } from "node:crypto"; + +import type { SessionEntry, SessionHeader, SessionManager } from "@earendil-works/pi-coding-agent"; +import type { JsonObject } from "nemo-fabric-adapter-contract"; +import { LifecycleError, type AdapterRecoveryWarning } from "nemo-fabric-adapters-common"; + +export const PI_ADAPTER_ID = "nvidia.fabric.pi"; +/** Pi 1.0.3 session file format accepted for explicit resume. */ +export const PI_SESSION_FORMAT_VERSION = 3; + +const INDEX_FORMAT = "nemo-fabric.pi-session-index/v1"; +const TURN_FORMAT = "nemo-fabric.pi-turn/v1"; +const SESSIONS_FOLDER = "sessions"; +const INDEX_FILE = "session-index.json"; +const TURNS_FOLDER = ".fabric-turns"; +// Matches Pi's assertValidSessionId(); the identifier also names files below. +const NATIVE_ID = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/u; +const SESSION_FILE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.jsonl$/u; +const POSIX = process.platform !== "win32"; +const MAX_INDEX_BYTES = 4 * 1024 * 1024; +const MAX_RECORD_BYTES = 64 * 1024; + +const ENTRY_TYPES = new Set([ + "message", + "thinking_level_change", + "model_change", + "usage", + "compaction", + "branch_summary", + "custom", + "custom_message", + "context_edit", + "label", + "session_info", +]); +const MESSAGE_ROLES = new Set([ + "system", + "user", + "assistant", + "toolResult", + "custom", + "bashExecution", + "branchSummary", + "compactionSummary", +]); +const TERMINAL_STOP_REASONS = new Set(["stop", "length", "error", "aborted"]); + +type SessionManagerClass = typeof SessionManager; + +function sessionError(code: string, message: string, metadata?: JsonObject): LifecycleError { + return new LifecycleError(code, message, metadata === undefined ? {} : { metadata }); +} + +function incompatible(message: string): LifecycleError { + return sessionError("session_incompatible", message); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function errorCode(error: unknown): string | undefined { + return isRecord(error) && typeof error.code === "string" ? error.code : undefined; +} + +function contained(root: string, candidate: string): boolean { + const path = relative(root, candidate); + return path !== "" && !path.startsWith(`..${sep}`) && path !== ".." && !isAbsolute(path); +} + +/** Flush a file's data to stable storage. */ +export async function syncFile(path: string): Promise { + const handle = await open(path, POSIX ? constants.O_RDONLY | constants.O_NOFOLLOW : "r+"); + try { + await handle.sync(); + } finally { + await handle.close(); + } +} + +/** Flush a directory entry change, where the platform supports it. */ +async function syncDirectory(path: string): Promise { + if (!POSIX) { + return; + } + const handle = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); + try { + await handle.sync(); + } finally { + await handle.close(); + } +} + +/** Write a private file atomically: temporary file, fsync, rename, then fsync the folder. */ +async function writePrivateAtomically(path: string, contents: string): Promise { + const folder = dirname(path); + const temporary = join(folder, `.${basename(path)}.${randomUUID()}.tmp`); + const handle = await open(temporary, "wx", 0o600); + try { + await handle.writeFile(contents, "utf8"); + await handle.sync(); + } catch (error) { + await handle.close().catch(() => undefined); + await rm(temporary, { force: true }); + throw error; + } + await handle.close(); + try { + await rename(temporary, path); + } catch (error) { + await rm(temporary, { force: true }); + throw error; + } + await syncDirectory(folder); +} + +/** Read a bounded private file without following a final symbolic link. */ +async function readPrivateFile(path: string, limit: number): Promise { + let handle; + try { + handle = await open(path, POSIX ? constants.O_RDONLY | constants.O_NOFOLLOW : "r"); + } catch (error) { + if (errorCode(error) === "ENOENT") { + return undefined; + } + throw incompatible("Pi session state is not a readable regular file"); + } + try { + const info = await handle.stat(); + if (!info.isFile() || info.size > limit) { + throw incompatible("Pi session state is not a readable regular file"); + } + return await handle.readFile("utf8"); + } finally { + await handle.close(); + } +} + +/** Create or confirm one private, non-symlinked folder. */ +async function privateFolder(path: string, create: boolean): Promise { + if (create) { + try { + await mkdir(path, { mode: 0o700 }); + } catch (error) { + if (errorCode(error) !== "EEXIST") { + throw incompatible("Pi session storage could not be created"); + } + } + } + let info; + try { + info = await lstat(path); + } catch { + throw sessionError("session_not_found", "Pi session storage was not found in the retained state"); + } + if (info.isSymbolicLink() || !info.isDirectory()) { + throw incompatible("Pi session storage must be a real folder"); + } + if (POSIX && (info.mode & 0o077) !== 0) { + const handle = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); + try { + await handle.chmod(0o700); + if (((await handle.stat()).mode & 0o077) !== 0) { + throw incompatible("Pi session storage permissions could not be made private"); + } + } finally { + await handle.close(); + } + } +} + +/** Paths of the adapter-owned stores inside one Fabric agent state folder. */ +export interface PiSessionStore { + readonly stateDir: string; + readonly sessionsDir: string; + readonly indexPath: string; + readonly turnsDir: string; +} + +/** + * Resolve the native stores in a Fabric-supplied state folder. + * + * Fabric already resolved the folder inside the caller's artifact root and holds + * its writer lock. A new conversation creates the private folders; a selected + * conversation requires them to exist. + */ +export async function sessionStore(stateDir: string, create: boolean): Promise { + if (!isAbsolute(stateDir)) { + throw sessionError("session_storage_required", "Durable Pi sessions require an absolute state folder"); + } + let root: string; + try { + root = await realpath(stateDir); + } catch { + throw sessionError("session_storage_required", "Durable Pi sessions require retained storage"); + } + const info = await lstat(root); + if (!info.isDirectory()) { + throw sessionError("session_storage_required", "Durable Pi sessions require retained storage"); + } + const store = { + stateDir: root, + sessionsDir: join(root, SESSIONS_FOLDER), + indexPath: join(root, INDEX_FILE), + turnsDir: join(root, TURNS_FOLDER), + }; + await privateFolder(store.sessionsDir, create); + await privateFolder(store.turnsDir, true); + return store; +} + +/** Read the private native-identity-to-file index. Missing means empty. */ +async function readIndex(store: PiSessionStore): Promise> { + const contents = await readPrivateFile(store.indexPath, MAX_INDEX_BYTES); + const index = new Map(); + if (contents === undefined) { + return index; + } + let parsed: unknown; + try { + parsed = JSON.parse(contents); + } catch { + throw incompatible("Pi session index is invalid"); + } + if (!isRecord(parsed) || parsed.format !== INDEX_FORMAT || !isRecord(parsed.sessions)) { + throw incompatible("Pi session index is invalid"); + } + const files = new Set(); + for (const [id, file] of Object.entries(parsed.sessions)) { + if (!NATIVE_ID.test(id) || typeof file !== "string" || !SESSION_FILE.test(file) || files.has(file)) { + throw incompatible("Pi session index contains an invalid or duplicate mapping"); + } + files.add(file); + index.set(id, file); + } + return index; +} + +async function writeIndex(store: PiSessionStore, index: Map): Promise { + const sessions = Object.fromEntries([...index.entries()].sort(([left], [right]) => left.localeCompare(right))); + await writePrivateAtomically(store.indexPath, `${JSON.stringify({ format: INDEX_FORMAT, sessions })}\n`); +} + +/** One structurally validated Pi session file. */ +export interface ValidatedSession { + readonly sessionId: string; + readonly file: string; +} + +/** + * Validate a complete Pi JSONL session before Pi's loader can touch it. + * + * Pi 1.0.3 initializes a missing or empty file, skips malformed lines, and + * repairs a missing final newline. Explicit resume rejects each of those states + * instead, so the selected file is never rewritten by a failed resume. + */ +export function validateSessionText(text: string, expectedId: string): SessionEntry[] { + if (text.length === 0) { + throw incompatible("The selected Pi session file is empty"); + } + if (!text.endsWith("\n")) { + throw incompatible("The selected Pi session file is truncated"); + } + const lines = text.slice(0, -1).split("\n"); + const records: Record[] = []; + for (const line of lines) { + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + throw incompatible("The selected Pi session file contains a malformed record"); + } + if (!isRecord(parsed)) { + throw incompatible("The selected Pi session file contains a malformed record"); + } + records.push(parsed); + } + const [header, ...entries] = records; + if ( + header === undefined || + header.type !== "session" || + typeof header.id !== "string" || + typeof header.timestamp !== "string" || + typeof header.cwd !== "string" + ) { + throw incompatible("The selected Pi session file has no valid session header"); + } + if (header.version !== PI_SESSION_FORMAT_VERSION) { + throw incompatible(`The selected Pi session uses an unsupported format; supported version: ${PI_SESSION_FORMAT_VERSION}`); + } + if (header.id !== expectedId) { + throw incompatible("The selected Pi session file belongs to another native session"); + } + const seen = new Set(); + const known = (id: unknown) => typeof id === "string" && seen.has(id); + for (const entry of entries) { + const { type, id, parentId } = entry; + if ( + typeof type !== "string" || + !ENTRY_TYPES.has(type) || + typeof id !== "string" || + id.length === 0 || + seen.has(id) || + typeof entry.timestamp !== "string" || + (parentId !== null && !known(parentId)) + ) { + throw incompatible("The selected Pi session file contains an invalid history entry"); + } + const message = entry.message; + const related = + type === "message" + ? isRecord(message) && typeof message.role === "string" && MESSAGE_ROLES.has(message.role) + : type === "compaction" + ? // Pi points a compaction that keeps no earlier entry at itself. + typeof entry.summary === "string" && (known(entry.firstKeptEntryId) || entry.firstKeptEntryId === id) + : type === "branch_summary" + ? typeof entry.summary === "string" && known(entry.fromId) + : type === "context_edit" || type === "label" + ? known(entry.targetId) + : true; + if (!related) { + throw incompatible("The selected Pi session file contains an invalid history entry"); + } + seen.add(id); + } + return entries as unknown as SessionEntry[]; +} + +/** Resolve and strictly validate the file for a selected native identity. */ +export async function selectSession(store: PiSessionStore, sessionId: string): Promise { + if (!NATIVE_ID.test(sessionId)) { + throw sessionError("session_not_found", "The selected Pi session was not found in retained storage"); + } + const file = (await readIndex(store)).get(sessionId); + if (file === undefined) { + throw sessionError("session_not_found", "The selected Pi session was not found in retained storage"); + } + const path = join(store.sessionsDir, file); + let info; + try { + info = await lstat(path); + } catch { + throw sessionError("session_not_found", "The selected Pi session file is missing"); + } + if (info.isSymbolicLink() || !info.isFile()) { + throw incompatible("The selected Pi session file is not a regular file"); + } + if (!contained(store.sessionsDir, await realpath(path))) { + throw incompatible("The selected Pi session file leaves its session folder"); + } + let bytes: Buffer; + try { + bytes = await readFile(path, { flag: POSIX ? constants.O_RDONLY | constants.O_NOFOLLOW : "r" }); + } catch { + throw incompatible("The selected Pi session file is unreadable"); + } + let text: string; + try { + text = new TextDecoder("utf-8", { fatal: true }).decode(bytes); + } catch { + throw incompatible("The selected Pi session file is not valid UTF-8"); + } + validateSessionText(text, sessionId); + return { sessionId, file: path }; +} + +/** + * Create a new durable Pi conversation and publish it in the private index. + * + * Pi delays writing a new session file until it has a conversation message, so + * a reference returned before the first prompt would name no file. Write Pi's + * own header exclusively instead, make it durable, then publish the index. + */ +export async function createSession( + store: PiSessionStore, + workspace: string, + sessionManager: SessionManagerClass, +): Promise { + const draft = sessionManager.create(workspace, store.sessionsDir); + const header: SessionHeader | null = draft.getHeader(); + const file = draft.getSessionFile(); + if ( + header === null || + header.version !== PI_SESSION_FORMAT_VERSION || + !NATIVE_ID.test(header.id) || + header.id !== draft.getSessionId() || + file === undefined || + dirname(file) !== store.sessionsDir || + !SESSION_FILE.test(basename(file)) + ) { + throw sessionError("session_resume_unconfirmed", "Pi did not provide a usable new session identity"); + } + const index = await readIndex(store); + if (index.has(header.id)) { + throw incompatible("A new Pi session identity is already indexed"); + } + const handle = await open(file, "wx", 0o600); + try { + await handle.writeFile(`${JSON.stringify(header)}\n`, "utf8"); + await handle.sync(); + } finally { + await handle.close(); + } + await syncDirectory(store.sessionsDir); + index.set(header.id, basename(file)); + await writeIndex(store, index); + return { sessionId: header.id, file }; +} + +/** Open a validated file with Pi, using the current workspace as its cwd. */ +export function openSession( + sessionManager: SessionManagerClass, + store: PiSessionStore, + selected: ValidatedSession, + workspace: string, +): SessionManager { + const manager = sessionManager.open(selected.file, store.sessionsDir, workspace); + if (manager.getSessionId() !== selected.sessionId || manager.getSessionFile() !== selected.file) { + throw sessionError("session_resume_unconfirmed", "Pi opened another native session"); + } + return manager; +} + +/** Durable boundary of one turn, written before Pi starts native work. */ +export interface TurnRecord { + format: typeof TURN_FORMAT; + session_id: string; + state: "running" | "complete"; + leaf_id: string | null; + entry_count: number; + request_id?: string; + invocation_id?: string; +} + +function turnPath(store: PiSessionStore, sessionId: string): string { + return join(store.turnsDir, `${sessionId}.json`); +} + +/** Read a turn record; `null` marks a record that exists but cannot be trusted. */ +async function readTurnRecord(store: PiSessionStore, sessionId: string): Promise { + let contents: string | undefined; + try { + contents = await readPrivateFile(turnPath(store, sessionId), MAX_RECORD_BYTES); + } catch { + return null; + } + if (contents === undefined) { + return undefined; + } + try { + const parsed: unknown = JSON.parse(contents); + if ( + isRecord(parsed) && + parsed.format === TURN_FORMAT && + parsed.session_id === sessionId && + (parsed.state === "running" || parsed.state === "complete") && + (parsed.leaf_id === null || typeof parsed.leaf_id === "string") && + Number.isSafeInteger(parsed.entry_count) && + (parsed.entry_count as number) >= 0 + ) { + return parsed as unknown as TurnRecord; + } + } catch { + // Fall through: an unreadable record leaves completion uncertain. + } + return null; +} + +/** Native evidence about the turn that follows a recorded history position. */ +export interface TurnAnalysis { + complete: boolean; + pendingToolCallIds: string[]; +} + +/** + * Decide from native history whether the turn after `record` finished. + * + * A turn is complete when it added no messages, or when its last message is a + * terminal assistant response and every executed tool call has a result. A lost + * Fabric reply alone therefore does not make a durably completed turn uncertain. + */ +export function analyzeTurn( + manager: Pick, + record: Pick | undefined, +): TurnAnalysis { + const branch = manager.getBranch(); + let start = 0; + if (record !== undefined) { + if (manager.getEntryCount() < record.entry_count) { + return { complete: false, pendingToolCallIds: [] }; + } + if (record.leaf_id !== null) { + const position = branch.findIndex((entry) => entry.id === record.leaf_id); + if (position < 0) { + return { complete: false, pendingToolCallIds: [] }; + } + start = position + 1; + } + } + const pending = new Map(); + let last: Record | undefined; + for (const entry of branch.slice(start)) { + if (entry.type !== "message" || !isRecord(entry.message)) { + continue; + } + const message = entry.message as Record; + if (message.role === "assistant") { + // Pi does not execute tool calls from an aborted or failed response. + if (message.stopReason !== "aborted" && message.stopReason !== "error" && Array.isArray(message.content)) { + for (const block of message.content) { + if (isRecord(block) && block.type === "toolCall" && typeof block.id === "string") { + pending.set(block.id, true); + } + } + } + last = message; + } else if (message.role === "toolResult") { + if (typeof message.toolCallId === "string") { + pending.delete(message.toolCallId); + } + last = message; + } else if (message.role === "user") { + last = message; + } + } + const pendingToolCallIds = [...pending.keys()]; + const complete = + last === undefined + ? true + : last.role === "assistant" && + typeof last.stopReason === "string" && + TERMINAL_STOP_REASONS.has(last.stopReason) && + pendingToolCallIds.length === 0; + return { complete, pendingToolCallIds }; +} + +/** Identifiers of the request whose native work a turn record covers. */ +export interface TurnIdentity { + requestId?: string; + invocationId?: string; +} + +/** + * Track durable turn boundaries for one open native session. + * + * A running record is synced before Pi can do native work. After Pi returns, the + * session file is synced before the record is marked complete. When completion + * cannot be confirmed, ordinary requests stay blocked until the caller explicitly + * acknowledges recovery; acknowledgment never replays the earlier request. + */ +export class PiTurnTracker { + readonly sessionId: string; + readonly file: string; + readonly warnings: AdapterRecoveryWarning[]; + private readonly store: PiSessionStore; + private readonly manager: SessionManager; + private record?: TurnRecord; + private recoveryRequired: boolean; + + private constructor( + store: PiSessionStore, + selected: ValidatedSession, + manager: SessionManager, + record: TurnRecord | undefined, + warnings: AdapterRecoveryWarning[], + ) { + this.store = store; + this.sessionId = selected.sessionId; + this.file = selected.file; + this.manager = manager; + this.record = record; + this.warnings = warnings; + this.recoveryRequired = warnings.length > 0; + } + + /** Inspect the last recorded turn of a freshly opened session. */ + static async open(store: PiSessionStore, selected: ValidatedSession, manager: SessionManager): Promise { + const record = await readTurnRecord(store, selected.sessionId); + const analysis = analyzeTurn(manager, record ?? undefined); + const warnings: AdapterRecoveryWarning[] = []; + if (record === null || !analysis.complete) { + const metadata: JsonObject = { + external_effects: "unknown", + pending_tool_call_ids: analysis.pendingToolCallIds, + turn_record_valid: record !== null, + }; + if (record?.request_id !== undefined) metadata.request_id = record.request_id; + if (record?.invocation_id !== undefined) metadata.invocation_id = record.invocation_id; + warnings.push({ + stage: "start", + code: "session_recovery_required", + message: + "Session restored. Earlier turn completion is uncertain. Inspect native and external state before explicitly continuing. No request was replayed.", + retryable: false, + metadata, + }); + } + return new PiTurnTracker(store, selected, manager, record ?? undefined, warnings); + } + + get recoveryPending(): boolean { + return this.recoveryRequired; + } + + /** Confirm Pi still writes the selected native session. */ + confirmIdentity(sessionId: string): void { + if ( + sessionId !== this.sessionId || + this.manager.getSessionId() !== this.sessionId || + this.manager.getSessionFile() !== this.file + ) { + throw sessionError("session_identity_changed", "Pi no longer confirms the selected native session"); + } + } + + /** + * Durably record a new turn before native work starts. + * + * @returns false when an uncertain earlier turn still needs acknowledgment. + */ + async begin(identity: TurnIdentity, acknowledgeRecovery: boolean): Promise { + if (this.recoveryRequired && !acknowledgeRecovery) { + return false; + } + const record: TurnRecord = { + format: TURN_FORMAT, + session_id: this.sessionId, + state: "running", + leaf_id: this.manager.getLeafId(), + entry_count: this.manager.getEntryCount(), + ...(identity.requestId === undefined ? {} : { request_id: identity.requestId }), + ...(identity.invocationId === undefined ? {} : { invocation_id: identity.invocationId }), + }; + await writePrivateAtomically(turnPath(this.store, this.sessionId), `${JSON.stringify(record)}\n`); + this.record = record; + this.recoveryRequired = false; + return true; + } + + /** Mark the current turn uncertain after Pi failed without confirmed completion. */ + markUncertain(): void { + this.recoveryRequired = true; + } + + /** + * Confirm and persist completion of the current turn. + * + * @returns false, leaving the running record and the recovery gate in place, + * when native history does not show a terminal response. + */ + async finish(): Promise { + const record = this.record; + if (record === undefined || record.state !== "running" || !analyzeTurn(this.manager, record).complete) { + this.recoveryRequired = true; + return false; + } + await this.sync(); + const complete: TurnRecord = { + ...record, + state: "complete", + leaf_id: this.manager.getLeafId(), + entry_count: this.manager.getEntryCount(), + }; + await writePrivateAtomically(turnPath(this.store, this.sessionId), `${JSON.stringify(complete)}\n`); + this.record = complete; + return true; + } + + /** Flush Pi's appended native history. */ + async sync(): Promise { + await syncFile(this.file); + } +} diff --git a/adapters/typescript/pi/test/sessions.test.mjs b/adapters/typescript/pi/test/sessions.test.mjs new file mode 100644 index 000000000..828b0eb1e --- /dev/null +++ b/adapters/typescript/pi/test/sessions.test.mjs @@ -0,0 +1,637 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import { appendFile, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, symlink, writeFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; + +import { LifecycleError } from "nemo-fabric-adapters-common"; + +import { PiSdkSessionFactory } from "../dist/pi-sdk.js"; +import { PiAdapterRuntime } from "../dist/runtime.js"; +import { analyzeTurn, validateSessionText } from "../dist/sessions.js"; + +const [major, minor] = process.versions.node.split(".").map(Number); +const skip = major > 22 || (major === 22 && minor >= 19) ? false : "Pi requires Node >=22.19"; +const POSIX = process.platform !== "win32"; +const SESSION_ID = "019a0000-0000-7000-8000-000000000001"; + +function header(overrides = {}) { + return { type: "session", version: 3, id: SESSION_ID, timestamp: "2026-12-01T00:00:00.000Z", cwd: "/w", ...overrides }; +} + +function entry(id, parentId, fields) { + return { id, parentId, timestamp: "2026-12-01T00:00:00.000Z", ...fields }; +} + +function lines(...records) { + return records.map((record) => `${JSON.stringify(record)}\n`).join(""); +} + +const user = (text) => ({ type: "message", message: { role: "user", content: [{ type: "text", text }], timestamp: 0 } }); +const assistant = (stopReason, content = [{ type: "text", text: "done" }]) => ({ + type: "message", + message: { role: "assistant", content, stopReason, api: "openai-completions", provider: "p", model: "m", timestamp: 0 }, +}); +const toolResult = (toolCallId) => ({ + type: "message", + message: { role: "toolResult", toolCallId, toolName: "bash", content: [], isError: false, timestamp: 0 }, +}); + +test("strict validation accepts complete Pi 1.0.3 history including self-kept compaction", () => { + const text = lines( + header(), + entry("a", null, { type: "model_change", provider: "p", modelId: "m" }), + entry("b", "a", user("hello")), + entry("c", "b", assistant("stop")), + entry("d", "c", { type: "compaction", summary: "s", firstKeptEntryId: "d", tokensBefore: 1 }), + entry("e", "d", { type: "label", targetId: "b", label: "x" }), + ); + assert.equal(validateSessionText(text, SESSION_ID).length, 5); +}); + +for (const [description, text] of [ + ["an empty file", ""], + ["a missing final newline", lines(header()).slice(0, -1)], + ["a malformed line", `${lines(header())}{not json\n`], + ["a blank line", `${lines(header())}\n`], + ["an unsupported format", lines(header({ version: 2 }))], + ["another native identity", lines(header({ id: "other" }))], + ["no session header", lines(entry("a", null, user("x")))], + ["an unknown entry type", lines(header(), entry("a", null, { type: "mystery" }))], + ["a dangling parent", lines(header(), entry("a", "missing", user("x")))], + ["a duplicate entry id", lines(header(), entry("a", null, user("x")), entry("a", "a", user("y")))], + ["a dangling compaction", lines(header(), entry("a", null, { type: "compaction", summary: "s", firstKeptEntryId: "z" }))], + ["an invalid message", lines(header(), entry("a", null, { type: "message", message: { role: "robot" } }))], +]) { + test(`strict validation rejects ${description}`, () => { + assert.throws(() => validateSessionText(text, SESSION_ID), { code: "session_incompatible" }); + }); +} + +function fakeManager(branch, entryCount = branch.length) { + return { getBranch: () => branch, getEntryCount: () => entryCount }; +} + +test("turn analysis confirms only terminal responses with every tool result", () => { + const before = entry("a", null, { type: "thinking_level_change", thinkingLevel: "off" }); + const record = { leaf_id: "a", entry_count: 1 }; + const call = [{ type: "toolCall", id: "call-1", name: "bash", arguments: {} }]; + assert.deepEqual(analyzeTurn(fakeManager([before]), record), { complete: true, pendingToolCallIds: [] }); + assert.equal(analyzeTurn(fakeManager([before, entry("b", "a", user("x"))]), record).complete, false); + assert.deepEqual( + analyzeTurn(fakeManager([before, entry("b", "a", user("x")), entry("c", "b", assistant("toolUse", call))]), record), + { complete: false, pendingToolCallIds: ["call-1"] }, + ); + assert.equal( + analyzeTurn(fakeManager([before, entry("b", "a", user("x")), entry("c", "b", assistant("toolUse", call)), + entry("d", "c", toolResult("call-1"))]), record).complete, + false, + ); + assert.equal( + analyzeTurn(fakeManager([before, entry("b", "a", user("x")), entry("c", "b", assistant("toolUse", call)), + entry("d", "c", toolResult("call-1")), entry("e", "d", assistant("stop"))]), record).complete, + true, + ); + for (const reason of ["length", "error", "aborted"]) { + assert.equal(analyzeTurn(fakeManager([before, entry("b", "a", user("x")), entry("c", "b", assistant(reason))]), record).complete, true); + } + // A recorded position that left the active branch, or shrank, is uncertain. + assert.equal(analyzeTurn(fakeManager([entry("z", null, user("x"))]), record).complete, false); + assert.equal(analyzeTurn(fakeManager([before], 0), record).complete, false); +}); + +// --- Runtime gate with a fake durable handle ------------------------------------------------- + +function runtimeInput() { + return { + agentName: "pi-test", + baseDir: "/tmp", + config: {}, + runtimeContext: { + artifacts: {}, + environment: { control_location: "external_control", environment_id: "e", ownership: "caller_owned", provider: "local" }, + invocation_id: "start", + request_id: "request-start", + runtime_id: "runtime-1", + }, + }; +} + +function invocation(id) { + return { ...runtimeInput().runtimeContext, invocation_id: id, request_id: `request-${id}` }; +} + +function fakeDurable({ recovery = false, finish = [] } = {}) { + const state = { recovery, began: [], uncertain: 0, identityOk: true, finish: [...finish] }; + return { + state, + durable: { + sessionId: "native-1", + recoveryWarnings: recovery + ? [{ stage: "start", code: "session_recovery_required", message: "uncertain", retryable: false }] + : [], + confirmIdentity() { + if (!state.identityOk) throw new LifecycleError("session_identity_changed", "changed"); + }, + async beginTurn(identity, acknowledge) { + if (state.recovery && !acknowledge) return false; + state.began.push(identity); + state.recovery = false; + return true; + }, + markUncertain() { + state.uncertain += 1; + state.recovery = true; + }, + async finishTurn() { + const result = state.finish.length === 0 ? true : state.finish.shift(); + if (!result) state.recovery = true; + return result; + }, + }, + }; +} + +function durableRuntime(durable, prompt) { + let turnCount = 0; + const prompts = []; + const runtime = new PiAdapterRuntime({ + async create() { + return { + durable, + get turnCount() { + return turnCount; + }, + async prompt(text) { + prompts.push(text); + if (prompt !== undefined) return prompt(text); + turnCount += 1; + return { accepted: true, turnStarted: true, turnCount, text: `reply:${text}`, stopReason: "stop" }; + }, + async stop() {}, + async check() { + throw new Error("unused"); + }, + }; + }, + }); + return { runtime, prompts }; +} + +test("start reports the durable identity and recovery warnings; results always confirm it", async () => { + const { durable } = fakeDurable({ recovery: true }); + const { runtime } = durableRuntime(durable); + const output = await runtime.start(runtimeInput()); + assert.deepEqual(output, { + session_id: "native-1", + recovery_warnings: [{ stage: "start", code: "session_recovery_required", message: "uncertain", retryable: false }], + }); + const unsupported = await runtime.invoke({ input: { messages: [] } }, invocation("one")); + assert.equal(unsupported.session_id, "native-1"); + assert.equal(unsupported.error.code, "pi_unsupported_input"); +}); + +test("in-memory starts return no durable identity and results carry none", async () => { + const runtime = new PiAdapterRuntime({ + async create() { + return { + async prompt() { + return { accepted: true, turnStarted: true, turnCount: 1, text: "ok", stopReason: "stop" }; + }, + async stop() {}, + }; + }, + }); + assert.equal(await runtime.start(runtimeInput()), undefined); + const result = await runtime.invoke({ input: "x" }, invocation("one")); + assert.equal(result.status, "succeeded"); + assert.equal("session_id" in result, false); +}); + +test("an uncertain earlier turn blocks model work until acknowledgment and never replays", async () => { + const { durable, state } = fakeDurable({ recovery: true }); + const { runtime, prompts } = durableRuntime(durable); + await runtime.start(runtimeInput()); + + const denied = await runtime.invoke({ input: "new work" }, invocation("one")); + assert.equal(denied.status, "failed"); + assert.equal(denied.error.code, "session_recovery_required"); + assert.equal(denied.session_id, "native-1"); + assert.deepEqual(prompts, []); + + const allowed = await runtime.invoke({ input: "reviewed", acknowledge_recovery: true }, invocation("two")); + assert.equal(allowed.status, "succeeded"); + assert.deepEqual(prompts, ["reviewed"]); + assert.deepEqual(state.began, [{ requestId: "request-two", invocationId: "two" }]); + const next = await runtime.invoke({ input: "ordinary" }, invocation("three")); + assert.equal(next.status, "succeeded"); +}); + +test("a live turn without confirmed native completion closes the recovery gate", async () => { + const { durable } = fakeDurable({ finish: [false] }); + const { runtime, prompts } = durableRuntime(durable); + await runtime.start(runtimeInput()); + const uncertain = await runtime.invoke({ input: "one" }, invocation("one")); + assert.equal(uncertain.status, "failed"); + assert.equal(uncertain.error.code, "session_recovery_required"); + assert.deepEqual(uncertain.output, { response: "reply:one" }); + const blocked = await runtime.invoke({ input: "two" }, invocation("two")); + assert.equal(blocked.error.code, "session_recovery_required"); + assert.deepEqual(prompts, ["one"]); +}); + +test("an extension shutdown during an uncertain turn still retires the runtime", async () => { + const { durable } = fakeDurable({ finish: [false] }); + const { runtime } = durableRuntime(durable, async () => ({ + accepted: true, turnStarted: true, turnCount: 1, stopReason: "aborted", shutdownRequested: true, + })); + await runtime.start(runtimeInput()); + const result = await runtime.invoke({ input: "x" }, invocation("one")); + assert.equal(result.error.code, "session_recovery_required"); + await assert.rejects( + runtime.invoke({ input: "y", acknowledge_recovery: true }, invocation("two")), + { code: "pi_runtime_unusable" }, + ); +}); + +test("a thrown Pi turn stays uncertain and an identity change makes the runtime unusable", async () => { + const { durable, state } = fakeDurable(); + const { runtime } = durableRuntime(durable, async () => { + throw new Error("crashed"); + }); + await runtime.start(runtimeInput()); + await assert.rejects(runtime.invoke({ input: "x" }, invocation("one")), /crashed/); + assert.equal(state.uncertain, 1); + + const second = fakeDurable(); + const { runtime: changed } = durableRuntime(second.durable); + await changed.start(runtimeInput()); + second.state.identityOk = false; + await assert.rejects(changed.invoke({ input: "x" }, invocation("one")), { code: "session_identity_changed" }); + second.state.identityOk = true; + await assert.rejects(changed.invoke({ input: "x" }, invocation("two")), { code: "pi_runtime_unusable" }); +}); + +// --- Real Pi SDK resume against a deterministic model endpoint ------------------------------ + +async function modelEndpoint() { + const requests = []; + const server = createServer(async (request, response) => { + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + requests.push(JSON.parse(Buffer.concat(chunks).toString("utf8"))); + const frame = (value) => + `data: ${JSON.stringify({ id: `c-${requests.length}`, object: "chat.completion.chunk", created: 0, model: "m", ...value })}\n\n`; + response.writeHead(200, { "content-type": "text/event-stream" }); + response.end( + frame({ choices: [{ index: 0, delta: { role: "assistant", content: `answer-${requests.length}` }, finish_reason: "stop" }] }) + + frame({ choices: [], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }) + + "data: [DONE]\n\n", + ); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return { + requests, + url: `http://127.0.0.1:${server.address().port}/v1`, + async close() { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + }, + }; +} + +async function fixture(t) { + const root = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-resume-"))); + const workspace = join(root, "workspace"); + const stateDir = join(root, "state"); + await mkdir(workspace); + await mkdir(stateDir, { mode: 0o700 }); + const endpoint = await modelEndpoint(); + t.after(async () => { + await endpoint.close(); + await rm(root, { recursive: true, force: true }); + }); + return { root, workspace, stateDir, endpoint }; +} + +function piInput({ workspace, stateDir, endpoint }, { sessionRef, runtimeId = "runtime-1" } = {}) { + return { + agentName: "resume-test", + baseDir: workspace, + config: { + models: { + default: { provider: "nvidia", model: "openai/gpt-oss-20b", base_url: endpoint.url, api_key_env: "TEST_API_KEY" }, + }, + tools: { enabled: [] }, + }, + runtimeContext: { + artifacts: {}, + environment: { + control_location: "external_control", + environment_id: "resume-test", + ownership: "caller_owned", + provider: "local", + workspace, + env: { TEST_API_KEY: "unused" }, + }, + invocation_id: "start", + request_id: "start", + runtime_id: runtimeId, + ...(stateDir === undefined ? {} : { state_dir: stateDir }), + ...(sessionRef === undefined ? {} : { session_ref: sessionRef }), + }, + }; +} + +function reference(sessionId, adapterId = "nvidia.fabric.pi") { + return { schema_version: "fabric.session_ref/v1alpha1", adapter_id: adapterId, session_id: sessionId }; +} + +async function withRuntime(input, body) { + const runtime = new PiAdapterRuntime(new PiSdkSessionFactory()); + try { + const output = await runtime.start(input); + return await body(runtime, output); + } finally { + await runtime.stop(); + } +} + +function lastUserTexts(request) { + return request.messages.filter((message) => message.role === "user").map((message) => JSON.stringify(message.content)); +} + +async function snapshot(stateDir) { + const files = {}; + for (const folder of ["", "sessions", ".fabric-turns"]) { + const path = join(stateDir, folder); + let names = []; + try { + names = await readdir(path); + } catch { + continue; + } + for (const name of names) { + const info = await stat(join(path, name)); + if (info.isFile()) files[join(folder, name)] = await readFile(join(path, name), "utf8"); + } + } + return files; +} + +test("resumes the selected conversation with the same native identity and a new runtime", { skip }, async (t) => { + const env = await fixture(t); + const seed = async (text, runtimeId) => + withRuntime(piInput(env, { runtimeId }), async (runtime, output) => { + const result = await runtime.invoke({ input: text }, invocation(runtimeId)); + assert.equal(result.status, "succeeded"); + assert.equal(result.session_id, output.session_id); + assert.deepEqual(output.recovery_warnings, []); + return output.session_id; + }); + const a = await seed("Remember: the project codename is Cedar.", "seed-a"); + const b = await seed("Remember: the project codename is Birch.", "seed-b"); + assert.notEqual(a, b); + + const before = env.endpoint.requests.length; + await withRuntime(piInput(env, { sessionRef: reference(a), runtimeId: "resume-a" }), async (runtime, output) => { + assert.deepEqual(output, { session_id: a, recovery_warnings: [] }); + const result = await runtime.invoke({ input: "What is the project codename?" }, invocation("ask")); + assert.equal(result.status, "succeeded"); + assert.equal(result.session_id, a); + }); + const resumed = env.endpoint.requests[before]; + const sent = JSON.stringify(resumed.messages); + assert.match(sent, /Cedar/); + assert.doesNotMatch(sent, /Birch/); + // The earlier request appears once: history is restored, never replayed. + assert.equal(lastUserTexts(resumed).filter((text) => text.includes("Cedar")).length, 1); + assert.match(sent, /answer-1/); + + await withRuntime(piInput(env, { runtimeId: "fresh" }), async (runtime, output) => { + assert.notEqual(output.session_id, a); + assert.notEqual(output.session_id, b); + await runtime.invoke({ input: "Hello" }, invocation("fresh")); + }); + const fresh = JSON.stringify(env.endpoint.requests.at(-1).messages); + assert.doesNotMatch(fresh, /Cedar|Birch/); +}); + +test("reopens an empty conversation saved before its first prompt", { skip }, async (t) => { + const env = await fixture(t); + const id = await withRuntime(piInput(env), async (_runtime, output) => output.session_id); + assert.equal(env.endpoint.requests.length, 0); + await withRuntime(piInput(env, { sessionRef: reference(id) }), async (runtime, output) => { + assert.deepEqual(output, { session_id: id, recovery_warnings: [] }); + await runtime.invoke({ input: "first" }, invocation("first")); + }); + assert.equal(lastUserTexts(env.endpoint.requests[0]).length, 1); +}); + +test("keeps the in-memory behavior without a state folder", { skip }, async (t) => { + const env = await fixture(t); + await withRuntime(piInput({ ...env, stateDir: undefined }), async (runtime, output) => { + assert.equal(output, undefined); + const result = await runtime.invoke({ input: "x" }, invocation("x")); + assert.equal("session_id" in result, false); + }); + assert.deepEqual(await readdir(env.stateDir), []); +}); + +test("keeps native history and indexes private", { skip: skip || (!POSIX && "POSIX permissions") }, async (t) => { + const env = await fixture(t); + const id = await withRuntime(piInput(env), async (runtime, output) => { + await runtime.invoke({ input: "x" }, invocation("x")); + return output.session_id; + }); + const sessions = join(env.stateDir, "sessions"); + const [file] = await readdir(sessions); + assert.match(file, new RegExp(`_${id}\\.jsonl$`)); + for (const [path, mode] of [ + [sessions, 0o700], + [join(env.stateDir, ".fabric-turns"), 0o700], + [join(sessions, file), 0o600], + [join(env.stateDir, "session-index.json"), 0o600], + [join(env.stateDir, ".fabric-turns", `${id}.json`), 0o600], + ]) { + assert.equal((await stat(path)).mode & 0o777, mode, path); + } +}); + +test("applies the current workspace to a resumed conversation", { skip }, async (t) => { + const env = await fixture(t); + const id = await withRuntime(piInput(env), async (_runtime, output) => output.session_id); + const moved = join(env.root, "moved-workspace"); + await mkdir(moved); + const handle = await new PiSdkSessionFactory().create(piInput({ ...env, workspace: moved }, { sessionRef: reference(id) })); + try { + assert.equal(handle.session.sessionManager.getCwd(), moved); + assert.equal(handle.durable.sessionId, id); + } finally { + await handle.stop(); + } +}); + +async function sessionFile(stateDir) { + const [file] = await readdir(join(stateDir, "sessions")); + return join(stateDir, "sessions", file); +} + +async function nativeEntries(path) { + return (await readFile(path, "utf8")).trim().split("\n").map((line) => JSON.parse(line)).slice(1); +} + +test("requires acknowledgment after a crash left a tool call unfinished", { skip }, async (t) => { + const env = await fixture(t); + const id = await withRuntime(piInput(env), async (runtime, output) => { + await runtime.invoke({ input: "Prepare the invoice." }, invocation("one")); + return output.session_id; + }); + // Simulate a host killed after the model requested a tool but before its result. + const path = await sessionFile(env.stateDir); + const entries = await nativeEntries(path); + const leaf = entries.at(-1).id; + const now = new Date().toISOString(); + await appendFile(path, lines( + { type: "message", id: "crash001", parentId: leaf, timestamp: now, message: user("Send the invoice.").message }, + { type: "message", id: "crash002", parentId: "crash001", timestamp: now, message: assistant("toolUse", [ + { type: "toolCall", id: "call-1", name: "bash", arguments: { command: "send" } }, + ]).message }, + )); + await writeFile(join(env.stateDir, ".fabric-turns", `${id}.json`), JSON.stringify({ + format: "nemo-fabric.pi-turn/v1", session_id: id, state: "running", leaf_id: leaf, + entry_count: entries.length, request_id: "request-crash", invocation_id: "crash", + })); + + const before = env.endpoint.requests.length; + await withRuntime(piInput(env, { sessionRef: reference(id) }), async (runtime, output) => { + assert.equal(output.session_id, id); + assert.equal(output.recovery_warnings.length, 1); + const [warning] = output.recovery_warnings; + assert.equal(warning.code, "session_recovery_required"); + assert.deepEqual(warning.metadata.pending_tool_call_ids, ["call-1"]); + assert.equal(warning.metadata.request_id, "request-crash"); + + const denied = await runtime.invoke({ input: "Continue." }, invocation("two")); + assert.equal(denied.error.code, "session_recovery_required"); + assert.equal(env.endpoint.requests.length, before); + + const allowed = await runtime.invoke({ input: "Continue with the reviewed state.", acknowledge_recovery: true }, + invocation("three")); + assert.equal(allowed.status, "succeeded"); + assert.equal(env.endpoint.requests.length, before + 1); + }); + const sent = lastUserTexts(env.endpoint.requests.at(-1)); + // Acknowledgment sends only the new request; the unfinished one is not resubmitted. + assert.equal(sent.filter((text) => text.includes("Send the invoice")).length, 1); + assert.equal(sent.filter((text) => text.includes("reviewed state")).length, 1); + + // The acknowledged turn completed durably, so the next resume needs no acknowledgment. + await withRuntime(piInput(env, { sessionRef: reference(id) }), async (_runtime, output) => { + assert.deepEqual(output.recovery_warnings, []); + }); +}); + +test("a turn that completed natively before a lost completion record needs no acknowledgment", { skip }, async (t) => { + const env = await fixture(t); + const id = await withRuntime(piInput(env), async (_runtime, output) => output.session_id); + const path = await sessionFile(env.stateDir); + const setup = await nativeEntries(path); + await withRuntime(piInput(env, { sessionRef: reference(id) }), async (runtime) => { + await runtime.invoke({ input: "Finish this." }, invocation("one")); + }); + // Restore a running record from before that turn, as if the host died before marking it complete. + await writeFile(join(env.stateDir, ".fabric-turns", `${id}.json`), JSON.stringify({ + format: "nemo-fabric.pi-turn/v1", session_id: id, state: "running", leaf_id: setup.at(-1).id, + entry_count: setup.length, + })); + await withRuntime(piInput(env, { sessionRef: reference(id) }), async (_runtime, output) => { + assert.deepEqual(output.recovery_warnings, []); + }); +}); + +test("rejects selection without storage or for another adapter before reading state", { skip }, async (t) => { + const env = await fixture(t); + const factory = new PiSdkSessionFactory(); + await assert.rejects( + factory.create(piInput({ ...env, stateDir: undefined }, { sessionRef: reference("anything") })), + { code: "session_storage_required" }, + ); + await assert.rejects( + factory.create(piInput(env, { sessionRef: reference("anything", "nvidia.fabric.hermes") })), + { code: "session_adapter_mismatch" }, + ); + await assert.rejects(factory.create(piInput(env, { sessionRef: reference("unknown") })), { code: "session_not_found" }); + assert.equal(env.endpoint.requests.length, 0); +}); + +for (const [description, corrupt, code] of [ + ["truncated", async (path) => writeFile(path, (await readFile(path, "utf8")).slice(0, -1)), "session_incompatible"], + ["malformed", async (path) => appendFile(path, "{oops\n"), "session_incompatible"], + ["empty", async (path) => writeFile(path, ""), "session_incompatible"], + ["missing", async (path) => rm(path), "session_not_found"], + [ + "an older format", + async (path) => { + const [first, ...rest] = (await readFile(path, "utf8")).split("\n"); + await writeFile(path, [JSON.stringify({ ...JSON.parse(first), version: 2 }), ...rest].join("\n")); + }, + "session_incompatible", + ], + [ + "identity-mismatched", + async (path) => { + const [first, ...rest] = (await readFile(path, "utf8")).split("\n"); + await writeFile(path, [JSON.stringify({ ...JSON.parse(first), id: "someone-else" }), ...rest].join("\n")); + }, + "session_incompatible", + ], + [ + "a symbolic link", + async (path) => { + const copy = `${path}.copy`; + await writeFile(copy, await readFile(path)); + await rm(path); + await symlink(copy, path); + }, + "session_incompatible", + ], +]) { + test(`fails explicitly for ${description} selected state without starting fresh`, { skip }, async (t) => { + const env = await fixture(t); + const id = await withRuntime(piInput(env), async (runtime, output) => { + await runtime.invoke({ input: "Remember Cedar." }, invocation("one")); + return output.session_id; + }); + await corrupt(await sessionFile(env.stateDir)); + const before = await snapshot(env.stateDir); + const requests = env.endpoint.requests.length; + await assert.rejects(new PiSdkSessionFactory().create(piInput(env, { sessionRef: reference(id) })), { code }); + assert.deepEqual(await snapshot(env.stateDir), before); + assert.equal(env.endpoint.requests.length, requests); + }); +} + +for (const [description, index] of [ + ["a duplicate mapping", (id, file) => ({ [id]: file, other: file })], + ["a path escape", (id) => ({ [id]: "../escape.jsonl" })], + ["an unknown format", (id, file) => ({ __format: true, [id]: file })], +]) { + test(`rejects an index with ${description}`, { skip }, async (t) => { + const env = await fixture(t); + const id = await withRuntime(piInput(env), async (_runtime, output) => output.session_id); + const indexPath = join(env.stateDir, "session-index.json"); + const current = JSON.parse(await readFile(indexPath, "utf8")); + const value = index(id, current.sessions[id]); + const format = value.__format ? "other" : current.format; + delete value.__format; + await writeFile(indexPath, JSON.stringify({ format, sessions: value })); + await assert.rejects(new PiSdkSessionFactory().create(piInput(env, { sessionRef: reference(id) })), { + code: "session_incompatible", + }); + }); +} diff --git a/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json b/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json index 52f97acda..da1e90059 100644 --- a/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json +++ b/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json @@ -3445,6 +3445,7 @@ ] }, "service": false, + "session_resume": true, "streaming": false, "updates": false }, @@ -3458,7 +3459,8 @@ "tools.blocked", "skills", "mcp", - "mcp.tool_filters" + "mcp.tool_filters", + "runtime.keep_state" ], "system_instruction_modes": [ "replace" @@ -3727,7 +3729,7 @@ "name": "nemo-fabric-adapters-pi", "version": "0.8.0" }, - "sha256": "1d3f4b6933689530782ba0ebd019ca9af3476a8f9b7d5b955783d0a59b743283", + "sha256": "3350f175bcaafa98d97c8bf7628977bcf4dde504335592bbc8106f1dbbf58989", "source": "adapters/typescript/pi/pi.fabric-adapter.json" }, "nvidia.fabric.qwen": { diff --git a/tests/adapters/test_pi_adapter.py b/tests/adapters/test_pi_adapter.py index 4eea74aec..0f91189c5 100644 --- a/tests/adapters/test_pi_adapter.py +++ b/tests/adapters/test_pi_adapter.py @@ -64,6 +64,7 @@ def test_pi_descriptor_declares_the_supported_surface(): "skills", "mcp", "mcp.tool_filters", + "runtime.keep_state", ] assert descriptor["config"]["system_instruction_modes"] == ["replace"] assert descriptor["settings_schema"]["properties"]["relay_extension_path"] == { @@ -94,6 +95,7 @@ def test_pi_descriptor_declares_the_supported_surface(): "cancellation": False, "updates": False, "service": False, + "session_resume": True, } assert descriptor["tool_definition_schema"] == { diff --git a/tests/e2e/test_pi_resume.py b/tests/e2e/test_pi_resume.py new file mode 100644 index 000000000..4f0acbe17 --- /dev/null +++ b/tests/e2e/test_pi_resume.py @@ -0,0 +1,218 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Pi cold resume through the real SDK, native core, lifecycle host, and Pi store.""" + +import asyncio +import json +from pathlib import Path +from uuid import uuid4 + +import pytest +import pytest_asyncio +import uvicorn +from fastapi import FastAPI, Request +from fastapi.responses import StreamingResponse + +from nemo_fabric import Fabric, FabricConfig, RunRequest, SessionRef +from nemo_fabric.errors import FabricError + +ROOT = Path(__file__).resolve().parents[2] + + +@pytest_asyncio.fixture(name="echo_model", loop_scope="function") +async def echo_model_fixture(unused_tcp_port): + app = FastAPI() + requests = [] + + @app.post("/v1/chat/completions") + async def complete(request: Request): + requests.append(await request.json()) + common = { + "id": f"resume-{len(requests)}", + "object": "chat.completion.chunk", + "created": 0, + "model": "gpt-4.1-mini", + } + chunks = [ + {"choices": [{"index": 0, "delta": {"role": "assistant", "content": f"answer-{len(requests)}"}, "finish_reason": None}]}, + {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}, + ] + body = [f"data: {json.dumps({**common, **chunk})}\n\n" for chunk in chunks] + body.append("data: [DONE]\n\n") + return StreamingResponse(iter(body), media_type="text/event-stream") + + server = uvicorn.Server( + uvicorn.Config( + app, + host="127.0.0.1", + port=unused_tcp_port, + log_config=None, + access_log=False, + lifespan="off", + ) + ) + serving = asyncio.create_task(server.serve()) + try: + async with asyncio.timeout(5): + while not server.started: + await asyncio.sleep(0.01) + yield f"http://127.0.0.1:{unused_tcp_port}/v1", requests + finally: + server.should_exit = True + await asyncio.wait_for(serving, 5) + + +def _config(tmp_path, endpoint, name="pi-resume", keep_state=True): + return FabricConfig.from_mapping( + { + "metadata": {"name": name}, + "harness": {"adapter_id": "nvidia.fabric.pi"}, + "discovery": { + "local_paths": [str(ROOT / "adapters/typescript/pi/pi.fabric-adapter.json")] + }, + "models": { + "default": { + "provider": "openai", + "model": "gpt-4.1-mini", + "api": "openai-completions", + "base_url": endpoint, + "api_key_env": "PI_RESUME_KEY", + } + }, + "tools": {"enabled": []}, + "runtime": {"keep_state": keep_state, "artifacts": str(tmp_path / "artifacts")}, + "environment": { + "provider": "local", + "workspace": str(tmp_path), + "env": {"PI_RESUME_KEY": "local-test-fixture"}, + }, + } + ) + + +def _sent(request): + return json.dumps(request["messages"]) + + +async def test_pi_resume_restores_selected_history_after_agent_rename(tmp_path, echo_model): + endpoint, requests = echo_model + config = _config(tmp_path, endpoint) + nonce = "cedar-" + uuid4().hex + other = "birch-" + uuid4().hex + + async with await Fabric().start_runtime(config, base_dir=tmp_path) as first: + reference = first.session_ref + assert isinstance(reference, SessionRef) + assert reference.adapter_id == "nvidia.fabric.pi" + first_id = first.runtime_id + result = await first.invoke(input=f"Remember the codename {nonce}.") + assert result.status == "succeeded" + assert result.session_ref == reference + saved = reference.to_mapping() + + async with await Fabric().start_runtime(config, base_dir=tmp_path) as second: + assert second.session_ref != reference + assert (await second.invoke(input=f"Remember the codename {other}.")).status == "succeeded" + + renamed = config.model_copy(deep=True) + renamed.metadata.name = "pi-resume-renamed" + selected = SessionRef.from_mapping(saved) + async with await Fabric().start_runtime(renamed, base_dir=tmp_path, session_ref=selected) as resumed: + assert resumed.runtime_id != first_id + assert resumed.session_ref == selected + assert resumed.recovery_warnings == () + result = await resumed.invoke(input="What is the codename?") + assert result.status == "succeeded" + assert result.session_ref == selected + + sent = _sent(requests[-1]) + assert nonce in sent + assert other not in sent + assert sent.count(nonce) == 1 + + async with await Fabric().start_runtime(config, base_dir=tmp_path) as fresh: + assert fresh.session_ref not in (reference, None) + await fresh.invoke(input="Hello.") + assert nonce not in _sent(requests[-1]) + + +async def test_pi_resume_reopens_an_empty_conversation(tmp_path, echo_model): + endpoint, requests = echo_model + config = _config(tmp_path, endpoint) + async with await Fabric().start_runtime(config, base_dir=tmp_path) as first: + reference = first.session_ref + assert reference is not None + assert requests == [] + async with await Fabric().start_runtime(config, base_dir=tmp_path, session_ref=reference) as resumed: + assert resumed.session_ref == reference + assert (await resumed.invoke(input="First prompt.")).status == "succeeded" + + +async def test_pi_without_keep_state_returns_no_reference(tmp_path, echo_model): + endpoint, _requests = echo_model + config = _config(tmp_path, endpoint, keep_state=False) + async with await Fabric().start_runtime(config, base_dir=tmp_path) as runtime: + assert runtime.session_ref is None + result = await runtime.invoke(input="Hello.") + assert result.status == "succeeded" + assert result.session_ref is None + + +async def test_pi_resume_requires_acknowledgment_after_an_unfinished_turn(tmp_path, echo_model): + endpoint, requests = echo_model + config = _config(tmp_path, endpoint) + async with await Fabric().start_runtime(config, base_dir=tmp_path) as first: + reference = first.session_ref + assert (await first.invoke(input="Prepare the invoice.")).status == "succeeded" + + # Simulate a host killed after the model requested a tool and before its result. + state = tmp_path / "artifacts" / ".fabric" / "state" / "nvidia.fabric.pi" + [session_file] = state.glob("*/sessions/*.jsonl") + entries = [json.loads(line) for line in session_file.read_text().splitlines()][1:] + leaf = entries[-1]["id"] + now = "2026-12-01T00:00:00.000Z" + with session_file.open("a") as stream: + for record in ( + {"type": "message", "id": "crash001", "parentId": leaf, "timestamp": now, + "message": {"role": "user", "content": [{"type": "text", "text": "Send the invoice."}], "timestamp": 0}}, + {"type": "message", "id": "crash002", "parentId": "crash001", "timestamp": now, + "message": {"role": "assistant", "stopReason": "toolUse", "api": "openai-completions", + "provider": "openai", "model": "gpt-4.1-mini", "timestamp": 0, + "content": [{"type": "toolCall", "id": "call-1", "name": "bash", "arguments": {}}]}}, + ): + stream.write(json.dumps(record) + "\n") + turns = session_file.parent.parent / ".fabric-turns" / f"{reference.session_id}.json" + turns.write_text(json.dumps({ + "format": "nemo-fabric.pi-turn/v1", "session_id": reference.session_id, "state": "running", + "leaf_id": leaf, "entry_count": len(entries), + })) + + before = len(requests) + async with await Fabric().start_runtime(config, base_dir=tmp_path, session_ref=reference) as resumed: + [warning] = resumed.recovery_warnings + assert warning.code == "session_recovery_required" + denied = await resumed.invoke(input="Continue.") + assert denied.status == "failed" + assert denied.error.code == "session_recovery_required" + assert len(requests) == before + allowed = await resumed.invoke( + request=RunRequest(input="Continue with the reviewed state.", acknowledge_recovery=True) + ) + assert allowed.status == "succeeded" + assert len(requests) == before + 1 + + +async def test_pi_resume_fails_explicitly_for_truncated_history(tmp_path, echo_model): + endpoint, _requests = echo_model + config = _config(tmp_path, endpoint) + async with await Fabric().start_runtime(config, base_dir=tmp_path) as first: + reference = first.session_ref + await first.invoke(input="Remember Cedar.") + [session_file] = (tmp_path / "artifacts").glob(".fabric/state/nvidia.fabric.pi/*/sessions/*.jsonl") + original = session_file.read_bytes()[:-1] + session_file.write_bytes(original) + with pytest.raises(FabricError) as failure: + await Fabric().start_runtime(config, base_dir=tmp_path, session_ref=reference) + assert "session_incompatible" in str(failure.value) + assert session_file.read_bytes() == original