Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion adapters/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
2 changes: 2 additions & 0 deletions adapters/typescript/common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
export {
LifecycleError,
serve,
type AdapterRecoveryWarning,
type AdapterRuntime,
type AdapterRuntimeFactory,
type AdapterStartInput,
type AdapterStartOutput,
type LifecycleHostOptions,
} from "./lifecycle.js";

Expand Down
79 changes: 75 additions & 4 deletions adapters/typescript/common/src/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>;
/** Start the runtime; return session output only when it opened a durable native session. */
start(input: AdapterStartInput): Promise<void | AdapterStartOutput>;
invoke(request: AgentRunRequest, context: RuntimeContext): Promise<AgentRunResult>;
stop(): Promise<void>;
check?(level: CheckLevel): Promise<AdapterCheckResult>;
Expand Down Expand Up @@ -222,6 +243,43 @@ function decodeInvocation(payload: Record<string, unknown>): {
};
}

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<T>(operation: string, call: () => T | Promise<T>): Promise<T> {
try {
return await call();
Expand Down Expand Up @@ -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;
}
Expand All @@ -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) {
Expand Down
105 changes: 105 additions & 0 deletions adapters/typescript/common/test/lifecycle.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
58 changes: 57 additions & 1 deletion adapters/typescript/pi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions adapters/typescript/pi/pi.fabric-adapter.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
"tools.blocked",
"skills",
"mcp",
"mcp.tool_filters"
"mcp.tool_filters",
"runtime.keep_state"
],
"system_instruction_modes": ["replace"]
},
Expand Down Expand Up @@ -201,6 +202,7 @@
"streaming": false,
"cancellation": false,
"updates": false,
"service": false
"service": false,
"session_resume": true
}
}
Loading
Loading