From 27da49519fd7be147cdcba7eefbf4c511ec456ea Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 20 Jun 2026 17:06:29 -0700 Subject: [PATCH] Share Codex sessions across orchestration threads - Track explicit thread-to-session bindings and detach without stopping siblings - Apply runtime settings per Codex thread and filter multiplexed events by turn - Add migration, projection, lifecycle, and concurrency coverage --- ...rchestration-v2-application-integration.md | 33 +- .../Adapters/CodexAdapterV2.test.ts | 56 +- .../Adapters/CodexAdapterV2.ts | 138 ++-- .../Adapters/OpenCodeAdapterV2.ts | 4 +- .../src/orchestration-v2/EffectOutbox.ts | 8 +- .../src/orchestration-v2/EffectWorker.ts | 6 +- apps/server/src/orchestration-v2/EventSink.ts | 12 +- .../src/orchestration-v2/IdAllocator.ts | 7 + .../src/orchestration-v2/Orchestrator.ts | 200 ++++-- .../orchestration-v2/ProjectionMaintenance.ts | 1 + .../orchestration-v2/ProjectionStore.test.ts | 126 +++- .../src/orchestration-v2/ProjectionStore.ts | 38 +- .../src/orchestration-v2/ProviderAdapter.ts | 16 + .../ProviderSessionManager.test.ts | 250 ++++++- .../ProviderSessionManager.ts | 679 +++++++++++++++--- .../ProviderTurnStartService.ts | 19 +- .../RunExecutionService.test.ts | 137 ++++ .../orchestration-v2/RunExecutionService.ts | 185 ++++- .../testkit/OrchestratorScenario.ts | 2 +- .../testkit/fixtures/shared.ts | 1 + .../codex_transcript.ndjson | 11 +- .../codex_transcript.ndjson | 15 +- .../codex_transcript.ndjson | 19 +- .../codex_transcript.ndjson | 34 +- apps/server/src/persistence/Migrations.ts | 29 +- .../033_034_OrchestrationV2.test.ts | 46 ++ ..._OrchestrationV2ProviderSessionBindings.ts | 27 + .../web/src/routes/debug.orchestration-v2.tsx | 8 + packages/contracts/src/orchestrationV2.ts | 32 +- .../effect-codex-app-server/src/replay.ts | 17 + 30 files changed, 1798 insertions(+), 358 deletions(-) create mode 100644 apps/server/src/orchestration-v2/RunExecutionService.test.ts create mode 100644 apps/server/src/persistence/Migrations/036_OrchestrationV2ProviderSessionBindings.ts diff --git a/.plans/21-orchestration-v2-application-integration.md b/.plans/21-orchestration-v2-application-integration.md index 3b842c6cb9..874829965a 100644 --- a/.plans/21-orchestration-v2-application-integration.md +++ b/.plans/21-orchestration-v2-application-integration.md @@ -163,6 +163,24 @@ Use these field rules: - adapter lookup always uses `providerInstanceId` - capability and protocol-specific behavior uses `driver` only at adapter and presentation boundaries +### Provider process residency and thread multiplexing + +Make process sharing a provider capability, not an orchestrator special case: + +- when `supportsMultipleProviderThreadsPerSession` is true, derive one stable provider-session ID per configured provider instance +- when it is false, allocate an isolated provider session per app thread +- Codex enables sharing now; ACP, Claude, Cursor, and OpenCode remain isolated until their adapters are independently proven multiplex-safe +- model selection, cwd, runtime policy, and MCP authorization are applied on thread start/resume/fork rather than process launch +- the manager tracks the loaded native thread configuration per app thread, so reattachment or a model/cwd/policy change reapplies thread-scoped settings without redundantly resuming unchanged threads +- provider-session projections use explicit many-to-many thread bindings +- archiving, deleting, or switching one thread detaches that binding; it does not release a shared runtime used by sibling threads +- the manager owns one consumer of each provider process event stream and broadcasts events to run subscribers +- each run filters broadcast events by app thread, run attempt, provider thread, provider turn, and subagent lineage before ingestion +- reaping uses aggregate activity: a shared process stays resident while any attached thread is active, then closes after the normal idle timeout +- full release remains an internal runtime lifecycle operation for process failure, server shutdown, or idle reap + +This is an orchestration capability even when only one adapter enables it. Adding ACP or Claude sharing later must require only adapter capability and multiplex-safety work, not a new orchestrator path. + ### 3. Complete the V2 command and event vocabulary Add V2-native domain commands and events for: @@ -174,7 +192,7 @@ Add V2-native domain commands and events for: - runtime mode - interaction mode - model-selection changes -- explicit session release +- explicit thread detachment from a provider session - provider switching Extend thread and shell projections with: @@ -206,7 +224,7 @@ Introduce a durable orchestration-effect outbox for operations such as: - provider interrupt - runtime-request response - provider rollback and fork -- session release +- provider-session detach - checkpoint capture - terminal cleanup - attachment cleanup @@ -255,6 +273,9 @@ Add coverage for: - more than 100 turn items in one run - projection replay equivalence - lifecycle command projection behavior +- capability-driven shared versus isolated provider-session identity +- two concurrent app threads sharing one Codex runtime without cross-run event ingestion +- detaching one thread without closing the sibling runtime, followed by idle reap after the last detach ### Shape 1 exit gate @@ -345,7 +366,7 @@ Create `ThreadLifecycleService` around the Shape 1 lifecycle commands. Archive behavior: - commit archive state -- enqueue release of live provider sessions +- enqueue detachment from live provider sessions - enqueue terminal closure - remove the thread from the active shell projection @@ -359,7 +380,7 @@ Delete behavior: - commit a tombstone first - cancel queued or running work -- release provider sessions +- detach the deleted thread from provider sessions - close terminal history according to current product semantics - clean unreferenced attachments - revoke MCP credentials @@ -519,7 +540,7 @@ Replace V1 and debug V2 endpoints with one production API containing: - rollback - fork and merge-back - provider switch -- session release +- provider-session detach Use final unversioned method names. Do not retain compatibility aliases. @@ -683,7 +704,7 @@ Update client-runtime operations for: - rollback - fork and merge-back - provider switching -- session release +- provider-session detach Commands use final V2 identifiers and receipt semantics directly. diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 398ab91b70..f73ddffd4f 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -23,7 +23,7 @@ import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger. import { buildCodexTurnStartParams, CODEX_DRIVER_KIND, - codexAppServerMcpLaunchConfig, + codexThreadRuntimeParams, makeCodexAppServerProtocolLogger, makeCodexAppServerSpawnCommand, projectCodexDynamicToolItem, @@ -82,7 +82,7 @@ describe("CodexAdapterV2 runtime policy", () => { }); describe("CodexAdapterV2 process spawning", () => { - it("injects the thread-scoped MCP endpoint and bearer token", () => { + it("injects cwd, model, and MCP authorization into thread-scoped params", () => { const threadId = ThreadId.make("thread-codex-mcp"); McpProviderSession.setMcpProviderSession({ environmentId: EnvironmentId.make("environment-codex-mcp"), @@ -94,17 +94,31 @@ describe("CodexAdapterV2 process spawning", () => { }); try { - assert.deepEqual(codexAppServerMcpLaunchConfig(threadId), { - args: [ - "-c", - "mcp_servers.t3-code.url=http://127.0.0.1:43123/mcp", - "-c", - 'mcp_servers.t3-code.bearer_token_env_var="T3_MCP_BEARER_TOKEN"', - ], - environment: { - T3_MCP_BEARER_TOKEN: "secret-codex-token", + assert.deepEqual( + codexThreadRuntimeParams({ + threadId, + modelSelection: { model: "gpt-5.4" }, + runtimePolicy: { + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace/thread-codex-mcp", + }, + }), + { + cwd: "/workspace/thread-codex-mcp", + model: "gpt-5.4", + config: { + mcp_servers: { + "t3-code": { + url: "http://127.0.0.1:43123/mcp", + http_headers: { + Authorization: "Bearer secret-codex-token", + }, + }, + }, + }, }, - }); + ); } finally { McpProviderSession.clearMcpProviderSession(threadId); } @@ -248,7 +262,14 @@ describe("CodexAdapterV2 native protocol logging", () => { yield* protocolLogger({ direction: "incoming", stage: "decoded", - payload: { method: "thread/event", params: { id: "evt-1" } }, + payload: { + method: "thread/event", + params: { + id: "evt-1", + http_headers: { Authorization: "Bearer secret-codex-token" }, + usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 }, + }, + }, }); assert.equal(writes.length, 1); @@ -261,7 +282,14 @@ describe("CodexAdapterV2 native protocol logging", () => { event: { direction: "incoming", stage: "decoded", - payload: { method: "thread/event", params: { id: "evt-1" } }, + payload: { + method: "thread/event", + params: { + id: "evt-1", + http_headers: { Authorization: "[REDACTED]" }, + usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 }, + }, + }, }, }); }), diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index ff37655da9..30791b36f8 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -769,24 +769,35 @@ export class CodexAppServerClientFactory extends Context.Service< CodexAppServerClientFactoryShape >()("t3/orchestration-v2/Adapters/CodexAdapterV2/CodexAppServerClientFactory") {} -export function codexAppServerMcpLaunchConfig(threadId: ThreadId): { - readonly args: ReadonlyArray; - readonly environment: NodeJS.ProcessEnv; -} | null { - const session = McpProviderSession.readMcpProviderSession(threadId); - return session === undefined - ? null - : { - args: [ - "-c", - `mcp_servers.t3-code.url=${session.endpoint}`, - "-c", - 'mcp_servers.t3-code.bearer_token_env_var="T3_MCP_BEARER_TOKEN"', - ], - environment: { - T3_MCP_BEARER_TOKEN: session.authorizationHeader.replace(/^Bearer\s+/, ""), - }, - }; +export function codexThreadRuntimeParams(input: { + readonly threadId: ThreadId | null; + readonly modelSelection?: { readonly model: string }; + readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy; +}): { + readonly cwd?: string; + readonly model?: string; + readonly config?: Readonly>; +} { + const mcpSession = + input.threadId === null ? undefined : McpProviderSession.readMcpProviderSession(input.threadId); + return { + ...(input.runtimePolicy?.cwd == null ? {} : { cwd: input.runtimePolicy.cwd }), + ...(input.modelSelection === undefined ? {} : { model: input.modelSelection.model }), + ...(mcpSession === undefined + ? {} + : { + config: { + mcp_servers: { + "t3-code": { + url: mcpSession.endpoint, + http_headers: { + Authorization: mcpSession.authorizationHeader, + }, + }, + }, + }, + }), + }; } export const makeCodexAppServerSpawnCommand = Effect.fn( @@ -826,22 +837,11 @@ export const makeCodexAppServerClientFactoryCommandLayer = ( open: (input) => Effect.gen(function* () { const scope = yield* Scope.Scope; - const mcp = codexAppServerMcpLaunchConfig(input.threadId); const command = yield* makeCodexAppServerSpawnCommand({ command: options.command, - args: [...(options.args ?? []), ...(mcp?.args ?? [])], - ...((input.runtimePolicy.cwd ?? options.cwd) === undefined - ? {} - : { cwd: input.runtimePolicy.cwd ?? options.cwd }), - ...(options.env === undefined && mcp === null - ? {} - : { - env: { - ...options.env, - ...mcp?.environment, - }, - extendEnv: true, - }), + args: [...(options.args ?? [])], + ...(options.cwd === undefined ? {} : { cwd: options.cwd }), + ...(options.env === undefined ? {} : { env: options.env, extendEnv: true }), }); const handle = yield* spawner.spawn(command).pipe( Effect.provideService(Scope.Scope, scope), @@ -881,13 +881,39 @@ export function makeCodexAppServerProtocolLogger(input: { protocol: "codex.app-server", kind: "protocol", providerSessionId: input.providerSessionId, - event, + event: redactCodexProtocolValue(event), }, input.threadId, ) .pipe(Effect.ignore); } +export function redactCodexProtocolValue(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(redactCodexProtocolValue); + } + if (value === null || typeof value !== "object") { + return typeof value === "string" && /^Bearer\s+/i.test(value) ? "[REDACTED]" : value; + } + return Object.fromEntries( + Object.entries(value).map(([key, nested]) => [ + key, + isSensitiveCodexProtocolKey(key) ? "[REDACTED]" : redactCodexProtocolValue(nested), + ]), + ); +} + +function isSensitiveCodexProtocolKey(key: string): boolean { + const normalized = key.replace(/[^a-z0-9]/gi, "").toLowerCase(); + return ( + normalized.endsWith("authorization") || + normalized.endsWith("apikey") || + normalized.endsWith("token") || + normalized.endsWith("password") || + normalized.endsWith("secret") + ); +} + export const codexAppServerClientFactoryFromSettingsLayer: Layer.Layer< CodexAppServerClientFactory, never, @@ -906,16 +932,13 @@ export const codexAppServerClientFactoryFromSettingsLayer: Layer.Layer< open: (input) => Effect.gen(function* () { const scope = yield* Scope.Scope; - const mcp = codexAppServerMcpLaunchConfig(input.threadId); const environment = { ...input.environment, ...(input.settings.homePath ? { CODEX_HOME: input.settings.homePath } : {}), - ...mcp?.environment, }; const command = yield* makeCodexAppServerSpawnCommand({ command: input.settings.binaryPath || "codex", - args: ["app-server", ...(mcp?.args ?? [])], - ...(input.runtimePolicy.cwd === null ? {} : { cwd: input.runtimePolicy.cwd }), + args: ["app-server"], env: environment, }); const handle = yield* spawner.spawn(command).pipe( @@ -3876,7 +3899,16 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi events: Stream.fromEffectRepeat(Queue.take(events)), ensureThread: (threadInput) => ensureInitialized.pipe( - Effect.andThen(client.request("thread/start", {})), + Effect.andThen( + client.request( + "thread/start", + codexThreadRuntimeParams({ + threadId: threadInput.threadId, + modelSelection: threadInput.modelSelection, + runtimePolicy: threadInput.runtimePolicy, + }), + ), + ), Effect.map( (response): OrchestrationV2ProviderThread => providerThreadFromCodexThread({ @@ -3905,7 +3937,20 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi } const response = yield* ensureInitialized.pipe( - Effect.andThen(client.request("thread/resume", { threadId: nativeThreadId })), + Effect.andThen( + client.request("thread/resume", { + threadId: nativeThreadId, + ...codexThreadRuntimeParams({ + threadId: threadInput.threadId ?? threadInput.providerThread.appThreadId, + ...(threadInput.modelSelection === undefined + ? {} + : { modelSelection: threadInput.modelSelection }), + ...(threadInput.runtimePolicy === undefined + ? {} + : { runtimePolicy: threadInput.runtimePolicy }), + }), + }), + ), ); return { ...threadInput.providerThread, @@ -4335,7 +4380,20 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi Effect.gen(function* () { const threadId = yield* getNativeThreadId(threadInput.sourceProviderThread); const response = yield* ensureInitialized.pipe( - Effect.andThen(client.request("thread/fork", { threadId })), + Effect.andThen( + client.request("thread/fork", { + threadId, + ...codexThreadRuntimeParams({ + threadId: threadInput.targetThreadId, + ...(threadInput.modelSelection === undefined + ? {} + : { modelSelection: threadInput.modelSelection }), + ...(threadInput.runtimePolicy === undefined + ? {} + : { runtimePolicy: threadInput.runtimePolicy }), + }), + }), + ), Effect.mapError( (cause) => new ProviderAdapterForkThreadError({ diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts index 209afd2696..91303741e6 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts @@ -105,7 +105,9 @@ const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettingsSchema)({}); */ export const OpenCodeProviderCapabilitiesV2 = { sessions: { - supportsMultipleProviderThreadsPerSession: true, + // The current adapter owns one directory-bound client/server per session. + // Keep it isolated until its runtime is made safe for cross-thread pooling. + supportsMultipleProviderThreadsPerSession: false, supportsModelSwitchInSession: true, supportsProviderSwitchingViaHandoff: true, supportsRuntimeModeSwitchInSession: false, diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index 49d8989356..3c443dc019 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -24,14 +24,8 @@ import * as SqlClient from "effect/unstable/sql/SqlClient"; export const OrchestrationEffectRequestV2 = Schema.Union([ Schema.Struct({ - type: Schema.Literal("provider-session.release"), + type: Schema.Literal("provider-session.detach"), providerSessionId: ProviderSessionId, - reason: Schema.Literals([ - "idle_timeout", - "runtime_error", - "manual_shutdown", - "server_shutdown", - ]), detail: Schema.optional(Schema.String), }), Schema.Struct({ diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 60f61b99bc..9e5e76d7c0 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -56,11 +56,11 @@ export const executorLayer: Layer.Layer< return OrchestrationEffectExecutorV2.of({ execute: (effect) => { switch (effect.request.type) { - case "provider-session.release": + case "provider-session.detach": return providerSessions - .release({ + .detach({ providerSessionId: effect.request.providerSessionId, - reason: effect.request.reason, + threadId: effect.threadId, ...(effect.request.detail === undefined ? {} : { detail: effect.request.detail }), }) .pipe( diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index 0115ac44d7..76f69db12a 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -25,7 +25,10 @@ import { layer as effectOutboxLayer, } from "./EffectOutbox.ts"; import { EventStoreV2 } from "./EventStore.ts"; -import { ProjectionStoreV2 } from "./ProjectionStore.ts"; +import { + ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, + ProjectionStoreV2, +} from "./ProjectionStore.ts"; import { TurnItemPositionStoreV2, layer as turnItemPositionStoreLayer, @@ -177,7 +180,12 @@ const baseLayer: Layer.Layer< last_sequence, updated_at ) - VALUES ('thread-projections', 1, ${sequence}, ${now}) + VALUES ( + 'thread-projections', + ${ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION}, + ${sequence}, + ${now} + ) ON CONFLICT(projection_name) DO UPDATE SET schema_version = excluded.schema_version, diff --git a/apps/server/src/orchestration-v2/IdAllocator.ts b/apps/server/src/orchestration-v2/IdAllocator.ts index f6081a33e6..7e07c76590 100644 --- a/apps/server/src/orchestration-v2/IdAllocator.ts +++ b/apps/server/src/orchestration-v2/IdAllocator.ts @@ -127,6 +127,9 @@ export interface IdAllocatorV2AllocateShape { } export interface IdAllocatorV2DeriveShape { + readonly providerSession: (input: { + readonly providerInstanceId: ProviderInstanceId; + }) => ProviderSessionId; readonly delegatedTaskNode: (input: { readonly commandId: CommandId }) => NodeId; readonly delegatedTaskThread: (input: { readonly commandId: CommandId }) => ThreadId; readonly delegatedTaskMessage: (input: { readonly commandId: CommandId }) => MessageId; @@ -343,6 +346,10 @@ export const layer: Layer.Layer = Layer.succeed( })(input), }, derive: { + providerSession: (input) => + ProviderSessionId.make( + joinId("provider-session", "provider-instance", input.providerInstanceId, "shared"), + ), delegatedTaskNode: (input) => NodeId.make(joinId("node", "delegated-task", input.commandId)), delegatedTaskThread: (input) => ThreadId.make(joinId("thread", "delegated-task", input.commandId)), diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 7e1b4abde9..d614c34713 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -42,6 +42,7 @@ import type { PendingOrchestrationEffectV2 } from "./EffectOutbox.ts"; import { OrchestrationEffectWorkerV2 } from "./EffectWorker.ts"; import { IdAllocatorV2 } from "./IdAllocator.ts"; import { applyToProjection, emptyProjection, ProjectionStoreV2 } from "./ProjectionStore.ts"; +import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts"; import { ProviderAdapterRegistryV2 } from "./ProviderAdapterRegistry.ts"; import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; import { ProviderSwitchServiceV2 } from "./ProviderSwitchService.ts"; @@ -174,7 +175,7 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId { case "thread.runtime-mode.set": case "thread.interaction-mode.set": case "thread.model-selection.set": - case "provider-session.release": + case "provider-session.detach": case "message.dispatch": case "run.interrupt": case "queued-message.promote-to-steer": @@ -409,6 +410,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); + const providerSessionIdFor = (input: { + readonly adapter: ProviderAdapterV2Shape; + readonly providerInstanceId: ProviderInstanceId; + readonly threadId: ThreadId; + }) => + input.adapter.getCapabilities().pipe( + Effect.flatMap((capabilities) => + capabilities.sessions.supportsMultipleProviderThreadsPerSession + ? Effect.succeed( + idAllocator.derive.providerSession({ + providerInstanceId: input.providerInstanceId, + }), + ) + : idAllocator.allocate.providerSession({ + providerInstanceId: input.providerInstanceId, + threadId: input.threadId, + }), + ), + ); + const enforceCommandPolicy = (command: OrchestrationV2Command) => (effect: Effect.Effect): Effect.Effect => @@ -547,12 +568,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } + const commandId = CommandId.make(`command:system:start-queued:${queuedRun.id}`); const providerSessionId = queuedProviderThread.providerSessionId ?? - (yield* idAllocator.allocate.providerSession({ - providerInstanceId: queuedRun.providerInstanceId, - threadId, - })); + (yield* providerAdapters.get(queuedRun.providerInstanceId).pipe( + Effect.flatMap((adapter) => + providerSessionIdFor({ + adapter, + providerInstanceId: queuedRun.providerInstanceId, + threadId, + }), + ), + Effect.mapError( + (cause) => + new OrchestratorDispatchError({ + commandId, + commandType: "message.dispatch", + cause, + }), + ), + )); const now = yield* DateTime.now; const providerThread: OrchestrationV2ProviderThread = { ...queuedProviderThread, @@ -568,8 +603,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio queuePosition: null, startedAt: null, }; - const commandId = CommandId.make(`command:system:start-queued:${queuedRun.id}`); - yield* writeSystemEvents( [ { @@ -782,7 +815,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: updatedThread, }); - const releaseSessionIds = new Set( + const detachSessionIds = new Set( command.type === "thread.archive" || command.type === "thread.delete" ? projection.providerSessions.map((session) => session.id) : command.type === "thread.runtime-mode.set" @@ -793,10 +826,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio .map((session) => session.id) : (providerSwitchPlan?.releaseProviderSessionIds ?? []), ); - if (releaseSessionIds.size > 0) { + if (detachSessionIds.size > 0) { const liveSessions = projection.providerSessions.filter( (session) => - releaseSessionIds.has(session.id) && + detachSessionIds.has(session.id) && session.status !== "stopped" && session.status !== "error", ); @@ -808,21 +841,31 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio events, command, )({ - type: "provider-session.updated", + type: "provider-session.detached", threadId: command.threadId, driver: session.driver, providerInstanceId: session.providerInstanceId, occurredAt: now, - payload: { ...session, status: "stopped", updatedAt: now }, + payload: { + providerSessionId: session.id, + detachedAt: now, + reason: + command.type === "thread.archive" + ? "Thread archived." + : command.type === "thread.delete" + ? "Thread deleted." + : command.type === "thread.runtime-mode.set" + ? "Runtime mode changed." + : "Provider or model selection changed.", + }, }); const pendingEffect = { - id: `effect:${command.commandId}:provider-session.release:${session.id}`, + id: `effect:${command.commandId}:provider-session.detach:${session.id}`, commandId: command.commandId, threadId: command.threadId, request: { - type: "provider-session.release", + type: "provider-session.detach", providerSessionId: session.id, - reason: "manual_shutdown", detail: command.type === "thread.archive" ? "Thread archived." @@ -840,55 +883,58 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } }); - const dispatchProviderSessionRelease = Effect.fn( - "orchestrationV2.dispatch.providerSessionRelease", - )(function* ( - command: Extract, - events: Ref.Ref>, - effects: Ref.Ref>, - ) { - const projection = yield* projectionStore - .getThreadProjection(command.threadId) - .pipe( - Effect.mapError( - (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), - ), + const dispatchProviderSessionDetach = Effect.fn("orchestrationV2.dispatch.providerSessionDetach")( + function* ( + command: Extract, + events: Ref.Ref>, + effects: Ref.Ref>, + ) { + const projection = yield* projectionStore + .getThreadProjection(command.threadId) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), + ), + ); + const session = projection.providerSessions.find( + (candidate) => candidate.id === command.providerSessionId, ); - const session = projection.providerSessions.find( - (candidate) => candidate.id === command.providerSessionId, - ); - if (session === undefined) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: `Provider session ${command.providerSessionId} does not belong to thread ${command.threadId}.`, + if (session === undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Provider session ${command.providerSessionId} does not belong to thread ${command.threadId}.`, + }); + } + const now = yield* DateTime.now; + yield* emit( + events, + command, + )({ + type: "provider-session.detached", + threadId: command.threadId, + driver: session.driver, + providerInstanceId: session.providerInstanceId, + occurredAt: now, + payload: { + providerSessionId: session.id, + detachedAt: now, + ...(command.reason === undefined ? {} : { reason: command.reason }), + }, }); - } - const now = yield* DateTime.now; - yield* emit( - events, - command, - )({ - type: "provider-session.updated", - threadId: command.threadId, - driver: session.driver, - providerInstanceId: session.providerInstanceId, - occurredAt: now, - payload: { ...session, status: "stopped", updatedAt: now }, - }); - const pendingEffect = { - id: `effect:${command.commandId}:provider-session.release:${command.providerSessionId}`, - commandId: command.commandId, - threadId: command.threadId, - request: { - type: "provider-session.release", - providerSessionId: command.providerSessionId, - reason: "manual_shutdown", - ...(command.reason === undefined ? {} : { detail: command.reason }), - }, - } satisfies PendingOrchestrationEffectV2; - yield* Ref.update(effects, (existing) => [...existing, pendingEffect]); - }); + const pendingEffect = { + id: `effect:${command.commandId}:provider-session.detach:${command.providerSessionId}`, + commandId: command.commandId, + threadId: command.threadId, + request: { + type: "provider-session.detach", + providerSessionId: command.providerSessionId, + ...(command.reason === undefined ? {} : { detail: command.reason }), + }, + } satisfies PendingOrchestrationEffectV2; + yield* Ref.update(effects, (existing) => [...existing, pendingEffect]); + }, + ); const dispatchThreadFork = Effect.fn("orchestrationV2.dispatch.threadFork")(function* ( command: Extract, @@ -1799,7 +1845,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const providerSessionId = activeProviderThread?.providerSessionId ?? (yield* mapDispatchError(command)( - idAllocator.allocate.providerSession({ + providerSessionIdFor({ + adapter, providerInstanceId: modelSelection.instanceId, threadId: command.threadId, }), @@ -2059,13 +2106,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } } + const adapter = yield* providerAdapters.get(modelSelection.instanceId).pipe( + Effect.mapError( + (cause) => + new OrchestratorProviderAdapterError({ + commandId: command.commandId, + providerInstanceId: modelSelection.instanceId, + cause, + }), + ), + ); const targetProviderThread = isProviderSwitch ? rootProviderThreadsForProvider(projection, modelSelection.instanceId)[0] : activeProviderThread; const providerSessionId = targetProviderThread?.providerSessionId ?? (yield* mapDispatchError(command)( - idAllocator.allocate.providerSession({ + providerSessionIdFor({ + adapter, providerInstanceId: modelSelection.instanceId, threadId: command.threadId, }), @@ -2086,16 +2144,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); - const adapter = yield* providerAdapters.get(modelSelection.instanceId).pipe( - Effect.mapError( - (cause) => - new OrchestratorProviderAdapterError({ - commandId: command.commandId, - providerInstanceId: modelSelection.instanceId, - cause, - }), - ), - ); const capabilities = yield* adapter.getCapabilities().pipe( Effect.mapError( (cause) => @@ -3945,8 +3993,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "provider.switch": yield* dispatchThreadMutation(command, events, effects); break; - case "provider-session.release": - yield* dispatchProviderSessionRelease(command, events, effects); + case "provider-session.detach": + yield* dispatchProviderSessionDetach(command, events, effects); break; case "message.dispatch": yield* dispatchMessage(command, events, effects); diff --git a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts index 91ebe25336..5ea252d58e 100644 --- a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts +++ b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts @@ -204,6 +204,7 @@ export const layer: Layer.Layer< yield* sql`DELETE FROM orchestration_v2_projection_runtime_requests`; yield* sql`DELETE FROM orchestration_v2_projection_provider_turns`; yield* sql`DELETE FROM orchestration_v2_projection_provider_threads`; + yield* sql`DELETE FROM orchestration_v2_projection_provider_session_bindings`; yield* sql`DELETE FROM orchestration_v2_projection_provider_sessions`; yield* sql`DELETE FROM orchestration_v2_projection_subagents`; yield* sql`DELETE FROM orchestration_v2_projection_nodes`; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 812ebafb68..a9a33fa943 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -7,6 +7,7 @@ import { ProjectId, ProviderDriverKind, ProviderInstanceId, + ProviderSessionId, ProviderThreadId, ProviderTurnId, RunAttemptId, @@ -21,6 +22,7 @@ import * as Schema from "effect/Schema"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import { ProjectionStoreV2, layer as projectionStoreLayer } from "./ProjectionStore.ts"; const TestLayer = Layer.mergeAll( @@ -36,6 +38,116 @@ const providerInstanceId = modelSelection.instanceId; const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); it.layer(TestLayer)("ProjectionStoreV2", (it) => { + it.effect("projects one shared provider session into multiple thread bindings", () => + Effect.gen(function* () { + const projectionStore = yield* ProjectionStoreV2; + const now = yield* DateTime.now; + const projectId = ProjectId.make("project:projection-shared-provider-session"); + const firstThreadId = ThreadId.make("thread:projection-shared-provider-session:first"); + const secondThreadId = ThreadId.make("thread:projection-shared-provider-session:second"); + const providerSessionId = ProviderSessionId.make( + "provider-session:projection-shared-provider-session", + ); + const makeThread = (threadId: ThreadId) => ({ + createdBy: "user" as const, + creationSource: "web" as const, + id: threadId, + projectId, + title: "Shared provider session", + providerInstanceId, + modelSelection, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: threadId, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + deletedAt: null, + }); + const session = { + id: providerSessionId, + driver, + providerInstanceId, + status: "ready" as const, + cwd: "/workspace", + model: modelSelection.model, + capabilities: CodexProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }; + + yield* projectionStore.apply({ + id: EventId.make("event:projection-shared-provider-session:first-thread"), + type: "thread.created", + threadId: firstThreadId, + occurredAt: now, + payload: makeThread(firstThreadId), + }); + yield* projectionStore.apply({ + id: EventId.make("event:projection-shared-provider-session:second-thread"), + type: "thread.created", + threadId: secondThreadId, + occurredAt: now, + payload: makeThread(secondThreadId), + }); + for (const [threadId, suffix] of [ + [firstThreadId, "first"], + [secondThreadId, "second"], + ] as const) { + yield* projectionStore.apply({ + id: EventId.make(`event:projection-shared-provider-session:${suffix}-binding`), + type: "provider-session.attached", + threadId, + driver, + providerInstanceId, + occurredAt: now, + payload: session, + }); + } + + assert.deepEqual( + (yield* projectionStore.getThreadProjection(firstThreadId)).providerSessions.map( + (value) => value.id, + ), + [providerSessionId], + ); + assert.deepEqual( + (yield* projectionStore.getThreadProjection(secondThreadId)).providerSessions.map( + (value) => value.id, + ), + [providerSessionId], + ); + + yield* projectionStore.apply({ + id: EventId.make("event:projection-shared-provider-session:first-detached"), + type: "provider-session.detached", + threadId: firstThreadId, + driver, + providerInstanceId, + occurredAt: now, + payload: { providerSessionId, detachedAt: now }, + }); + + assert.lengthOf( + (yield* projectionStore.getThreadProjection(firstThreadId)).providerSessions, + 0, + ); + assert.lengthOf( + (yield* projectionStore.getThreadProjection(secondThreadId)).providerSessions, + 1, + ); + }), + ); + it.effect("builds shell snapshots without decoding full turn item payloads", () => Effect.gen(function* () { const projectionStore = yield* ProjectionStoreV2; @@ -130,12 +242,14 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { const fullProjectionExit = yield* Effect.exit(projectionStore.getThreadProjection(threadId)); assert.deepEqual( - shell.threads.map((thread) => ({ - id: thread.id, - itemCount: thread.itemCount, - visibleItemCount: thread.visibleItemCount, - status: thread.status, - })), + shell.threads + .filter((thread) => thread.id === threadId) + .map((thread) => ({ + id: thread.id, + itemCount: thread.itemCount, + visibleItemCount: thread.visibleItemCount, + status: thread.status, + })), [ { id: threadId, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 78b4de020f..3f035e786a 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -120,7 +120,7 @@ export class ProjectionStoreV2 extends Context.Service(items: ReadonlyArray, next: T): Array { const index = items.findIndex((item) => item.id === next.id); @@ -207,11 +207,19 @@ export function applyToProjection( ...base, subagents: upsertById(base.subagents, event.payload), }; + case "provider-session.attached": case "provider-session.updated": return { ...base, providerSessions: upsertById(base.providerSessions, event.payload), }; + case "provider-session.detached": + return { + ...base, + providerSessions: base.providerSessions.filter( + (session) => session.id !== event.payload.providerSessionId, + ), + }; case "provider-thread.updated": return { ...base, @@ -1086,6 +1094,7 @@ export const layer: Layer.Layer = `; break; } + case "provider-session.attached": case "provider-session.updated": { const payloadJson = yield* encodeProviderSessionPayload(event.payload); const payload = parseEncodedPayload(payloadJson); @@ -1123,6 +1132,23 @@ export const layer: Layer.Layer = updated_at = excluded.updated_at, payload_json = excluded.payload_json `; + if (event.type === "provider-session.attached") { + yield* sql` + INSERT OR IGNORE INTO orchestration_v2_projection_provider_session_bindings ( + provider_session_id, + thread_id + ) + VALUES (${event.payload.id}, ${event.threadId}) + `; + } + break; + } + case "provider-session.detached": { + yield* sql` + DELETE FROM orchestration_v2_projection_provider_session_bindings + WHERE provider_session_id = ${event.payload.providerSessionId} + AND thread_id = ${event.threadId} + `; break; } case "provider-thread.updated": { @@ -1676,10 +1702,12 @@ export const layer: Layer.Layer = ORDER BY COALESCE(started_at, ''), subagent_id ASC `, sql` - SELECT payload_json - FROM orchestration_v2_projection_provider_sessions - WHERE thread_id = ${threadId} - ORDER BY updated_at ASC, provider_session_id ASC + SELECT sessions.payload_json + FROM orchestration_v2_projection_provider_sessions AS sessions + INNER JOIN orchestration_v2_projection_provider_session_bindings AS bindings + ON bindings.provider_session_id = sessions.provider_session_id + WHERE bindings.thread_id = ${threadId} + ORDER BY sessions.updated_at ASC, sessions.provider_session_id ASC `, sql` SELECT payload_json diff --git a/apps/server/src/orchestration-v2/ProviderAdapter.ts b/apps/server/src/orchestration-v2/ProviderAdapter.ts index b54cf5c1d6..62b521cf45 100644 --- a/apps/server/src/orchestration-v2/ProviderAdapter.ts +++ b/apps/server/src/orchestration-v2/ProviderAdapter.ts @@ -432,6 +432,13 @@ export interface ProviderAdapterV2ForkThreadInput { readonly providerTurnId?: ProviderTurnId; readonly targetThreadId: ThreadId; readonly ownerNodeId?: NodeId; + readonly modelSelection?: ModelSelection; + readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy; +} + +export interface ProviderAdapterV2EventSubscription { + readonly events: Stream.Stream; + readonly close: Effect.Effect; } export interface ProviderAdapterV2SessionRuntime { @@ -441,11 +448,20 @@ export interface ProviderAdapterV2SessionRuntime { readonly providerSession: OrchestrationV2ProviderSession; readonly rawEvents: Stream.Stream; readonly events: Stream.Stream; + /** + * Manager-owned runtimes expose a synchronous subscription so concurrent + * provider threads receive independent copies of the process event stream. + * Adapter runtimes may omit this and expose only their raw single-consumer stream. + */ + readonly subscribeEvents?: Effect.Effect; readonly ensureThread: ( input: ProviderAdapterV2EnsureThreadInput, ) => Effect.Effect; readonly resumeThread: (input: { readonly providerThread: OrchestrationV2ProviderThread; + readonly threadId?: ThreadId; + readonly modelSelection?: ModelSelection; + readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy; }) => Effect.Effect; readonly startTurn: ( input: ProviderAdapterV2TurnInput, diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 93cbfc81eb..0882a0dbcb 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -59,16 +59,27 @@ const TestEventSinkLayer = eventSinkLayer.pipe( ); const CodexCapabilities: OrchestrationV2ProviderCapabilities = CodexProviderCapabilitiesV2; +const ExclusiveCapabilities: OrchestrationV2ProviderCapabilities = { + ...CodexCapabilities, + sessions: { + ...CodexCapabilities.sessions, + supportsMultipleProviderThreadsPerSession: false, + }, +}; interface TestProviderRuntimeState { readonly openCount: number; readonly closeCount: number; + readonly interruptCount: number; + readonly resumeCount: number; readonly eventQueues: ReadonlyMap>; } const emptyState: TestProviderRuntimeState = { openCount: 0, closeCount: 0, + interruptCount: 0, + resumeCount: 0, eventQueues: new Map(), }; @@ -87,6 +98,7 @@ const runtimePolicy = { function makeProviderSession(input: { readonly providerSessionId: ProviderSessionId; readonly now: DateTime.Utc; + readonly capabilities?: OrchestrationV2ProviderCapabilities; }): OrchestrationV2ProviderSession { return { id: input.providerSessionId, @@ -95,7 +107,7 @@ function makeProviderSession(input: { status: "ready", cwd: process.cwd(), model: "gpt-5.4", - capabilities: CodexCapabilities, + capabilities: input.capabilities ?? CodexCapabilities, createdAt: input.now, updatedAt: input.now, lastError: null, @@ -194,6 +206,7 @@ function makeProviderAdapter( state: Ref.Ref, options: { readonly failEventStream?: boolean; + readonly capabilities?: OrchestrationV2ProviderCapabilities; readonly mcpConfigs?: Ref.Ref< ReadonlyArray >; @@ -202,7 +215,7 @@ function makeProviderAdapter( return { instanceId: ProviderInstanceId.make("codex"), driver: CODEX_DRIVER, - getCapabilities: () => Effect.succeed(CodexCapabilities), + getCapabilities: () => Effect.succeed(options.capabilities ?? CodexCapabilities), openSession: (input) => Effect.gen(function* () { if (options.mcpConfigs !== undefined) { @@ -216,6 +229,7 @@ function makeProviderAdapter( const session = makeProviderSession({ providerSessionId: input.providerSessionId, now, + ...(options.capabilities === undefined ? {} : { capabilities: options.capabilities }), }); yield* Ref.update(state, (current) => { const eventQueues = new Map(current.eventQueues); @@ -249,10 +263,18 @@ function makeProviderAdapter( ) : Stream.fromQueue(events), ensureThread: () => unimplemented("ensureThread unused in test"), - resumeThread: (threadInput) => Effect.succeed(threadInput.providerThread), + resumeThread: (threadInput) => + Ref.update(state, (current) => ({ + ...current, + resumeCount: current.resumeCount + 1, + })).pipe(Effect.as(threadInput.providerThread)), startTurn: () => Effect.void, steerTurn: () => Effect.void, - interruptTurn: () => Effect.void, + interruptTurn: () => + Ref.update(state, (current) => ({ + ...current, + interruptCount: current.interruptCount + 1, + })), respondToRuntimeRequest: () => Effect.void, readThreadSnapshot: () => unimplemented("readThreadSnapshot unused in test"), rollbackThread: () => unimplemented("rollbackThread unused in test"), @@ -266,6 +288,7 @@ function makeTestLayer(input: { readonly state: Ref.Ref; readonly idleTimeoutMs: number; readonly failEventStream?: boolean; + readonly capabilities?: OrchestrationV2ProviderCapabilities; readonly mcpConfigs?: Ref.Ref< ReadonlyArray >; @@ -273,6 +296,7 @@ function makeTestLayer(input: { const registryLayer = makeProviderAdapterRegistryLayer( makeProviderAdapter(input.state, { failEventStream: input.failEventStream ?? false, + ...(input.capabilities === undefined ? {} : { capabilities: input.capabilities }), ...(input.mcpConfigs === undefined ? {} : { mcpConfigs: input.mcpConfigs }), }), ); @@ -964,6 +988,224 @@ it.effect( }), ); +it.effect( + "ProviderSessionManagerV2 opens one shared runtime, broadcasts events, and detaches threads independently", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const effect = Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const idAllocator = yield* IdAllocatorV2; + const manager = yield* ProviderSessionManagerV2; + const now = yield* DateTime.now; + const projectId = yield* idAllocator.allocate.project({ + fixtureName: "provider-session-manager-shared-runtime", + }); + const firstThreadId = yield* idAllocator.allocate.thread({ + fixtureName: "provider-session-manager-shared-runtime-a", + projectId, + }); + const secondThreadId = yield* idAllocator.allocate.thread({ + fixtureName: "provider-session-manager-shared-runtime-b", + projectId, + }); + const providerSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: firstThreadId, now }), + yield* makeThreadCreatedEvent({ idAllocator, threadId: secondThreadId, now }), + ], + }); + const firstProviderThread = makeProviderThread({ + idAllocator, + threadId: firstThreadId, + providerSessionId, + now, + }); + const secondProviderThread = makeProviderThread({ + idAllocator, + threadId: secondThreadId, + providerSessionId, + now, + }); + const firstRunId = idAllocator.derive.run({ threadId: firstThreadId, ordinal: 1 }); + yield* eventSink.write({ + events: [ + { + id: yield* idAllocator.allocate.event({ threadId: firstThreadId }), + type: "provider-thread.updated", + threadId: firstThreadId, + driver: CODEX_DRIVER, + occurredAt: now, + payload: firstProviderThread, + }, + { + id: yield* idAllocator.allocate.event({ threadId: firstThreadId }), + type: "provider-turn.updated", + threadId: firstThreadId, + runId: firstRunId, + driver: CODEX_DRIVER, + occurredAt: now, + payload: { + id: idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: "native-turn-shared-runtime-a", + }), + providerThreadId: firstProviderThread.id, + nodeId: idAllocator.derive.rootNode({ runId: firstRunId }), + runAttemptId: null, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt: now, + completedAt: null, + }, + }, + ], + }); + const firstRuntime = yield* manager.open({ + threadId: firstThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const secondRuntime = yield* manager.open({ + threadId: secondThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + + assert.strictEqual(firstRuntime, secondRuntime); + assert.equal((yield* Ref.get(state)).openCount, 1); + const resumeSecondThread = secondRuntime.resumeThread({ + providerThread: secondProviderThread, + threadId: secondThreadId, + modelSelection, + runtimePolicy, + }); + yield* resumeSecondThread; + yield* resumeSecondThread; + assert.equal((yield* Ref.get(state)).resumeCount, 1); + yield* secondRuntime.resumeThread({ + providerThread: secondProviderThread, + threadId: secondThreadId, + modelSelection: { ...modelSelection, model: "gpt-5.4-mini" }, + runtimePolicy, + }); + assert.equal((yield* Ref.get(state)).resumeCount, 2); + yield* resumeSecondThread; + assert.equal((yield* Ref.get(state)).resumeCount, 3); + const subscribe = firstRuntime.subscribeEvents; + assert.isDefined(subscribe); + if (subscribe === undefined) return; + const firstSubscription = yield* subscribe; + const secondSubscription = yield* subscribe; + const queue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId)); + assert.isDefined(queue); + yield* Queue.offer(queue!, { + type: "provider_session.updated", + driver: CODEX_DRIVER, + providerSession: firstRuntime.providerSession, + }); + const received = yield* Effect.all([ + firstSubscription.events.pipe(Stream.runHead), + secondSubscription.events.pipe(Stream.runHead), + ]); + assert.isTrue(received.every(Option.isSome)); + assert.isTrue( + received.every( + (event) => Option.isSome(event) && event.value.type === "provider_session.updated", + ), + ); + + yield* manager.detach({ providerSessionId, threadId: secondThreadId }); + yield* manager.open({ + threadId: secondThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + yield* resumeSecondThread; + assert.equal((yield* Ref.get(state)).resumeCount, 4); + + yield* manager.detach({ providerSessionId, threadId: firstThreadId }); + assert.isTrue(Option.isSome(yield* manager.get(providerSessionId))); + assert.equal((yield* Ref.get(state)).closeCount, 0); + assert.equal((yield* Ref.get(state)).interruptCount, 1); + + yield* manager.detach({ providerSessionId, threadId: secondThreadId }); + yield* TestClock.adjust("1 second"); + yield* Effect.yieldNow; + assert.equal((yield* Ref.get(state)).closeCount, 1); + }); + + yield* effect.pipe(Effect.provide(makeTestLayer({ state, idleTimeoutMs: 1000 }))); + }), +); + +it.effect( + "ProviderSessionManagerV2 rejects a second thread when the provider runtime is exclusive", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const effect = Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const idAllocator = yield* IdAllocatorV2; + const manager = yield* ProviderSessionManagerV2; + const now = yield* DateTime.now; + const projectId = yield* idAllocator.allocate.project({ + fixtureName: "provider-session-manager-exclusive-runtime", + }); + const firstThreadId = yield* idAllocator.allocate.thread({ + fixtureName: "provider-session-manager-exclusive-runtime-a", + projectId, + }); + const secondThreadId = yield* idAllocator.allocate.thread({ + fixtureName: "provider-session-manager-exclusive-runtime-b", + projectId, + }); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId: firstThreadId, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: firstThreadId, now }), + yield* makeThreadCreatedEvent({ idAllocator, threadId: secondThreadId, now }), + ], + }); + + yield* manager.open({ + threadId: firstThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const error = yield* manager + .open({ + threadId: secondThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }) + .pipe(Effect.flip); + + assert.equal(error._tag, "ProviderSessionOpenError"); + assert.equal((yield* Ref.get(state)).openCount, 1); + }); + + yield* effect.pipe( + Effect.provide( + makeTestLayer({ state, idleTimeoutMs: 1000, capabilities: ExclusiveCapabilities }), + ), + ); + }), +); + it.todo( "ProviderRuntimeRecoveryService restarts process_exited or transport_unavailable sessions with a bounded retry policy and resumes the native provider thread", ); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 076350e4d1..6f909cc338 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -17,9 +17,11 @@ import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; +import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as McpProviderSession from "../mcp/McpProviderSession.ts"; @@ -27,7 +29,11 @@ import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; import { EventSinkV2 } from "./EventSink.ts"; import { IdAllocatorV2 } from "./IdAllocator.ts"; import { + ProviderAdapterEventStreamError, ProviderAdapterV2RuntimePolicy, + type ProviderAdapterV2Error, + type ProviderAdapterV2Event, + type ProviderAdapterV2EventSubscription, type ProviderAdapterV2SessionRuntime, } from "./ProviderAdapter.ts"; import { ProviderAdapterRegistryV2 } from "./ProviderAdapterRegistry.ts"; @@ -149,6 +155,11 @@ export interface ProviderSessionManagerV2Shape { readonly reason: ProviderSessionReleaseReason; readonly detail?: string; }) => Effect.Effect; + readonly detach: (input: { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + readonly detail?: string; + }) => Effect.Effect; } export class ProviderSessionManagerV2 extends Context.Service< @@ -158,8 +169,11 @@ export class ProviderSessionManagerV2 extends Context.Service< interface LiveSessionEntry { readonly attachedThreadIds: ReadonlySet; + readonly loadedProviderThreadKeyByThread: ReadonlyMap; + readonly supportsMultipleProviderThreads: boolean; readonly runtime: ProviderAdapterV2SessionRuntime; readonly exposedRuntime: ProviderAdapterV2SessionRuntime; + readonly eventSubscribers: Ref.Ref>>; readonly scope: Scope.Closeable; readonly idleGeneration: number; readonly busyCount: number; @@ -167,6 +181,13 @@ interface LiveSessionEntry { readonly idleFiber: Fiber.Fiber | null; } +type ProviderSessionEventSignal = + | { readonly type: "event"; readonly event: ProviderAdapterV2Event } + | { + readonly type: "failure"; + readonly cause: Cause.Cause; + }; + export interface ProviderSessionManagerV2LayerOptions { readonly idleTimeoutMs?: number; } @@ -187,6 +208,29 @@ function sessionKey(providerSessionId: ProviderSessionId): string { return String(providerSessionId); } +function providerThreadRuntimeKey( + providerThread: Parameters[0]["providerThread"], +): string { + const nativeThreadRef = providerThread.nativeThreadRef; + return nativeThreadRef === null + ? String(providerThread.id) + : `${nativeThreadRef.driver}:${nativeThreadRef.nativeId}`; +} + +function providerThreadLoadKey(input: { + readonly providerThread: Parameters< + ProviderAdapterV2SessionRuntime["resumeThread"] + >[0]["providerThread"]; + readonly modelSelection?: ModelSelection; + readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy; +}): string { + return JSON.stringify({ + providerThread: providerThreadRuntimeKey(input.providerThread), + modelSelection: input.modelSelection ?? null, + runtimePolicy: input.runtimePolicy ?? null, + }); +} + export const layerWithOptions = ( options: ProviderSessionManagerV2LayerOptions = {}, ): Layer.Layer< @@ -203,6 +247,8 @@ export const layerWithOptions = ( const projectionStore = yield* ProjectionStoreV2; const layerScope = yield* Effect.scope; const sessions = yield* Ref.make(new Map()); + const nextSubscriberId = yield* Ref.make(0); + const openSemaphore = yield* Semaphore.make(1); const idleTimeoutMs = Math.max(1, options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS); const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => McpSessionRegistry.issueActiveMcpCredential({ @@ -220,9 +266,64 @@ export const layerWithOptions = ( Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))), ); + const publishToSubscribers = ( + subscribers: Ref.Ref>>, + signal: ProviderSessionEventSignal, + ) => + Ref.get(subscribers).pipe( + Effect.flatMap((current) => + Effect.forEach(current.values(), (queue) => Queue.offer(queue, signal), { + discard: true, + }), + ), + ); + + const failSubscribers = (entry: LiveSessionEntry, detail: string) => + Effect.gen(function* () { + const error = new ProviderAdapterEventStreamError({ + driver: entry.runtime.driver, + providerSessionId: entry.runtime.providerSessionId, + cause: detail, + }); + yield* publishToSubscribers(entry.eventSubscribers, { + type: "failure", + cause: Cause.fail(error), + }); + yield* Ref.set(entry.eventSubscribers, new Map()); + }); + const cancelIdleFiber = (fiber: Fiber.Fiber | null) => fiber === null ? Effect.void : Fiber.interrupt(fiber).pipe(Effect.ignore); + const writeProviderSessionEvents = (input: { + readonly runtime: ProviderAdapterV2SessionRuntime; + readonly threadIds: Iterable; + readonly type: "provider-session.attached" | "provider-session.updated"; + readonly payload: OrchestrationV2ProviderSession; + }) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const events = yield* Effect.forEach(input.threadIds, (threadId) => + Effect.gen(function* () { + return { + id: yield* idAllocator.allocate.event({ + threadId, + providerSessionId: input.runtime.providerSessionId, + }), + type: input.type, + threadId, + driver: input.runtime.driver, + providerInstanceId: input.runtime.instanceId, + occurredAt: now, + payload: input.payload, + } satisfies OrchestrationV2DomainEvent; + }), + ); + if (events.length > 0) { + yield* eventSink.write({ events }); + } + }); + const writeReleasedSessionEvents = (input: { readonly entry: LiveSessionEntry; readonly reason: ProviderSessionReleaseReason; @@ -239,24 +340,12 @@ export const layerWithOptions = ( ? (input.detail ?? "Provider runtime failed.") : null, }; - const events = yield* Effect.forEach( - Array.from(input.entry.attachedThreadIds), - (threadId) => - Effect.gen(function* () { - return { - id: yield* idAllocator.allocate.event({ - threadId, - providerSessionId: input.entry.runtime.providerSessionId, - }), - type: "provider-session.updated", - threadId, - driver: input.entry.runtime.driver, - occurredAt: now, - payload, - } satisfies OrchestrationV2DomainEvent; - }), - ); - yield* eventSink.write({ events }); + yield* writeProviderSessionEvents({ + runtime: input.entry.runtime, + threadIds: input.entry.attachedThreadIds, + type: "provider-session.updated", + payload, + }); }); const writeReleasedRuntimeRequestEvents = (input: { @@ -380,6 +469,10 @@ export const layerWithOptions = ( if (input.cancelIdleFiber !== false) { yield* cancelIdleFiber(entry.value.idleFiber); } + yield* failSubscribers( + entry.value, + input.detail ?? `Provider session released: ${input.reason}.`, + ); const closeExit = yield* Effect.exit(Scope.close(entry.value.scope, Exit.void)); yield* writeReleasedSessionEvents({ entry: entry.value, @@ -511,20 +604,103 @@ export const layerWithOptions = ( }) => withActivityError( input.providerSessionId, - Ref.update(sessions, (current) => { + Ref.modify(sessions, (current) => { const entry = current.get(sessionKey(input.providerSessionId)); if (entry === undefined || entry.attachedThreadIds.has(input.threadId)) { - return current; + return [false, current] as const; } const updated = new Map(current); updated.set(sessionKey(input.providerSessionId), { ...entry, attachedThreadIds: new Set([...entry.attachedThreadIds, input.threadId]), }); - return updated; + return [true, updated] as const; }), ); + const removeThreadAttachment = (input: { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + }) => + Ref.update(sessions, (current) => { + const key = sessionKey(input.providerSessionId); + const entry = current.get(key); + if (entry === undefined || !entry.attachedThreadIds.has(input.threadId)) { + return current; + } + const attachedThreadIds = new Set(entry.attachedThreadIds); + attachedThreadIds.delete(input.threadId); + const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); + loadedProviderThreadKeyByThread.delete(input.threadId); + const updated = new Map(current); + updated.set(key, { + ...entry, + attachedThreadIds, + loadedProviderThreadKeyByThread, + }); + return updated; + }); + + const isProviderThreadLoaded = (input: { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + readonly providerThreadKey: string; + }) => + Ref.get(sessions).pipe( + Effect.map( + (current) => + current + .get(sessionKey(input.providerSessionId)) + ?.loadedProviderThreadKeyByThread.get(input.threadId) === input.providerThreadKey, + ), + ); + + const markProviderThreadLoaded = (input: { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + readonly providerThreadKey: string; + }) => + Ref.update(sessions, (current) => { + const key = sessionKey(input.providerSessionId); + const entry = current.get(key); + if (entry === undefined) { + return current; + } + const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); + loadedProviderThreadKeyByThread.set(input.threadId, input.providerThreadKey); + const updated = new Map(current); + updated.set(key, { ...entry, loadedProviderThreadKeyByThread }); + return updated; + }); + + const ensureThreadAttached = (input: { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + readonly providerInstanceId: ProviderInstanceId; + }) => + Effect.gen(function* () { + const attached = yield* attachThread(input); + if (attached) { + yield* prepareMcpSession(input.threadId, input.providerInstanceId); + const entry = (yield* Ref.get(sessions)).get(sessionKey(input.providerSessionId)); + if (entry !== undefined) { + yield* withActivityError( + input.providerSessionId, + writeProviderSessionEvents({ + runtime: entry.runtime, + threadIds: [input.threadId], + type: "provider-session.attached", + payload: entry.runtime.providerSession, + }), + ); + } + } + }).pipe( + Effect.tapError(() => + removeThreadAttachment(input).pipe(Effect.andThen(clearMcpSession(input.threadId))), + ), + ); + const markBusy = (providerSessionId: ProviderSessionId) => withActivityError( providerSessionId, @@ -585,47 +761,147 @@ export const layerWithOptions = ( ), ); + const makeEventSubscription = ( + subscribers: Ref.Ref>>, + ): Effect.Effect => + Effect.gen(function* () { + const queue = yield* Queue.unbounded(); + const subscriberId = yield* Ref.getAndUpdate(nextSubscriberId, (value) => value + 1); + yield* Ref.update(subscribers, (current) => { + const updated = new Map(current); + updated.set(subscriberId, queue); + return updated; + }); + const close = Ref.modify(subscribers, (current) => { + if (!current.has(subscriberId)) { + return [false, current] as const; + } + const updated = new Map(current); + updated.delete(subscriberId); + return [true, updated] as const; + }).pipe(Effect.flatMap((removed) => (removed ? Queue.shutdown(queue) : Effect.void))); + const events = Stream.fromQueue(queue).pipe( + Stream.mapEffect((signal) => + signal.type === "event" + ? Effect.succeed(signal.event) + : Effect.failCause(signal.cause), + ), + Stream.ensuring(close), + ); + return { events, close } satisfies ProviderAdapterV2EventSubscription; + }); + const decorateRuntime = ( runtime: ProviderAdapterV2SessionRuntime, + eventSubscribers: Ref.Ref>>, ): ProviderAdapterV2SessionRuntime => { const providerSessionId = runtime.providerSessionId; + const subscribeEvents = makeEventSubscription(eventSubscribers); return { ...runtime, - events: runtime.events.pipe( - Stream.tap((event) => - event.type === "turn.terminal" - ? observeActivity(providerSessionId, markIdle(providerSessionId)) - : observeActivity(providerSessionId, touchActivity(providerSessionId)), - ), - Stream.catchCause((cause) => - Stream.fromEffect( - releaseEntry({ - providerSessionId, - reason: "runtime_error", - detail: Cause.pretty(cause), - }).pipe(Effect.ignore, Effect.andThen(Effect.failCause(cause))), - ), - ), + subscribeEvents, + events: Stream.unwrap( + subscribeEvents.pipe(Effect.map((subscription) => subscription.events)), ), ensureThread: (input) => observeActivity( providerSessionId, - attachThread({ providerSessionId, threadId: input.threadId }), - ).pipe(Effect.andThen(runtime.ensureThread(input))), - resumeThread: (input) => - input.providerThread.appThreadId === null - ? runtime.resumeThread(input) - : observeActivity( + ensureThreadAttached({ + providerSessionId, + threadId: input.threadId, + providerInstanceId: runtime.instanceId, + }), + ).pipe( + Effect.andThen(runtime.ensureThread(input)), + Effect.tap((providerThread) => + markProviderThreadLoaded({ providerSessionId, - attachThread({ - providerSessionId, - threadId: input.providerThread.appThreadId, + threadId: input.threadId, + providerThreadKey: providerThreadLoadKey({ + providerThread, + modelSelection: input.modelSelection, + runtimePolicy: input.runtimePolicy, }), - ).pipe(Effect.andThen(runtime.resumeThread(input))), + }), + ), + ), + resumeThread: (input) => { + const threadId = input.threadId ?? input.providerThread.appThreadId; + if (threadId === null || threadId === undefined) { + return runtime.resumeThread(input); + } + const providerThreadKey = providerThreadLoadKey({ + providerThread: input.providerThread, + ...(input.modelSelection === undefined + ? {} + : { modelSelection: input.modelSelection }), + ...(input.runtimePolicy === undefined ? {} : { runtimePolicy: input.runtimePolicy }), + }); + return observeActivity( + providerSessionId, + ensureThreadAttached({ + providerSessionId, + threadId, + providerInstanceId: runtime.instanceId, + }), + ).pipe( + Effect.andThen( + isProviderThreadLoaded({ providerSessionId, threadId, providerThreadKey }), + ), + Effect.flatMap((loaded) => + loaded ? Effect.succeed(input.providerThread) : runtime.resumeThread(input), + ), + Effect.tap((providerThread) => + markProviderThreadLoaded({ + providerSessionId, + threadId, + providerThreadKey: providerThreadLoadKey({ + providerThread, + ...(input.modelSelection === undefined + ? {} + : { modelSelection: input.modelSelection }), + ...(input.runtimePolicy === undefined + ? {} + : { runtimePolicy: input.runtimePolicy }), + }), + }), + ), + ); + }, + forkThread: (input) => + observeActivity( + providerSessionId, + ensureThreadAttached({ + providerSessionId, + threadId: input.targetThreadId, + providerInstanceId: runtime.instanceId, + }), + ).pipe( + Effect.andThen(runtime.forkThread(input)), + Effect.tap((providerThread) => + markProviderThreadLoaded({ + providerSessionId, + threadId: input.targetThreadId, + providerThreadKey: providerThreadLoadKey({ + providerThread, + ...(input.modelSelection === undefined + ? {} + : { modelSelection: input.modelSelection }), + ...(input.runtimePolicy === undefined + ? {} + : { runtimePolicy: input.runtimePolicy }), + }), + }), + ), + ), startTurn: (input) => observeActivity( providerSessionId, - attachThread({ providerSessionId, threadId: input.threadId }), + ensureThreadAttached({ + providerSessionId, + threadId: input.threadId, + providerInstanceId: runtime.instanceId, + }), ).pipe( Effect.andThen(observeActivity(providerSessionId, markBusy(providerSessionId))), Effect.andThen(runtime.startTurn(input)), @@ -650,6 +926,84 @@ export const layerWithOptions = ( }; }; + const persistProviderSessionUpdate = ( + entry: LiveSessionEntry, + event: Extract, + ) => + Effect.gen(function* () { + const current = (yield* Ref.get(sessions)).get( + sessionKey(entry.runtime.providerSessionId), + ); + if (current?.runtime !== entry.runtime) { + return; + } + yield* writeProviderSessionEvents({ + runtime: entry.runtime, + threadIds: current.attachedThreadIds, + type: "provider-session.updated", + payload: event.providerSession, + }); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.driver-session.status-persist-failed", { + providerSessionId: entry.runtime.providerSessionId, + cause, + }), + ), + ); + + const startEventPump = (entry: LiveSessionEntry) => + entry.runtime.events.pipe( + Stream.runForEach((event) => + observeActivity( + entry.runtime.providerSessionId, + event.type === "turn.terminal" + ? markIdle(entry.runtime.providerSessionId) + : touchActivity(entry.runtime.providerSessionId), + ).pipe( + Effect.andThen( + event.type === "provider_session.updated" + ? persistProviderSessionUpdate(entry, event) + : Effect.void, + ), + Effect.andThen( + publishToSubscribers(entry.eventSubscribers, { type: "event", event }), + ), + ), + ), + Effect.exit, + Effect.flatMap((exit) => + Effect.gen(function* () { + const current = (yield* Ref.get(sessions)).get( + sessionKey(entry.runtime.providerSessionId), + ); + if (current?.runtime !== entry.runtime) { + return; + } + const cause = Exit.isFailure(exit) + ? exit.cause + : Cause.fail( + new ProviderAdapterEventStreamError({ + driver: entry.runtime.driver, + providerSessionId: entry.runtime.providerSessionId, + cause: "Provider event stream ended unexpectedly.", + }), + ); + yield* publishToSubscribers(entry.eventSubscribers, { + type: "failure", + cause, + }); + yield* Ref.set(entry.eventSubscribers, new Map()); + yield* releaseEntry({ + providerSessionId: entry.runtime.providerSessionId, + reason: "runtime_error", + detail: Cause.pretty(cause), + }).pipe(Effect.ignore); + }), + ), + Effect.forkIn(layerScope), + ); + yield* Effect.addFinalizer(() => Effect.gen(function* () { const activeSessions = [...(yield* Ref.get(sessions)).values()]; @@ -674,48 +1028,31 @@ export const layerWithOptions = ( return ProviderSessionManagerV2.of({ open: (input) => - Effect.gen(function* () { - const key = sessionKey(input.providerSessionId); - const existing = (yield* Ref.get(sessions)).get(key); - if (existing !== undefined) { - yield* attachThread({ - providerSessionId: input.providerSessionId, - threadId: input.threadId, - }); - yield* touchActivity(input.providerSessionId); - return existing.exposedRuntime; - } - - const adapter = yield* registry.get(input.modelSelection.provider).pipe( - Effect.mapError( - (cause) => - new ProviderSessionOpenError({ - provider: input.modelSelection.provider, + openSemaphore.withPermit( + Effect.gen(function* () { + const key = sessionKey(input.providerSessionId); + const existing = (yield* Ref.get(sessions)).get(key); + if (existing !== undefined) { + if ( + !existing.attachedThreadIds.has(input.threadId) && + !existing.supportsMultipleProviderThreads + ) { + return yield* new ProviderSessionOpenError({ + instanceId: input.modelSelection.instanceId, providerSessionId: input.providerSessionId, - cause, - }), - ), - ); - yield* prepareMcpSession(input.threadId, input.modelSelection.instanceId); - const sessionScope = yield* Scope.make(); - const runtime = yield* adapter - .openSession({ - threadId: input.threadId, - providerSessionId: input.providerSessionId, - modelSelection: input.modelSelection, - runtimePolicy: input.runtimePolicy, - ...(input.resumeFromSession === undefined - ? {} - : { resumeFromSession: input.resumeFromSession }), - }) - .pipe( - Effect.provideService(Scope.Scope, sessionScope), - Effect.tapError(() => - Scope.close(sessionScope, Exit.void).pipe( - Effect.ignore, - Effect.andThen(clearMcpSession(input.threadId)), - ), - ), + cause: `Provider ${existing.runtime.driver} does not support attaching multiple app threads to one session.`, + }); + } + yield* ensureThreadAttached({ + providerSessionId: input.providerSessionId, + threadId: input.threadId, + providerInstanceId: existing.runtime.instanceId, + }); + yield* touchActivity(input.providerSessionId); + return existing.exposedRuntime; + } + + const adapter = yield* registry.get(input.modelSelection.instanceId).pipe( Effect.mapError( (cause) => new ProviderSessionOpenError({ @@ -725,25 +1062,82 @@ export const layerWithOptions = ( }), ), ); - const exposedRuntime = decorateRuntime(runtime); - const now = yield* Clock.currentTimeMillis; - yield* Ref.update(sessions, (current) => { - const updated = new Map(current); - updated.set(key, { + yield* prepareMcpSession(input.threadId, input.modelSelection.instanceId); + const sessionScope = yield* Scope.make(); + const runtime = yield* adapter + .openSession({ + threadId: input.threadId, + providerSessionId: input.providerSessionId, + modelSelection: input.modelSelection, + runtimePolicy: input.runtimePolicy, + ...(input.resumeFromSession === undefined + ? {} + : { resumeFromSession: input.resumeFromSession }), + }) + .pipe( + Effect.provideService(Scope.Scope, sessionScope), + Effect.tapError(() => + Scope.close(sessionScope, Exit.void).pipe( + Effect.ignore, + Effect.andThen(clearMcpSession(input.threadId)), + ), + ), + Effect.mapError( + (cause) => + new ProviderSessionOpenError({ + instanceId: input.modelSelection.instanceId, + providerSessionId: input.providerSessionId, + cause, + }), + ), + ); + const eventSubscribers = yield* Ref.make< + ReadonlyMap> + >(new Map()); + const exposedRuntime = decorateRuntime(runtime, eventSubscribers); + const now = yield* Clock.currentTimeMillis; + const entry: LiveSessionEntry = { attachedThreadIds: new Set([input.threadId]), + loadedProviderThreadKeyByThread: new Map(), + supportsMultipleProviderThreads: + runtime.providerSession.capabilities.sessions + .supportsMultipleProviderThreadsPerSession, runtime, exposedRuntime, + eventSubscribers, scope: sessionScope, idleGeneration: 0, busyCount: 0, lastActivityAtMs: now, idleFiber: null, + }; + yield* Ref.update(sessions, (current) => { + const updated = new Map(current); + updated.set(key, entry); + return updated; }); - return updated; - }); - yield* scheduleIdleRelease(input.providerSessionId); - return exposedRuntime; - }), + yield* withActivityError( + input.providerSessionId, + writeProviderSessionEvents({ + runtime, + threadIds: [input.threadId], + type: "provider-session.attached", + payload: runtime.providerSession, + }), + ).pipe( + Effect.tapError(() => + releaseEntry({ + providerSessionId: input.providerSessionId, + reason: "runtime_error", + detail: "Failed to persist the provider-session attachment.", + }).pipe(Effect.ignore), + ), + ); + yield* startEventPump(entry); + yield* scheduleIdleRelease(input.providerSessionId); + return exposedRuntime; + }), + ), get: (providerSessionId) => Effect.gen(function* () { const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId)); @@ -772,6 +1166,95 @@ export const layerWithOptions = ( ), ), release: releaseEntry, + detach: (input) => + Effect.gen(function* () { + const key = sessionKey(input.providerSessionId); + const currentEntry = (yield* Ref.get(sessions)).get(key); + if (currentEntry?.supportsMultipleProviderThreads === true) { + const projection = yield* Effect.option( + projectionStore.getThreadProjection(input.threadId), + ); + if (Option.isSome(projection)) { + const providerThreads = new Map( + projection.value.providerThreads + .filter((thread) => thread.providerSessionId === input.providerSessionId) + .map((thread) => [thread.id, thread] as const), + ); + const activeTurns = projection.value.providerTurns.filter( + (turn) => turn.status === "running" && providerThreads.has(turn.providerThreadId), + ); + yield* Effect.forEach( + activeTurns, + (turn) => + currentEntry.exposedRuntime + .interruptTurn({ + providerThread: providerThreads.get(turn.providerThreadId)!, + providerTurnId: turn.id, + }) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning( + "orchestration-v2.driver-session.detach-interrupt-failed", + { + providerSessionId: input.providerSessionId, + threadId: input.threadId, + providerTurnId: turn.id, + cause, + }, + ), + ), + ), + { concurrency: 1, discard: true }, + ); + } + } + const detached = yield* Ref.modify(sessions, (current) => { + const entry = current.get(key); + if (entry === undefined || !entry.attachedThreadIds.has(input.threadId)) { + return [Option.none(), current] as const; + } + const attachedThreadIds = new Set(entry.attachedThreadIds); + attachedThreadIds.delete(input.threadId); + const loadedProviderThreadKeyByThread = new Map( + entry.loadedProviderThreadKeyByThread, + ); + loadedProviderThreadKeyByThread.delete(input.threadId); + const updatedEntry = { + ...entry, + attachedThreadIds, + loadedProviderThreadKeyByThread, + }; + const updated = new Map(current); + updated.set(key, updatedEntry); + return [Option.some(updatedEntry), updated] as const; + }); + yield* clearMcpSession(input.threadId); + if (Option.isNone(detached)) { + return; + } + if ( + detached.value.attachedThreadIds.size === 0 && + !detached.value.supportsMultipleProviderThreads + ) { + yield* releaseEntry({ + providerSessionId: input.providerSessionId, + reason: "manual_shutdown", + ...(input.detail === undefined ? {} : { detail: input.detail }), + }); + return; + } + yield* scheduleIdleRelease(input.providerSessionId); + }).pipe( + Effect.catchCause((cause) => + Effect.fail( + new ProviderSessionReleaseError({ + providerSessionId: input.providerSessionId, + reason: "manual_shutdown", + cause, + }), + ), + ), + ), } satisfies ProviderSessionManagerV2Shape); }), ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index b175f0ff3f..3de486d9c2 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -12,7 +12,6 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { EventSinkV2 } from "./EventSink.ts"; @@ -118,7 +117,6 @@ export const layer: Layer.Layer< const existingSessionProjection = projection.providerSessions.find( (candidate) => candidate.id === providerSessionId, ); - const activeSession = yield* providerSessions.get(providerSessionId); const session = yield* providerSessions.open({ threadId: projection.thread.id, providerSessionId, @@ -157,6 +155,8 @@ export const layer: Layer.Layer< sourceProviderThread, sourceProviderTurns: sourceProjection.providerTurns, targetThreadId: projection.thread.id, + modelSelection: run.modelSelection, + runtimePolicy: resolvedRuntimePolicy, ...(sourceProviderTurn === undefined ? {} : { providerTurnId: sourceProviderTurn.id }), }); } @@ -167,9 +167,12 @@ export const layer: Layer.Layer< runtimePolicy: resolvedRuntimePolicy, providerSessionId, }) - : Option.isSome(activeSession) - ? providerThread - : yield* session.resumeThread({ providerThread }); + : yield* session.resumeThread({ + providerThread, + threadId: projection.thread.id, + modelSelection: run.modelSelection, + runtimePolicy: resolvedRuntimePolicy, + }); }); const now = yield* DateTime.now; const runningProviderThread: OrchestrationV2ProviderThread = { @@ -294,6 +297,12 @@ export const layer: Layer.Layer< providerThread: runningProviderThread, attempt: runningAttempt, attemptId: attempt.id, + relatedThreadIds: projection.subagents.flatMap((subagent) => + subagent.childThreadId === null ? [] : [subagent.childThreadId], + ), + relatedProviderThreadIds: projection.subagents.flatMap((subagent) => + subagent.providerThreadId === null ? [] : [subagent.providerThreadId], + ), providerTurnOrdinal: Math.max( 0, diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts new file mode 100644 index 0000000000..c888fda230 --- /dev/null +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -0,0 +1,137 @@ +import { assert, it } from "@effect/vitest"; +import { + MessageId, + NodeId, + ProviderDriverKind, + ProviderThreadId, + ProviderTurnId, + RunAttemptId, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; + +import type { ProviderAdapterV2Event } from "./ProviderAdapter.ts"; +import { + makeProviderEventRoutingState, + type ProviderEventRouteIdentity, + routeProviderEvent, +} from "./RunExecutionService.ts"; + +const driver = ProviderDriverKind.make("codex"); + +it.effect("routes shared-runtime events only to their owning root run", () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const first: ProviderEventRouteIdentity = { + threadId: ThreadId.make("thread:shared-runtime:first"), + runId: RunId.make("run:shared-runtime:first"), + attemptId: RunAttemptId.make("attempt:shared-runtime:first"), + providerThreadId: ProviderThreadId.make("provider-thread:shared-runtime:first"), + }; + const second: ProviderEventRouteIdentity = { + threadId: ThreadId.make("thread:shared-runtime:second"), + runId: RunId.make("run:shared-runtime:second"), + attemptId: RunAttemptId.make("attempt:shared-runtime:second"), + providerThreadId: ProviderThreadId.make("provider-thread:shared-runtime:second"), + }; + const firstTurnId = ProviderTurnId.make("provider-turn:shared-runtime:first"); + const turnEvent: ProviderAdapterV2Event = { + type: "provider_turn.updated", + driver, + threadId: first.threadId, + providerTurn: { + id: firstTurnId, + providerThreadId: first.providerThreadId, + nodeId: NodeId.make("node:shared-runtime:first"), + runAttemptId: first.attemptId, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt: now, + completedAt: null, + }, + }; + const messageEvent: ProviderAdapterV2Event = { + type: "message.updated", + driver, + message: { + createdBy: "agent", + creationSource: "provider", + id: MessageId.make("message:shared-runtime:first"), + threadId: first.threadId, + runId: first.runId, + nodeId: NodeId.make("node:shared-runtime:first"), + role: "assistant", + text: "first only", + attachments: [], + streaming: false, + createdAt: now, + updatedAt: now, + }, + }; + const terminalEvent: ProviderAdapterV2Event = { + type: "turn.terminal", + driver, + providerTurnId: firstTurnId, + status: "completed", + }; + + const firstInitial = makeProviderEventRoutingState({ + identity: first, + providerTurnId: null, + }); + const secondInitial = makeProviderEventRoutingState({ + identity: second, + providerTurnId: null, + }); + const [firstTurnAccepted, firstAfterTurn] = routeProviderEvent(turnEvent, first, firstInitial); + const [secondTurnAccepted, secondAfterTurn] = routeProviderEvent( + turnEvent, + second, + secondInitial, + ); + + assert.isTrue(firstTurnAccepted); + assert.isFalse(secondTurnAccepted); + assert.isTrue(routeProviderEvent(messageEvent, first, firstAfterTurn)[0]); + assert.isFalse(routeProviderEvent(messageEvent, second, secondAfterTurn)[0]); + assert.isTrue(routeProviderEvent(terminalEvent, first, firstAfterTurn)[0]); + assert.isFalse(routeProviderEvent(terminalEvent, second, secondAfterTurn)[0]); + }), +); + +it("does not route a superseded attempt through a reused provider thread", () => { + const threadId = ThreadId.make("thread:shared-runtime:restart"); + const providerThreadId = ProviderThreadId.make("provider-thread:shared-runtime:restart"); + const oldAttempt: ProviderEventRouteIdentity = { + threadId, + runId: RunId.make("run:shared-runtime:restart"), + attemptId: RunAttemptId.make("attempt:shared-runtime:restart:old"), + providerThreadId, + }; + const newAttempt: ProviderEventRouteIdentity = { + ...oldAttempt, + attemptId: RunAttemptId.make("attempt:shared-runtime:restart:new"), + }; + const oldTurnEvent: ProviderAdapterV2Event = { + type: "provider_turn.updated", + driver, + threadId, + providerTurn: { + id: ProviderTurnId.make("provider-turn:shared-runtime:restart:old"), + providerThreadId, + nodeId: NodeId.make("node:shared-runtime:restart:old"), + runAttemptId: oldAttempt.attemptId, + nativeTurnRef: null, + ordinal: 1, + status: "interrupted", + startedAt: null, + completedAt: null, + }, + }; + + const newState = makeProviderEventRoutingState({ identity: newAttempt, providerTurnId: null }); + assert.isFalse(routeProviderEvent(oldTurnEvent, newAttempt, newState)[0]); +}); diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index bbc61b9612..a2e00a2fb1 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -9,7 +9,10 @@ import { type OrchestrationV2RunAttempt, type OrchestrationV2TurnItem, type ProviderSessionId, + type ProviderThreadId, + type ProviderTurnId, type RunAttemptId, + type ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; @@ -32,6 +35,127 @@ import type { } from "./ProviderAdapter.ts"; import { ProviderEventIngestorV2 } from "./ProviderEventIngestor.ts"; +export interface ProviderEventRoutingState { + readonly ownedThreadIds: ReadonlySet; + readonly ownedProviderThreadIds: ReadonlySet; + readonly ownedProviderTurnIds: ReadonlySet; + readonly rootProviderTurnId: ProviderTurnId | null; +} + +export interface ProviderEventRouteIdentity { + readonly threadId: ThreadId; + readonly runId: OrchestrationV2Run["id"]; + readonly attemptId: RunAttemptId; + readonly providerThreadId: ProviderThreadId; +} + +export function makeProviderEventRoutingState(input: { + readonly identity: ProviderEventRouteIdentity; + readonly providerTurnId: ProviderTurnId | null; + readonly relatedThreadIds?: ReadonlyArray; + readonly relatedProviderThreadIds?: ReadonlyArray; +}): ProviderEventRoutingState { + return { + ownedThreadIds: new Set([input.identity.threadId, ...(input.relatedThreadIds ?? [])]), + ownedProviderThreadIds: new Set([ + input.identity.providerThreadId, + ...(input.relatedProviderThreadIds ?? []), + ]), + ownedProviderTurnIds: + input.providerTurnId === null ? new Set() : new Set([input.providerTurnId]), + rootProviderTurnId: input.providerTurnId, + }; +} + +export function routeProviderEvent( + event: ProviderAdapterV2Event, + input: ProviderEventRouteIdentity, + state: ProviderEventRoutingState, +): readonly [boolean, ProviderEventRoutingState] { + const ownsThread = (threadId: ThreadId): boolean => state.ownedThreadIds.has(threadId); + const ownsChildThread = (threadId: ThreadId): boolean => + threadId !== input.threadId && ownsThread(threadId); + const ownsRun = (runId: string | null): boolean => runId === input.runId; + const addProviderThread = (providerThreadId: ProviderThreadId): ProviderEventRoutingState => ({ + ...state, + ownedProviderThreadIds: new Set([...state.ownedProviderThreadIds, providerThreadId]), + }); + const addProviderTurn = ( + providerTurnId: ProviderTurnId, + root: boolean, + ): ProviderEventRoutingState => ({ + ...state, + ownedProviderTurnIds: new Set([...state.ownedProviderTurnIds, providerTurnId]), + rootProviderTurnId: root ? providerTurnId : state.rootProviderTurnId, + }); + + switch (event.type) { + case "provider_session.updated": + // The session manager persists process-wide status once for every + // attached app thread before broadcasting the adapter event. + return [false, state]; + case "app_thread.created": { + if (event.appThread.id === input.threadId) { + return [true, state]; + } + const isOwnedSubagent = + event.appThread.lineage.relationshipToParent === "subagent" && + event.appThread.lineage.parentThreadId !== null && + ownsThread(event.appThread.lineage.parentThreadId); + if (!isOwnedSubagent) { + return [false, state]; + } + return [ + true, + { + ...state, + ownedThreadIds: new Set([...state.ownedThreadIds, event.appThread.id]), + }, + ]; + } + case "provider_thread.updated": { + const belongs = + state.ownedProviderThreadIds.has(event.providerThread.id) || + (event.providerThread.appThreadId !== null && ownsThread(event.providerThread.appThreadId)); + return belongs ? [true, addProviderThread(event.providerThread.id)] : [false, state]; + } + case "provider_turn.updated": { + const isRoot = event.providerTurn.runAttemptId === input.attemptId; + const belongs = + isRoot || + (event.providerTurn.providerThreadId !== input.providerThreadId && + state.ownedProviderThreadIds.has(event.providerTurn.providerThreadId)) || + state.ownedProviderTurnIds.has(event.providerTurn.id) || + (event.threadId !== undefined && ownsChildThread(event.threadId)); + return belongs ? [true, addProviderTurn(event.providerTurn.id, isRoot)] : [false, state]; + } + case "node.updated": { + const belongs = ownsRun(event.node.runId) || ownsChildThread(event.node.threadId); + if (!belongs || event.node.providerThreadId === null) { + return [belongs, state]; + } + return [true, addProviderThread(event.node.providerThreadId)]; + } + case "subagent.updated": + return [ownsRun(event.subagent.runId) || ownsChildThread(event.subagent.threadId), state]; + case "message.updated": + return [ownsRun(event.message.runId) || ownsChildThread(event.message.threadId), state]; + case "turn_item.updated": + return [ownsRun(event.turnItem.runId) || ownsChildThread(event.turnItem.threadId), state]; + case "plan.updated": + return [ownsRun(event.plan.runId) || ownsChildThread(event.plan.threadId), state]; + case "runtime_request.updated": + return [ + (event.threadId !== undefined && ownsChildThread(event.threadId)) || + (event.runtimeRequest.providerTurnId !== null && + state.ownedProviderTurnIds.has(event.runtimeRequest.providerTurnId)), + state, + ]; + case "turn.terminal": + return [event.providerTurnId === state.rootProviderTurnId, state]; + } +} + /** * ERRORS */ @@ -81,6 +205,8 @@ export interface RunExecutionServiceV2StartRootRunInput { readonly attempt: OrchestrationV2RunAttempt; readonly attemptId: RunAttemptId; readonly providerTurnOrdinal: number; + readonly relatedThreadIds?: ReadonlyArray; + readonly relatedProviderThreadIds?: ReadonlyArray; readonly shouldFinalizeRun?: () => Effect.Effect; readonly message: ProviderAdapterV2TurnMessage; readonly modelSelection: ModelSelection; @@ -309,12 +435,52 @@ export const layer: Layer.Layer< }), ), ); + yield* checkpointService + .captureBaseline({ + scope: input.checkpointScope, + ordinalWithinScope: Math.max(0, input.run.ordinal - 1), + }) + .pipe( + Effect.mapError( + (cause) => + new RunExecutionStartError({ + commandId: input.commandId, + runId: input.run.id, + cause, + }), + ), + ); const terminalStatus = yield* Ref.make | null>(null); const latestProviderThread = yield* Ref.make(input.providerThread); - const providerEventFiber = yield* input.session.events.pipe( + const routeIdentity: ProviderEventRouteIdentity = { + threadId: input.run.threadId, + runId: input.run.id, + attemptId: input.attempt.id, + providerThreadId: input.providerThread.id, + }; + const eventRouting = yield* Ref.make( + makeProviderEventRoutingState({ + identity: routeIdentity, + providerTurnId: input.attempt.providerTurnId, + ...(input.relatedThreadIds === undefined + ? {} + : { relatedThreadIds: input.relatedThreadIds }), + ...(input.relatedProviderThreadIds === undefined + ? {} + : { relatedProviderThreadIds: input.relatedProviderThreadIds }), + }), + ); + const eventSubscription = + input.session.subscribeEvents === undefined + ? { events: input.session.events, close: Effect.void } + : yield* input.session.subscribeEvents; + const providerEventFiber = yield* eventSubscription.events.pipe( + Stream.filterEffect((event) => + Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)), + ), Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runForEach((event) => Effect.gen(function* () { @@ -391,25 +557,10 @@ export const layer: Layer.Layer< ), ), ), + Effect.ensuring(eventSubscription.close), Effect.forkDetach, ); - yield* checkpointService - .captureBaseline({ - scope: input.checkpointScope, - ordinalWithinScope: Math.max(0, input.run.ordinal - 1), - }) - .pipe( - Effect.mapError( - (cause) => - new RunExecutionStartError({ - commandId: input.commandId, - runId: input.run.id, - cause, - }), - ), - ); - yield* input.session .startTurn({ appThread: input.appThread, diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index d3cf0bb060..f6d8fa6f16 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -99,7 +99,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray