diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 9b1f4c45ef..1807be0bb5 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -568,8 +568,14 @@ describe("CodexAdapterV2 native protocol logging", () => { }, }, }); + yield* protocolLogger({ + direction: "incoming", + stage: "raw", + payload: + '{"method":"thread/event","params":{"http_headers":{"Authorization":"Bearer secret-codex-token"}}}\n', + }); - assert.equal(writes.length, 1); + assert.equal(writes.length, 2); assert.equal(writes[0]?.threadId, threadId); assert.deepEqual(writes[0]?.event, { provider: "codex", @@ -589,6 +595,19 @@ describe("CodexAdapterV2 native protocol logging", () => { }, }, }); + assert.equal(writes[1]?.threadId, threadId); + assert.deepEqual(writes[1]?.event, { + provider: "codex", + protocol: "codex.app-server", + kind: "protocol", + providerSessionId, + event: { + direction: "incoming", + stage: "raw", + payload: + '{"method":"thread/event","params":{"http_headers":{"Authorization":"[REDACTED]"}}}', + }, + }); }), ); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 689d3094f3..b092c578a1 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1167,7 +1167,26 @@ export function redactCodexProtocolValue(value: unknown): unknown { return value.map(redactCodexProtocolValue); } if (value === null || typeof value !== "object") { - return typeof value === "string" && /^Bearer\s+/i.test(value) ? "[REDACTED]" : value; + if (typeof value !== "string") { + return value; + } + if (/^Bearer\s+/i.test(value)) { + return "[REDACTED]"; + } + const trimmed = value.trim(); + if ( + !( + (trimmed.startsWith("{") && trimmed.endsWith("}")) || + (trimmed.startsWith("[") && trimmed.endsWith("]")) + ) + ) { + return value; + } + try { + return JSON.stringify(redactCodexProtocolValue(JSON.parse(trimmed) as unknown)); + } catch { + return value; + } } return Object.fromEntries( Object.entries(value).map(([key, nested]) => [ diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.test.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.test.ts new file mode 100644 index 0000000000..cb9f81d65c --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.test.ts @@ -0,0 +1,102 @@ +import { assert, describe, it } from "@effect/vitest"; +import { ProviderSessionId, ThreadId } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Schema from "effect/Schema"; + +import { + CURSOR_AGENT_SDK_PROTOCOL, + CURSOR_PROVIDER, + CursorAgentSdkRunnerError, +} from "./CursorAgentSdk.ts"; +import { + CursorReplayFrameMismatchError, + makeCursorAgentSdkReplayRunner, +} from "./CursorAdapterV2.testkit.ts"; + +const isCursorAgentSdkRunnerError = Schema.is(CursorAgentSdkRunnerError); +const isCursorReplayFrameMismatchError = Schema.is(CursorReplayFrameMismatchError); + +describe("CursorAdapterV2 replay testkit", () => { + it.effect("fails promptly when a run is followed by an unrelated outbound frame", () => + Effect.gen(function* () { + const agentId = "agent-replay-outbound-mismatch"; + const runId = "run-replay-outbound-mismatch"; + const runner = makeCursorAgentSdkReplayRunner({ + provider: CURSOR_PROVIDER, + protocol: CURSOR_AGENT_SDK_PROTOCOL, + version: "test", + scenario: "unrelated-outbound-after-run-started", + entries: [ + { + type: "expect_outbound", + frame: { + type: "agent.open", + operation: "create", + options: {}, + }, + }, + { + type: "emit_inbound", + frame: { + type: "agent.opened", + agentId, + }, + }, + { + type: "expect_outbound", + frame: { + type: "run.start", + message: "hello", + options: {}, + }, + }, + { + type: "emit_inbound", + frame: { + type: "run.started", + runId, + agentId, + }, + }, + { + type: "expect_outbound", + frame: { + type: "agent.close", + agentId, + }, + }, + ], + }); + const session = yield* runner.open({ + operation: "create", + options: {}, + threadId: ThreadId.make("thread-replay-outbound-mismatch"), + providerSessionId: ProviderSessionId.make("provider-session-replay-outbound-mismatch"), + }); + const run = yield* session.send({ message: "hello" }); + + const exit = yield* Effect.exit(run.wait.pipe(Effect.timeout("100 millis"))); + + assert.isTrue(Exit.isFailure(exit)); + if (Exit.isFailure(exit)) { + const error = Cause.squash(exit.cause); + assert.isTrue(isCursorAgentSdkRunnerError(error)); + if (isCursorAgentSdkRunnerError(error)) { + assert.isTrue(isCursorReplayFrameMismatchError(error.cause)); + if (isCursorReplayFrameMismatchError(error.cause)) { + assert.deepEqual(error.cause.expected, { + type: "run.cancel", + runId, + }); + assert.deepEqual(error.cause.actual, { + type: "agent.close", + agentId, + }); + } + } + } + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts index 1983eb9bc8..cb1e108afc 100644 --- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts @@ -317,6 +317,20 @@ export function makeCursorAgentSdkReplayRunner( ); } if (entry.type === "expect_outbound") { + const expectedCancel = { + type: "run.cancel", + runId, + }; + if (!sameFrame(entry.frame, expectedCancel)) { + return yield* recordFailure( + new CursorReplayFrameMismatchError({ + scenario: transcript.scenario, + cursor, + expected: expectedCancel, + actual: entry.frame, + }), + ); + } const signal = cursorAdvanced; yield* Effect.promise(() => signal.promise); continue; diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index e033dee754..5c22663c8f 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -18,7 +18,7 @@ import { } from "./CheckpointRollbackService.ts"; import { EventSinkV2 } from "./EventSink.ts"; import { layer as idAllocatorLayer } from "./IdAllocator.ts"; -import { ProjectionStoreV2 } from "./ProjectionStore.ts"; +import { ProjectionStoreReadError, ProjectionStoreV2 } from "./ProjectionStore.ts"; import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; import { RuntimePolicyV2 } from "./RuntimePolicy.ts"; @@ -67,7 +67,12 @@ it.effect("rejects a non-ready checkpoint before opening a session or restoring }) .pipe(Effect.flip); - assert.equal(error.cause, "The persisted rollback target is incomplete or no longer valid."); + assert.equal(error.reason, "rollback-target-invalid"); + assert.equal( + error.message, + `Rollback target ${checkpointId} for provider thread ${providerThreadId} on thread ${threadId} is incomplete or invalid.`, + ); + assert.equal(error.cause, undefined); assert.equal(resolveRuntimePolicy.mock.calls.length, 0); assert.equal(open.mock.calls.length, 0); assert.equal(restore.mock.calls.length, 0); @@ -132,7 +137,12 @@ it.effect("rejects a rollback when another provider thread became active", () => }) .pipe(Effect.flip); - assert.equal(error.cause, "The active provider changed before the rollback could execute."); + assert.equal(error.reason, "active-provider-changed"); + assert.equal( + error.message, + `Active provider changed before rollback target ${checkpointId} could execute on thread ${threadId}.`, + ); + assert.equal(error.cause, undefined); assert.equal(resolveRuntimePolicy.mock.calls.length, 0); assert.equal(open.mock.calls.length, 0); assert.equal(restore.mock.calls.length, 0); @@ -199,9 +209,123 @@ it.effect("rejects a rollback when provider selection changed before execution", }) .pipe(Effect.flip); - assert.equal(error.cause, "The active provider changed before the rollback could execute."); + assert.equal(error.reason, "active-provider-changed"); + assert.equal( + error.message, + `Active provider changed before rollback target ${checkpointId} could execute on thread ${threadId}.`, + ); + assert.equal(error.cause, undefined); assert.equal(resolveRuntimePolicy.mock.calls.length, 0); assert.equal(open.mock.calls.length, 0); assert.equal(restore.mock.calls.length, 0); }).pipe(Effect.provide(testLayer)); }); + +it.effect("reports a missing provider turn as a structured rollback failure", () => { + const threadId = ThreadId.make("thread:rollback-provider-turn-unavailable"); + const providerThreadId = ProviderThreadId.make( + "provider-thread:rollback-provider-turn-unavailable", + ); + const providerSessionId = ProviderSessionId.make( + "provider-session:rollback-provider-turn-unavailable", + ); + const checkpointId = CheckpointId.make("checkpoint:rollback-provider-turn-unavailable"); + const scopeId = CheckpointScopeId.make("checkpoint-scope:rollback-provider-turn-unavailable"); + const providerInstanceId = ProviderInstanceId.make("provider_rollback_provider_turn_unavailable"); + const restore = vi.fn(() => Effect.die("checkpoint restore must not run")); + const projection = { + thread: { + activeProviderThreadId: providerThreadId, + modelSelection: { instanceId: providerInstanceId, model: "test-model" }, + }, + providerThreads: [{ id: providerThreadId, providerSessionId, providerInstanceId }], + providerSessions: [], + checkpoints: [{ id: checkpointId, scopeId, status: "ready", appRunOrdinal: 1 }], + checkpointScopes: [{ id: scopeId }], + runs: [], + attempts: [], + providerTurns: [], + } as unknown as OrchestrationV2ThreadProjection; + const testLayer = checkpointRollbackServiceLayer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(CheckpointServiceV2)({ restore }), + Layer.mock(EventSinkV2)({}), + idAllocatorLayer, + Layer.mock(ProjectionStoreV2)({ + getThreadProjection: () => Effect.succeed(projection), + }), + Layer.mock(ProviderSessionManagerV2)({ + open: () => Effect.succeed({} as never), + }), + Layer.mock(RuntimePolicyV2)({ + resolve: () => Effect.succeed({} as never), + }), + ), + ), + ); + + return Effect.gen(function* () { + const service = yield* CheckpointRollbackServiceV2; + const error = yield* service + .execute({ + threadId, + providerThreadId, + checkpointId, + scopeId, + }) + .pipe(Effect.flip); + + assert.equal(error.reason, "provider-turn-unavailable"); + assert.equal( + error.message, + `Provider turn for rollback target ${checkpointId} is unavailable on provider thread ${providerThreadId}.`, + ); + assert.equal(error.cause, undefined); + assert.equal(restore.mock.calls.length, 0); + }).pipe(Effect.provide(testLayer)); +}); + +it.effect("wraps underlying failures with an unexpected-failure reason and cause", () => { + const threadId = ThreadId.make("thread:rollback-unexpected-failure"); + const providerThreadId = ProviderThreadId.make("provider-thread:rollback-unexpected-failure"); + const checkpointId = CheckpointId.make("checkpoint:rollback-unexpected-failure"); + const scopeId = CheckpointScopeId.make("checkpoint-scope:rollback-unexpected-failure"); + const projectionError = new ProjectionStoreReadError({ + threadId, + cause: new Error("database read failed"), + }); + const testLayer = checkpointRollbackServiceLayer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(CheckpointServiceV2)({}), + Layer.mock(EventSinkV2)({}), + idAllocatorLayer, + Layer.mock(ProjectionStoreV2)({ + getThreadProjection: () => Effect.fail(projectionError), + }), + Layer.mock(ProviderSessionManagerV2)({}), + Layer.mock(RuntimePolicyV2)({}), + ), + ), + ); + + return Effect.gen(function* () { + const service = yield* CheckpointRollbackServiceV2; + const error = yield* service + .execute({ + threadId, + providerThreadId, + checkpointId, + scopeId, + }) + .pipe(Effect.flip); + + assert.equal(error.reason, "unexpected-failure"); + assert.equal( + error.message, + `Failed to execute rollback target ${checkpointId} on provider thread ${providerThreadId} for thread ${threadId}.`, + ); + assert.strictEqual(error.cause, projectionError); + }).pipe(Effect.provide(testLayer)); +}); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index c5a01ea03b..1a0acb9007 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -22,12 +22,33 @@ import { RuntimePolicyV2 } from "./RuntimePolicy.ts"; export class CheckpointRollbackExecutionError extends Schema.TaggedErrorClass()( "CheckpointRollbackExecutionError", { + reason: Schema.Literals([ + "rollback-target-invalid", + "active-provider-changed", + "provider-turn-unavailable", + "unexpected-failure", + ]), threadId: ThreadId, providerThreadId: ProviderThreadId, checkpointId: CheckpointId, cause: Schema.optional(Schema.Defect()), }, -) {} +) { + override get message(): string { + switch (this.reason) { + case "rollback-target-invalid": + return `Rollback target ${this.checkpointId} for provider thread ${this.providerThreadId} on thread ${this.threadId} is incomplete or invalid.`; + case "active-provider-changed": + return `Active provider changed before rollback target ${this.checkpointId} could execute on thread ${this.threadId}.`; + case "provider-turn-unavailable": + return `Provider turn for rollback target ${this.checkpointId} is unavailable on provider thread ${this.providerThreadId}.`; + case "unexpected-failure": + return `Failed to execute rollback target ${this.checkpointId} on provider thread ${this.providerThreadId} for thread ${this.threadId}.`; + } + } +} + +const isCheckpointRollbackExecutionError = Schema.is(CheckpointRollbackExecutionError); export interface CheckpointRollbackServiceV2Shape { readonly execute: (input: { @@ -85,10 +106,10 @@ export const layer: Layer.Layer< checkpoint.status !== "ready" ) { return yield* new CheckpointRollbackExecutionError({ + reason: "rollback-target-invalid", threadId: input.threadId, providerThreadId: input.providerThreadId, checkpointId: input.checkpointId, - cause: "The persisted rollback target is incomplete or no longer valid.", }); } if ( @@ -96,10 +117,10 @@ export const layer: Layer.Layer< providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId ) { return yield* new CheckpointRollbackExecutionError({ + reason: "active-provider-changed", threadId: input.threadId, providerThreadId: input.providerThreadId, checkpointId: input.checkpointId, - cause: "The active provider changed before the rollback could execute.", }); } @@ -145,10 +166,10 @@ export const layer: Layer.Layer< ); if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) { return yield* new CheckpointRollbackExecutionError({ + reason: "provider-turn-unavailable", threadId: input.threadId, providerThreadId: input.providerThreadId, checkpointId: input.checkpointId, - cause: "The provider rollback turn is unavailable.", }); } return { @@ -251,9 +272,10 @@ export const layer: Layer.Layer< execute: (input) => execute(input).pipe( Effect.mapError((cause) => - Schema.is(CheckpointRollbackExecutionError)(cause) + isCheckpointRollbackExecutionError(cause) ? cause : new CheckpointRollbackExecutionError({ + reason: "unexpected-failure", threadId: input.threadId, providerThreadId: input.providerThreadId, checkpointId: input.checkpointId, diff --git a/apps/server/src/orchestration-v2/RuntimeRequestService.test.ts b/apps/server/src/orchestration-v2/RuntimeRequestService.test.ts index b6420f6e3e..ba5735d8be 100644 --- a/apps/server/src/orchestration-v2/RuntimeRequestService.test.ts +++ b/apps/server/src/orchestration-v2/RuntimeRequestService.test.ts @@ -4,6 +4,7 @@ import { ProviderSessionId, RuntimeRequestId, ThreadId, + type OrchestrationV2RuntimeRequest, type OrchestrationV2ThreadProjection, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -13,12 +14,63 @@ import * as Option from "effect/Option"; import type { ProviderAdapterV2RuntimeRequestResponseInput } from "./ProviderAdapter.ts"; import { ProjectionStoreV2 } from "./ProjectionStore.ts"; -import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; +import { + ProviderSessionLookupError, + ProviderSessionManagerV2, + type ProviderSessionManagerV2Shape, +} from "./ProviderSessionManager.ts"; import { layer as runtimeRequestServiceLayer, + RuntimeRequestResponseExecutionError, RuntimeRequestServiceV2, } from "./RuntimeRequestService.ts"; +function projectionWithRuntimeRequest( + runtimeRequest?: OrchestrationV2RuntimeRequest, +): OrchestrationV2ThreadProjection { + return { + runtimeRequests: runtimeRequest === undefined ? [] : [runtimeRequest], + } as unknown as OrchestrationV2ThreadProjection; +} + +function resolvedRuntimeRequest( + requestId: RuntimeRequestId, + providerSessionId: ProviderSessionId, +): OrchestrationV2RuntimeRequest { + return { + id: requestId, + nodeId: NodeId.make(`node-${requestId}`), + providerTurnId: null, + nativeRequestRef: null, + kind: "command", + status: "resolved", + responseCapability: { + type: "live", + providerSessionId, + }, + createdAt: DateTime.makeUnsafe("2026-07-29T00:00:00.000Z"), + resolvedAt: DateTime.makeUnsafe("2026-07-29T00:00:01.000Z"), + }; +} + +function runtimeRequestTestLayer( + projection: OrchestrationV2ThreadProjection, + getSession: ProviderSessionManagerV2Shape["get"], +) { + return runtimeRequestServiceLayer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ProjectionStoreV2)({ + getThreadProjection: () => Effect.succeed(projection), + }), + Layer.mock(ProviderSessionManagerV2)({ + get: getSession, + }), + ), + ), + ); +} + it.effect("forwards orchestrator-resolved runtime requests to the live adapter", () => { const threadId = ThreadId.make("thread-runtime-request-resolved"); const providerSessionId = ProviderSessionId.make("provider-session-runtime-request-resolved"); @@ -138,8 +190,109 @@ it.effect("rejects expired runtime requests before invoking the live adapter", ( }) .pipe(Effect.flip); - assert.equal(error.cause, "The runtime request is not ready for response execution."); + assert.equal(error.reason, "request-not-ready"); + assert.equal( + error.message, + `Runtime request ${requestId} on thread ${threadId} is not ready for response execution.`, + ); + assert.isUndefined(error.cause); assert.equal(getSession.mock.calls.length, 0); assert.equal(respondToRuntimeRequest.mock.calls.length, 0); }).pipe(Effect.provide(testLayer)); }); + +it.effect("classifies runtime request response validation failures", () => { + const threadId = ThreadId.make("thread-runtime-request-validation"); + const providerSessionId = ProviderSessionId.make("provider-session-runtime-request-validation"); + const otherProviderSessionId = ProviderSessionId.make( + "provider-session-runtime-request-validation-other", + ); + const requestId = RuntimeRequestId.make("request-validation"); + const unexpectedGetSession = vi.fn(() => Effect.succeed(Option.none())); + const missingLayer = runtimeRequestTestLayer( + projectionWithRuntimeRequest(), + unexpectedGetSession, + ); + const notResumableLayer = runtimeRequestTestLayer( + projectionWithRuntimeRequest(resolvedRuntimeRequest(requestId, otherProviderSessionId)), + unexpectedGetSession, + ); + const inactiveLayer = runtimeRequestTestLayer( + projectionWithRuntimeRequest(resolvedRuntimeRequest(requestId, providerSessionId)), + () => Effect.succeed(Option.none()), + ); + const respond = Effect.gen(function* () { + const service = yield* RuntimeRequestServiceV2; + return yield* service + .respond({ + threadId, + providerSessionId, + requestId, + decision: "accept", + }) + .pipe(Effect.flip); + }); + + return Effect.gen(function* () { + const missing = yield* respond.pipe(Effect.provide(missingLayer)); + assert.equal(missing.reason, "request-missing"); + assert.equal( + missing.message, + `Runtime request ${requestId} no longer exists on thread ${threadId}.`, + ); + assert.isUndefined(missing.cause); + + const notResumable = yield* respond.pipe(Effect.provide(notResumableLayer)); + assert.equal(notResumable.reason, "request-not-resumable"); + assert.equal( + notResumable.message, + `Runtime request ${requestId} on thread ${threadId} is not resumable on provider session ${providerSessionId}.`, + ); + assert.isUndefined(notResumable.cause); + + const inactive = yield* respond.pipe(Effect.provide(inactiveLayer)); + assert.equal(inactive.reason, "provider-session-not-active"); + assert.equal( + inactive.message, + `Provider session ${providerSessionId} is not active for runtime request ${requestId} on thread ${threadId}.`, + ); + assert.isUndefined(inactive.cause); + assert.equal(unexpectedGetSession.mock.calls.length, 0); + }); +}); + +it.effect("preserves genuine provider session lookup failures as the cause", () => { + const threadId = ThreadId.make("thread-runtime-request-lookup-failure"); + const providerSessionId = ProviderSessionId.make( + "provider-session-runtime-request-lookup-failure", + ); + const requestId = RuntimeRequestId.make("request-lookup-failure"); + const lookupFailure = new ProviderSessionLookupError({ + providerSessionId, + cause: "lookup failed", + }); + const testLayer = runtimeRequestTestLayer( + projectionWithRuntimeRequest(resolvedRuntimeRequest(requestId, providerSessionId)), + () => Effect.fail(lookupFailure), + ); + + return Effect.gen(function* () { + const service = yield* RuntimeRequestServiceV2; + const error = yield* service + .respond({ + threadId, + providerSessionId, + requestId, + decision: "accept", + }) + .pipe(Effect.flip); + + assert.instanceOf(error, RuntimeRequestResponseExecutionError); + assert.equal(error.reason, "unexpected-failure"); + assert.equal( + error.message, + `Failed to respond to runtime request ${requestId} on thread ${threadId} via provider session ${providerSessionId}.`, + ); + assert.strictEqual(error.cause, lookupFailure); + }).pipe(Effect.provide(testLayer)); +}); diff --git a/apps/server/src/orchestration-v2/RuntimeRequestService.ts b/apps/server/src/orchestration-v2/RuntimeRequestService.ts index 81647140d3..214db5fd2f 100644 --- a/apps/server/src/orchestration-v2/RuntimeRequestService.ts +++ b/apps/server/src/orchestration-v2/RuntimeRequestService.ts @@ -17,11 +17,36 @@ import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; export class RuntimeRequestResponseExecutionError extends Schema.TaggedErrorClass()( "RuntimeRequestResponseExecutionError", { + reason: Schema.Literals([ + "request-missing", + "request-not-ready", + "request-not-resumable", + "provider-session-not-active", + "unexpected-failure", + ]), threadId: ThreadId, + providerSessionId: ProviderSessionId, requestId: RuntimeRequestId, cause: Schema.optional(Schema.Defect()), }, -) {} +) { + override get message(): string { + switch (this.reason) { + case "request-missing": + return `Runtime request ${this.requestId} no longer exists on thread ${this.threadId}.`; + case "request-not-ready": + return `Runtime request ${this.requestId} on thread ${this.threadId} is not ready for response execution.`; + case "request-not-resumable": + return `Runtime request ${this.requestId} on thread ${this.threadId} is not resumable on provider session ${this.providerSessionId}.`; + case "provider-session-not-active": + return `Provider session ${this.providerSessionId} is not active for runtime request ${this.requestId} on thread ${this.threadId}.`; + case "unexpected-failure": + return `Failed to respond to runtime request ${this.requestId} on thread ${this.threadId} via provider session ${this.providerSessionId}.`; + } + } +} + +const isRuntimeRequestResponseExecutionError = Schema.is(RuntimeRequestResponseExecutionError); export interface RuntimeRequestServiceV2Shape { readonly respond: (input: { @@ -57,18 +82,20 @@ export const layer: Layer.Layer< ); if (request === undefined) { return yield* new RuntimeRequestResponseExecutionError({ + reason: "request-missing", threadId: input.threadId, + providerSessionId: input.providerSessionId, requestId: input.requestId, - cause: "The runtime request no longer exists.", }); } // Dispatch validates the request while it is pending, then persists the // resolved projection before this effect is executed. if (request.status !== "resolved") { return yield* new RuntimeRequestResponseExecutionError({ + reason: "request-not-ready", threadId: input.threadId, + providerSessionId: input.providerSessionId, requestId: input.requestId, - cause: "The runtime request is not ready for response execution.", }); } if ( @@ -76,17 +103,19 @@ export const layer: Layer.Layer< request.responseCapability.providerSessionId !== input.providerSessionId ) { return yield* new RuntimeRequestResponseExecutionError({ + reason: "request-not-resumable", threadId: input.threadId, + providerSessionId: input.providerSessionId, requestId: input.requestId, - cause: "The runtime request is not resumable on the recorded provider session.", }); } const session = yield* sessions.get(input.providerSessionId); if (Option.isNone(session)) { return yield* new RuntimeRequestResponseExecutionError({ + reason: "provider-session-not-active", threadId: input.threadId, + providerSessionId: input.providerSessionId, requestId: input.requestId, - cause: `Provider session ${input.providerSessionId} is not active.`, }); } yield* session.value.respondToRuntimeRequest({ @@ -96,10 +125,12 @@ export const layer: Layer.Layer< }); }).pipe( Effect.mapError((cause) => - Schema.is(RuntimeRequestResponseExecutionError)(cause) + isRuntimeRequestResponseExecutionError(cause) ? cause : new RuntimeRequestResponseExecutionError({ + reason: "unexpected-failure", threadId: input.threadId, + providerSessionId: input.providerSessionId, requestId: input.requestId, cause, }),