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"); +});