TypeScript
refactor(provider): trace adapter operations without per-chunk spans (#21992)
Julius Marminge05ad901e4947
diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.tsindex 424cb79b6b7..34201a35dbe 100644--- a/packages/provider-acp/src/server/AcpSessionRuntime.ts+++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts@@ -1256,1270 +1256,1264 @@ interface AcpActivePrompt {readonly completed: Deferred.Deferred<void>;}-export const make = (+export const make = Effect.fn("AcpSessionRuntime.make")(function* (options: AcpSessionRuntimeOptions,-): Effect.Effect<+): Effect.fn.Return<AcpSessionRuntime["Service"],EffectAcpErrors.AcpError,ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope-> =>- Effect.gen(function* () {- const crypto = yield* Crypto.Crypto;- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const runtimeScope = yield* Scope.fork(yield* Scope.Scope);- const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();- const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);- const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallTrackedState>());- const shownToolCallIds = new Set<string>();- const assistantItemRuntimeId = yield* crypto.randomUUIDv4().pipe(- Effect.mapError(- (cause) =>- new EffectAcpErrors.AcpTransportError({- detail: "Failed to generate an ACP assistant item runtime identifier.",- cause,+> {+ const crypto = yield* Crypto.Crypto;+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const runtimeScope = yield* Scope.fork(yield* Scope.Scope);+ const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();+ const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);+ const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallTrackedState>());+ const shownToolCallIds = new Set<string>();+ const assistantItemRuntimeId = yield* crypto.randomUUIDv4().pipe(+ Effect.mapError(+ (cause) =>+ new EffectAcpErrors.AcpTransportError({+ detail: "Failed to generate an ACP assistant item runtime identifier.",+ cause,+ }),+ ),+ );+ const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });+ const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));+ const initializeStateRef = yield* Ref.make<AcpInitializeState>({ _tag: "NotStarted" });+ const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });+ const startupMetadataRef = yield* Ref.make<ReadonlyArray<EffectAcpSchema.SessionNotification>>(+ [],+ );+ const notificationSemaphore = yield* Semaphore.make(1);+ const terminationErrorRef = yield* Ref.make<Option.Option<EffectAcpErrors.AcpError>>(+ Option.none(),+ );+ const stoppingRef = yield* Ref.make(false);+ const stderrFailure = yield* Deferred.make<never, EffectAcpErrors.AcpError>();+ const stderrTailRef = yield* Ref.make("");+ const homeDirectory = yield* HostProcess.HomeDirectory;+ const stderrDrained = yield* Deferred.make<void>();+ const runtimeClosed = yield* Deferred.make<void>();+ const promptSerializationSemaphore = yield* Semaphore.make(1);+ const sessionLoadSemaphore = yield* Semaphore.make(1);+ const promptDispatchSemaphore = yield* Semaphore.make(1);+ const activePromptRef = yield* Ref.make<Option.Option<AcpActivePrompt>>(Option.none());+ const assistantUpdatesOpenRef = yield* Ref.make(true);+ const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());++ const ensureConnected = Effect.gen(function* () {+ const error = yield* Ref.get(terminationErrorRef);+ if (Option.isSome(error)) {+ return yield* error.value;+ }+ if (yield* Ref.get(stoppingRef)) {+ return yield* new EffectAcpErrors.AcpTransportError({+ detail: "The ACP session runtime is closed.",+ cause: undefined,+ });+ }+ });++ const enrichProcessExitWithStderr = (+ error: EffectAcpErrors.AcpError,+ ): Effect.Effect<EffectAcpErrors.AcpError> =>+ error._tag !== "AcpProcessExitedError" || (error.stderr?.trim().length ?? 0) > 0+ ? Effect.succeed(error)+ : Deferred.await(stderrDrained).pipe(+ Effect.timeout("250 millis"),+ Effect.ignore,+ Effect.andThen(Ref.get(stderrTailRef)),+ Effect.map((tail) => {+ const stderr = sanitizeAcpStderrExcerpt(tail, homeDirectory);+ return stderr.length === 0+ ? error+ : new EffectAcpErrors.AcpProcessExitedError({+ ...(error.code !== undefined ? { code: error.code } : {}),+ ...(error.pid !== undefined ? { pid: error.pid } : {}),+ stderr,+ ...(error.cause !== undefined ? { cause: error.cause } : {}),+ });}),- ),- );- const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });- const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));- const initializeStateRef = yield* Ref.make<AcpInitializeState>({ _tag: "NotStarted" });- const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });- const startupMetadataRef = yield* Ref.make<ReadonlyArray<EffectAcpSchema.SessionNotification>>(- [],- );- const notificationSemaphore = yield* Semaphore.make(1);- const terminationErrorRef = yield* Ref.make<Option.Option<EffectAcpErrors.AcpError>>(- Option.none(),+ );++ const recordTermination = Effect.fn("AcpSessionRuntime.recordTermination")(function* (+ error: EffectAcpErrors.AcpError,+ ) {+ if (yield* Ref.get(stoppingRef)) {+ return;+ }+ const enriched = yield* enrichProcessExitWithStderr(error);+ const firstTermination = yield* Ref.modify(terminationErrorRef, (current) =>+ Option.isSome(current)+ ? ([false, current] as const)+ : ([true, Option.some(enriched)] as const),);- const stoppingRef = yield* Ref.make(false);- const stderrFailure = yield* Deferred.make<never, EffectAcpErrors.AcpError>();- const stderrTailRef = yield* Ref.make("");- const homeDirectory = yield* HostProcess.HomeDirectory;- const stderrDrained = yield* Deferred.make<void>();- const runtimeClosed = yield* Deferred.make<void>();- const promptSerializationSemaphore = yield* Semaphore.make(1);- const sessionLoadSemaphore = yield* Semaphore.make(1);- const promptDispatchSemaphore = yield* Semaphore.make(1);- const activePromptRef = yield* Ref.make<Option.Option<AcpActivePrompt>>(Option.none());- const assistantUpdatesOpenRef = yield* Ref.make(true);- const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());-- const ensureConnected = Effect.gen(function* () {- const error = yield* Ref.get(terminationErrorRef);- if (Option.isSome(error)) {- return yield* error.value;- }- if (yield* Ref.get(stoppingRef)) {- return yield* new EffectAcpErrors.AcpTransportError({- detail: "The ACP session runtime is closed.",- cause: undefined,- });- }- });+ if (!firstTermination) {+ return;+ }+ yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });+ yield* Queue.offer(eventQueue, { _tag: "ConnectionTerminated", error: enriched });+ });- const enrichProcessExitWithStderr = (- error: EffectAcpErrors.AcpError,- ): Effect.Effect<EffectAcpErrors.AcpError> =>- error._tag !== "AcpProcessExitedError" || (error.stderr?.trim().length ?? 0) > 0- ? Effect.succeed(error)- : Deferred.await(stderrDrained).pipe(- Effect.timeout("250 millis"),- Effect.ignore,- Effect.andThen(Ref.get(stderrTailRef)),- Effect.map((tail) => {- const stderr = sanitizeAcpStderrExcerpt(tail, homeDirectory);- return stderr.length === 0- ? error- : new EffectAcpErrors.AcpProcessExitedError({- ...(error.code !== undefined ? { code: error.code } : {}),- ...(error.pid !== undefined ? { pid: error.pid } : {}),- stderr,- ...(error.cause !== undefined ? { cause: error.cause } : {}),- });+ const logRequest = (event: AcpSessionRequestLogEvent) =>+ options.requestLogger ? options.requestLogger(event) : Effect.void;++ const runLoggedRequest = <A>(+ method: string,+ payload: unknown,+ effect: Effect.Effect<A, EffectAcpErrors.AcpError>,+ ): Effect.Effect<A, EffectAcpErrors.AcpError> =>+ logRequest({ method, payload, status: "started" }).pipe(+ Effect.flatMap(() =>+ (options.onStderr ? Effect.raceFirst(effect, Deferred.await(stderrFailure)) : effect).pipe(+ Effect.catch((error) =>+ enrichProcessExitWithStderr(error).pipe(Effect.flatMap(Effect.fail)),+ ),+ Effect.tap((result) =>+ logRequest({+ method,+ payload,+ status: "succeeded",+ result,}),- );-- const recordTermination = Effect.fn("AcpSessionRuntime.recordTermination")(function* (- error: EffectAcpErrors.AcpError,- ) {- if (yield* Ref.get(stoppingRef)) {- return;- }- const enriched = yield* enrichProcessExitWithStderr(error);- const firstTermination = yield* Ref.modify(terminationErrorRef, (current) =>- Option.isSome(current)- ? ([false, current] as const)- : ([true, Option.some(enriched)] as const),- );- if (!firstTermination) {- return;- }- yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });- yield* Queue.offer(eventQueue, { _tag: "ConnectionTerminated", error: enriched });- });-- const logRequest = (event: AcpSessionRequestLogEvent) =>- options.requestLogger ? options.requestLogger(event) : Effect.void;-- const runLoggedRequest = <A>(- method: string,- payload: unknown,- effect: Effect.Effect<A, EffectAcpErrors.AcpError>,- ): Effect.Effect<A, EffectAcpErrors.AcpError> =>- logRequest({ method, payload, status: "started" }).pipe(- Effect.flatMap(() =>- (options.onStderr- ? Effect.raceFirst(effect, Deferred.await(stderrFailure))- : effect- ).pipe(- Effect.catch((error) =>- enrichProcessExitWithStderr(error).pipe(Effect.flatMap(Effect.fail)),- ),- Effect.tap((result) =>- logRequest({- method,- payload,- status: "succeeded",- result,- }),- ),- Effect.onError((cause) =>- logRequest({- method,- payload,- status: "failed",- cause,- }),- ),),- ),- );-- const spawnCommand =- options.spawn.shell === false- ? { command: options.spawn.command, args: options.spawn.args, shell: false }- : yield* resolveSpawnCommand(options.spawn.command, options.spawn.args, {- ...(options.spawn.env ? { env: options.spawn.env } : {}),- extendEnv: options.spawn.extendEnv ?? true,- });- const linuxCgroupLease =- options.ownDescendantProcessGroups === true && options.processGroupPlatform === "linux"- ? yield* Effect.sync(() => {- try {- if (options.linuxCgroupController === null) return undefined;- return (options.linuxCgroupController ?? makeLinuxCgroupController()).create();- } catch {- return undefined;- }- })- : undefined;- // This is lifecycle containment for inherited provider work. It is not a- // security boundary against a provider that can modify its delegated cgroup.- if (linuxCgroupLease !== undefined) {- yield* Scope.addFinalizer(- runtimeScope,- Effect.uninterruptible(terminateLinuxCgroupLease(linuxCgroupLease)).pipe(- Effect.ignoreCause({ log: true }),- ),- );- }- const containedTargetCommand =- linuxCgroupLease === undefined || NodePath.isAbsolute(spawnCommand.command)- ? spawnCommand.command- : yield* Effect.gen(function* () {- const resolved = resolveLinuxCgroupTargetCommand(- spawnCommand.command,- options.spawn.cwd ?? options.cwd,- { ...process.env, ...options.spawn.env },- );- if (resolved !== undefined) return resolved;- return yield* new EffectAcpErrors.AcpSpawnError({- command: options.spawn.command,- cause: new Error("Contained ACP command was not found on PATH"),- });- });- const scopedSpawnCommand =- linuxCgroupLease !== undefined || spawnCommand.shell- ? spawnCommand- : {- ...(yield* (yield* AgentScope).wrap({- command: spawnCommand.command,- args: spawnCommand.args,- name: "acp",- threadId: yield* AgentScopeThreadId,- env: { ...process.env, ...options.spawn.env },- })),- shell: false,- };- const containedSpawnCommand =- linuxCgroupLease === undefined- ? scopedSpawnCommand- : {- ...wrapCommandForLinuxCgroup(- linuxCgroupLease,- containedTargetCommand,- spawnCommand.args,- ),- shell: false,- };- const spawnEnvironment =- linuxCgroupLease === undefined- ? options.spawn.env- : {- ...options.spawn.env,- ELECTRON_RUN_AS_NODE: "1",- T3_ACP_CGROUP_WRAPPER: "1",- };- const child = yield* spawner- .spawn(- ChildProcess.make(containedSpawnCommand.command, containedSpawnCommand.args, {- ...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),- ...(spawnEnvironment ? { env: spawnEnvironment } : {}),- extendEnv: options.spawn.extendEnv ?? true,- ...(options.ownDetachedProcessGroup === undefined- ? {}- : { detached: options.ownDetachedProcessGroup }),- shell: containedSpawnCommand.shell,- }),- )- .pipe(- Effect.provideService(Scope.Scope, runtimeScope),- Effect.mapError(- (cause) =>- new EffectAcpErrors.AcpSpawnError({- command: options.spawn.command,+ Effect.onError((cause) =>+ logRequest({+ method,+ payload,+ status: "failed",cause,}),+ ),),- );+ ),+ );- const posixOwnershipLedger = new Map<string, AcpOwnedPosixProcess>();- const posixOwnershipFrontier = new Map<number, AcpOwnedPosixProcess>();- const posixOwnershipChildQueues = new Map<number, Array<number>>();- const posixOwnershipRoot: AcpPosixOwnershipRoot = { value: undefined };- const posixController =- options.ownDescendantProcessGroups === true- ? yield* Effect.try({- try: () => {- if (options.posixProcessTreeController !== undefined) {- return options.posixProcessTreeController;- }- if (options.processGroupPlatform === undefined) {- throw new AcpProcessGroupTerminationError({- detail: "POSIX ACP descendant ownership requires a supported host platform",- });- }- return makePosixProcessTreeController(options.processGroupPlatform);- },- catch: (cause) =>- new EffectAcpErrors.AcpSpawnError({ command: options.spawn.command, cause }),- })- : undefined;- if (posixController !== undefined) {- const observeOwnership = () =>- observePosixOwnershipLedger({- childQueues: posixOwnershipChildQueues,- controller: posixController,- frontier: posixOwnershipFrontier,- ledger: posixOwnershipLedger,- root: posixOwnershipRoot,- rootPid: Number(child.pid),+ const spawnCommand =+ options.spawn.shell === false+ ? { command: options.spawn.command, args: options.spawn.args, shell: false }+ : yield* resolveSpawnCommand(options.spawn.command, options.spawn.args, {+ ...(options.spawn.env ? { env: options.spawn.env } : {}),+ extendEnv: options.spawn.extendEnv ?? true,});- yield* Effect.try({- try: observeOwnership,- catch: (cause) =>- new EffectAcpErrors.AcpSpawnError({ command: options.spawn.command, cause }),- });- yield* observePosixOwnershipLedgerContinuously({+ const linuxCgroupLease =+ options.ownDescendantProcessGroups === true && options.processGroupPlatform === "linux"+ ? yield* Effect.sync(() => {+ try {+ if (options.linuxCgroupController === null) return undefined;+ return (options.linuxCgroupController ?? makeLinuxCgroupController()).create();+ } catch {+ return undefined;+ }+ })+ : undefined;+ // This is lifecycle containment for inherited provider work. It is not a+ // security boundary against a provider that can modify its delegated cgroup.+ if (linuxCgroupLease !== undefined) {+ yield* Scope.addFinalizer(+ runtimeScope,+ Effect.uninterruptible(terminateLinuxCgroupLease(linuxCgroupLease)).pipe(+ Effect.ignoreCause({ log: true }),+ ),+ );+ }+ const containedTargetCommand =+ linuxCgroupLease === undefined || NodePath.isAbsolute(spawnCommand.command)+ ? spawnCommand.command+ : yield* Effect.gen(function* () {+ const resolved = resolveLinuxCgroupTargetCommand(+ spawnCommand.command,+ options.spawn.cwd ?? options.cwd,+ { ...process.env, ...options.spawn.env },+ );+ if (resolved !== undefined) return resolved;+ return yield* new EffectAcpErrors.AcpSpawnError({+ command: options.spawn.command,+ cause: new Error("Contained ACP command was not found on PATH"),+ });+ });+ const scopedSpawnCommand =+ linuxCgroupLease !== undefined || spawnCommand.shell+ ? spawnCommand+ : {+ ...(yield* (yield* AgentScope).wrap({+ command: spawnCommand.command,+ args: spawnCommand.args,+ name: "acp",+ threadId: yield* AgentScopeThreadId,+ env: { ...process.env, ...options.spawn.env },+ })),+ shell: false,+ };+ const containedSpawnCommand =+ linuxCgroupLease === undefined+ ? scopedSpawnCommand+ : {+ ...wrapCommandForLinuxCgroup(linuxCgroupLease, containedTargetCommand, spawnCommand.args),+ shell: false,+ };+ const spawnEnvironment =+ linuxCgroupLease === undefined+ ? options.spawn.env+ : {+ ...options.spawn.env,+ ELECTRON_RUN_AS_NODE: "1",+ T3_ACP_CGROUP_WRAPPER: "1",+ };+ const child = yield* spawner+ .spawn(+ ChildProcess.make(containedSpawnCommand.command, containedSpawnCommand.args, {+ ...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),+ ...(spawnEnvironment ? { env: spawnEnvironment } : {}),+ extendEnv: options.spawn.extendEnv ?? true,+ ...(options.ownDetachedProcessGroup === undefined+ ? {}+ : { detached: options.ownDetachedProcessGroup }),+ shell: containedSpawnCommand.shell,+ }),+ )+ .pipe(+ Effect.provideService(Scope.Scope, runtimeScope),+ Effect.mapError(+ (cause) =>+ new EffectAcpErrors.AcpSpawnError({+ command: options.spawn.command,+ cause,+ }),+ ),+ );++ const posixOwnershipLedger = new Map<string, AcpOwnedPosixProcess>();+ const posixOwnershipFrontier = new Map<number, AcpOwnedPosixProcess>();+ const posixOwnershipChildQueues = new Map<number, Array<number>>();+ const posixOwnershipRoot: AcpPosixOwnershipRoot = { value: undefined };+ const posixController =+ options.ownDescendantProcessGroups === true+ ? yield* Effect.try({+ try: () => {+ if (options.posixProcessTreeController !== undefined) {+ return options.posixProcessTreeController;+ }+ if (options.processGroupPlatform === undefined) {+ throw new AcpProcessGroupTerminationError({+ detail: "POSIX ACP descendant ownership requires a supported host platform",+ });+ }+ return makePosixProcessTreeController(options.processGroupPlatform);+ },+ catch: (cause) =>+ new EffectAcpErrors.AcpSpawnError({ command: options.spawn.command, cause }),+ })+ : undefined;+ if (posixController !== undefined) {+ const observeOwnership = () =>+ observePosixOwnershipLedger({childQueues: posixOwnershipChildQueues,controller: posixController,frontier: posixOwnershipFrontier,ledger: posixOwnershipLedger,root: posixOwnershipRoot,rootPid: Number(child.pid),- }).pipe(Effect.forkIn(runtimeScope));- }+ });+ yield* Effect.try({+ try: observeOwnership,+ catch: (cause) =>+ new EffectAcpErrors.AcpSpawnError({ command: options.spawn.command, cause }),+ });+ yield* observePosixOwnershipLedgerContinuously({+ childQueues: posixOwnershipChildQueues,+ controller: posixController,+ frontier: posixOwnershipFrontier,+ ledger: posixOwnershipLedger,+ root: posixOwnershipRoot,+ rootPid: Number(child.pid),+ }).pipe(Effect.forkIn(runtimeScope));+ }- const signalOwnedProcessGroup = (signal: NodeJS.Signals) =>- Effect.try({- try: () => {- signalProcessGroup(Number(child.pid), signal);- return true;- },- catch: (cause) =>- new AcpProcessGroupTerminationError({- cause,- detail: `Failed to signal ACP process group ${child.pid} with ${signal}`,- }),- }).pipe(- Effect.catch((error) => {- const cause = error.cause as NodeJS.ErrnoException | undefined;- return cause?.code === "ESRCH" ? Effect.succeed(false) : Effect.fail(error);+ const signalOwnedProcessGroup = (signal: NodeJS.Signals) =>+ Effect.try({+ try: () => {+ signalProcessGroup(Number(child.pid), signal);+ return true;+ },+ catch: (cause) =>+ new AcpProcessGroupTerminationError({+ cause,+ detail: `Failed to signal ACP process group ${child.pid} with ${signal}`,}),- );- const terminateWindowsProcessTree =- options.windowsProcessTreeTerminator ??- ((pid: number) =>- terminateWindowsProcessTreeWithTaskkill(pid).pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- ));- const terminatePosixProcessTree = (grace: Duration.Input, platformOverride?: NodeJS.Platform) =>- Effect.gen(function* () {- const platform = platformOverride ?? options.processGroupPlatform;- if (platform === undefined || platform === "win32") {- return yield* new AcpProcessGroupTerminationError({- detail: "POSIX ACP descendant ownership requires a supported host platform",- });- }- const controller = yield* Effect.try({- try: () => posixController ?? makePosixProcessTreeController(platform),- catch: (cause) =>- isAcpProcessGroupTerminationError(cause)- ? cause- : new AcpProcessGroupTerminationError({- cause,- detail: `Failed to initialize ACP descendant ownership on ${platform}`,- }),- });- yield* terminatePosixOwnedProcessTree({- controller,- grace,- ledger: posixOwnershipLedger,- root: posixOwnershipRoot,- rootPid: Number(child.pid),- });- });- const terminateOwnedProcessGroupImpl = Effect.gen(function* () {- if (options.ownDetachedProcessGroup !== true) return;- if (options.processGroupPlatform === undefined) {+ }).pipe(+ Effect.catch((error) => {+ const cause = error.cause as NodeJS.ErrnoException | undefined;+ return cause?.code === "ESRCH" ? Effect.succeed(false) : Effect.fail(error);+ }),+ );+ const terminateWindowsProcessTree =+ options.windowsProcessTreeTerminator ??+ ((pid: number) =>+ terminateWindowsProcessTreeWithTaskkill(pid).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ ));+ const terminatePosixProcessTree = Effect.fn("AcpSessionRuntime.terminatePosixProcessTree")(+ function* (grace: Duration.Input, platformOverride?: NodeJS.Platform) {+ const platform = platformOverride ?? options.processGroupPlatform;+ if (platform === undefined || platform === "win32") {return yield* new AcpProcessGroupTerminationError({- detail: "Detached ACP process-group ownership requires a host platform",+ detail: "POSIX ACP descendant ownership requires a supported host platform",});}- if (options.processGroupPlatform === "win32") {- return yield* terminateWindowsProcessTree(Number(child.pid));- }- if (linuxCgroupLease !== undefined) {- if (posixController !== undefined) {- yield* Effect.sync(() =>- signalLinuxCgroupRootTerm({- controller: posixController,- lease: linuxCgroupLease,- root: posixOwnershipRoot,- }),- );- }- const grace = options.processGroupTerminationGrace ?? "1 second";- if (grace !== 0) yield* Effect.sleep(grace);- return yield* terminateLinuxCgroupLease(linuxCgroupLease);- }- if (options.ownDescendantProcessGroups === true) {- return yield* terminatePosixProcessTree(options.processGroupTerminationGrace ?? "1 second");+ const controller = yield* Effect.try({+ try: () => posixController ?? makePosixProcessTreeController(platform),+ catch: (cause) =>+ isAcpProcessGroupTerminationError(cause)+ ? cause+ : new AcpProcessGroupTerminationError({+ cause,+ detail: `Failed to initialize ACP descendant ownership on ${platform}`,+ }),+ });+ yield* terminatePosixOwnedProcessTree({+ controller,+ grace,+ ledger: posixOwnershipLedger,+ root: posixOwnershipRoot,+ rootPid: Number(child.pid),+ });+ },+ );+ const terminateOwnedProcessGroupImpl = Effect.gen(function* () {+ if (options.ownDetachedProcessGroup !== true) return;+ if (options.processGroupPlatform === undefined) {+ return yield* new AcpProcessGroupTerminationError({+ detail: "Detached ACP process-group ownership requires a host platform",+ });+ }+ if (options.processGroupPlatform === "win32") {+ return yield* terminateWindowsProcessTree(Number(child.pid));+ }+ if (linuxCgroupLease !== undefined) {+ if (posixController !== undefined) {+ yield* Effect.sync(() =>+ signalLinuxCgroupRootTerm({+ controller: posixController,+ lease: linuxCgroupLease,+ root: posixOwnershipRoot,+ }),+ );}- const groupExisted = yield* signalOwnedProcessGroup("SIGTERM");- if (!groupExisted) return;const grace = options.processGroupTerminationGrace ?? "1 second";- if (grace !== 0) {- yield* Effect.sleep(grace);- }- yield* signalOwnedProcessGroup("SIGKILL");- }).pipe(withWallClock);- const terminateProcessGroup = yield* Effect.cached(- Effect.uninterruptible(terminateOwnedProcessGroupImpl),+ if (grace !== 0) yield* Effect.sleep(grace);+ return yield* terminateLinuxCgroupLease(linuxCgroupLease);+ }+ if (options.ownDescendantProcessGroups === true) {+ return yield* terminatePosixProcessTree(options.processGroupTerminationGrace ?? "1 second");+ }+ const groupExisted = yield* signalOwnedProcessGroup("SIGTERM");+ if (!groupExisted) return;+ const grace = options.processGroupTerminationGrace ?? "1 second";+ if (grace !== 0) {+ yield* Effect.sleep(grace);+ }+ yield* signalOwnedProcessGroup("SIGKILL");+ }).pipe(withWallClock);+ const terminateProcessGroup = yield* Effect.cached(+ Effect.uninterruptible(terminateOwnedProcessGroupImpl),+ );+ if (options.ownDetachedProcessGroup === true) {+ const hostPlatform = yield* HostProcess.Platform;+ const forceTerminateOwnedProcessGroup =+ hostPlatform === "win32"+ ? terminateWindowsProcessTreeWithTaskkill(Number(child.pid)).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ )+ : linuxCgroupLease !== undefined+ ? terminateLinuxCgroupLease(linuxCgroupLease)+ : options.ownDescendantProcessGroups === true+ ? terminatePosixProcessTree(0, hostPlatform)+ : signalOwnedProcessGroup("SIGKILL").pipe(Effect.asVoid);+ yield* Scope.addFinalizer(+ runtimeScope,+ Effect.uninterruptible(forceTerminateOwnedProcessGroup).pipe(+ Effect.ignoreCause({ log: true }),+ ),);- if (options.ownDetachedProcessGroup === true) {- const hostPlatform = yield* HostProcess.Platform;- const forceTerminateOwnedProcessGroup =- hostPlatform === "win32"- ? terminateWindowsProcessTreeWithTaskkill(Number(child.pid)).pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- )- : linuxCgroupLease !== undefined- ? terminateLinuxCgroupLease(linuxCgroupLease)- : options.ownDescendantProcessGroups === true- ? terminatePosixProcessTree(0, hostPlatform)- : signalOwnedProcessGroup("SIGKILL").pipe(Effect.asVoid);- yield* Scope.addFinalizer(- runtimeScope,- Effect.uninterruptible(forceTerminateOwnedProcessGroup).pipe(- Effect.ignoreCause({ log: true }),+ }+ yield* child.stderr.pipe(+ Stream.decodeText(),+ Stream.runForEach((chunk) =>+ Ref.update(stderrTailRef, (current) => appendAcpStderrTail(current, chunk)).pipe(+ Effect.andThen(+ options.onStderr ? options.onStderr(chunk.slice(-maxStderrChunkLength)) : Effect.void,),- );- }- yield* child.stderr.pipe(- Stream.decodeText(),- Stream.runForEach((chunk) =>- Ref.update(stderrTailRef, (current) => appendAcpStderrTail(current, chunk)).pipe(- Effect.andThen(- options.onStderr ? options.onStderr(chunk.slice(-maxStderrChunkLength)) : Effect.void,- ),- Effect.catch((error) =>- Effect.gen(function* () {- yield* Deferred.fail(stderrFailure, error);- yield* recordTermination(error);- yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);- }),- ),+ Effect.catch((error) =>+ Effect.gen(function* () {+ yield* Deferred.fail(stderrFailure, error);+ yield* recordTermination(error);+ yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);+ }),),),- Effect.ensuring(Deferred.succeed(stderrDrained, undefined)),- Effect.ignore,- Effect.forkIn(runtimeScope),- );+ ),+ Effect.ensuring(Deferred.succeed(stderrDrained, undefined)),+ Effect.ignore,+ Effect.forkIn(runtimeScope),+ );- const acpContext = yield* Layer.build(- EffectAcpClient.layerChildProcess(child, {- ...(options.transformStdout ? { transformStdout: options.transformStdout } : {}),- ...(options.transformSessionUpdate- ? { transformSessionUpdate: options.transformSessionUpdate }- : {}),- ...(options.protocolLogging?.logIncoming !== undefined- ? { logIncoming: options.protocolLogging.logIncoming }- : {}),- ...(options.protocolLogging?.logOutgoing !== undefined- ? { logOutgoing: options.protocolLogging.logOutgoing }- : {}),- ...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),- ...(options.onIncomingRequest ? { onIncomingRequest: options.onIncomingRequest } : {}),- onTermination: (error) =>- recordTermination(error).pipe(- Effect.andThen(options.onTermination?.(error) ?? Effect.void),- Effect.ensuring(- Scope.close(runtimeScope, Exit.fail(error)).pipe(Effect.forkDetach, Effect.asVoid),- ),+ const acpContext = yield* Layer.build(+ EffectAcpClient.layerChildProcess(child, {+ ...(options.transformStdout ? { transformStdout: options.transformStdout } : {}),+ ...(options.transformSessionUpdate+ ? { transformSessionUpdate: options.transformSessionUpdate }+ : {}),+ ...(options.protocolLogging?.logIncoming !== undefined+ ? { logIncoming: options.protocolLogging.logIncoming }+ : {}),+ ...(options.protocolLogging?.logOutgoing !== undefined+ ? { logOutgoing: options.protocolLogging.logOutgoing }+ : {}),+ ...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),+ ...(options.onIncomingRequest ? { onIncomingRequest: options.onIncomingRequest } : {}),+ onTermination: (error) =>+ recordTermination(error).pipe(+ Effect.andThen(options.onTermination?.(error) ?? Effect.void),+ Effect.ensuring(+ Scope.close(runtimeScope, Exit.fail(error)).pipe(Effect.forkDetach, Effect.asVoid),),- ...(options.onOutgoingResponseFailure- ? { onOutgoingResponseFailure: options.onOutgoingResponseFailure }- : {}),- ...(options.onOutgoingResponse ? { onOutgoingResponse: options.onOutgoingResponse } : {}),- }),- ).pipe(Effect.provideService(Scope.Scope, runtimeScope));-- const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));-- const processSessionUpdate = (notification: EffectAcpSchema.SessionNotification) =>- handleSessionUpdate({- queue: eventQueue,- modeStateRef,- configOptionsRef,- toolCallsRef,- shownToolCallIds,- assistantSegmentRef,- assistantItemRuntimeId,- params: notification,- });-- yield* acp.handleSessionUpdate((notification) =>- notificationSemaphore.withPermit(- Effect.gen(function* () {- if (Option.isSome(yield* Ref.get(terminationErrorRef))) {- return;- }- const gate = yield* Ref.get(sessionLoadGateRef);- // A different session can still have an in-flight prompt while this- // load replays history, so quarantine only the loading session.- const loadingThisSession =- Option.isSome(gate) &&- gate.value.active &&- notification.sessionId === gate.value.sessionId;- if (- loadingThisSession &&- sessionUpdateCountsAsLoadReplayActivity(notification, gate.value.sessionId)- ) {- const lastActivityAtMillis = yield* Clock.currentTimeMillis;- yield* Ref.set(- sessionLoadGateRef,- Option.some({- ...gate.value,- lastActivityAtMillis,- }),- );- }- if (sessionUpdateIsReplay(notification)) {- return;- }- const startState = yield* Ref.get(startStateRef);- if (startState._tag === "Starting") {- if (isStartupMetadataUpdate(notification)) {- yield* Ref.update(startupMetadataRef, (current) =>- [- ...current.filter(- (previous) =>- previous.sessionId !== notification.sessionId ||- previous.update.sessionUpdate !== notification.update.sessionUpdate,- ),- notification,- ].slice(-maxStartupMetadataUpdates),- );- }- return;- }- if (loadingThisSession) {- if (notification.update.sessionUpdate === "config_option_update") {- const candidateConfigOptions = notification.update.configOptions;- yield* Ref.update(sessionLoadGateRef, (current) =>- Option.isSome(current)- ? Option.some({ ...current.value, candidateConfigOptions })- : current,- );- }- return;- }- // One runtime projects one root ACP session. Child-session updates need- // explicit lineage routing and must never be flattened into this stream.- if (- startState._tag !== "Started" ||- notification.sessionId !== startState.result.sessionId- ) {- return;- }- if (- !(yield* Ref.get(assistantUpdatesOpenRef)) &&- (notification.update.sessionUpdate === "agent_message_chunk" ||- notification.update.sessionUpdate === "agent_thought_chunk")- ) {- return;- }- yield* processSessionUpdate(notification);- }),- ),- );- yield* Scope.addFinalizer(- runtimeScope,- Ref.set(stoppingRef, true).pipe(Effect.andThen(Deferred.succeed(runtimeClosed, undefined))),- );- const initializeClientCapabilities = {- fs: {- readTextFile: false,- writeTextFile: false,- ...options.clientCapabilities?.fs,- },- terminal: options.clientCapabilities?.terminal ?? false,- ...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),- ...(options.clientCapabilities?.elicitation- ? { elicitation: options.clientCapabilities.elicitation }+ ),+ ...(options.onOutgoingResponseFailure+ ? { onOutgoingResponseFailure: options.onOutgoingResponseFailure }: {}),- ...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),- } satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;-- const getStartedState = Effect.gen(function* () {- yield* ensureConnected;- const state = yield* Ref.get(startStateRef);- if (state._tag === "Started") {- return state.result;- }- return yield* new EffectAcpErrors.AcpTransportError({- detail: "ACP session runtime has not been started",- cause: "ACP session runtime has not been started",- });+ ...(options.onOutgoingResponse ? { onOutgoingResponse: options.onOutgoingResponse } : {}),+ }),+ ).pipe(Effect.provideService(Scope.Scope, runtimeScope));++ const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));++ const processSessionUpdate = (notification: EffectAcpSchema.SessionNotification) =>+ handleSessionUpdate({+ queue: eventQueue,+ modeStateRef,+ configOptionsRef,+ toolCallsRef,+ shownToolCallIds,+ assistantSegmentRef,+ assistantItemRuntimeId,+ params: notification,});- const validateConfigOptionValue = (- configId: string,- value: string | boolean,- ): Effect.Effect<void, EffectAcpErrors.AcpError> =>+ yield* acp.handleSessionUpdate((notification) =>+ notificationSemaphore.withPermit(Effect.gen(function* () {- const configOptions = yield* Ref.get(configOptionsRef);- const configOption = findSessionConfigOption(configOptions, configId);- if (!configOption) {+ if (Option.isSome(yield* Ref.get(terminationErrorRef))) {+ return;+ }+ const gate = yield* Ref.get(sessionLoadGateRef);+ // A different session can still have an in-flight prompt while this+ // load replays history, so quarantine only the loading session.+ const loadingThisSession =+ Option.isSome(gate) &&+ gate.value.active &&+ notification.sessionId === gate.value.sessionId;+ if (+ loadingThisSession &&+ sessionUpdateCountsAsLoadReplayActivity(notification, gate.value.sessionId)+ ) {+ const lastActivityAtMillis = yield* Clock.currentTimeMillis;+ yield* Ref.set(+ sessionLoadGateRef,+ Option.some({+ ...gate.value,+ lastActivityAtMillis,+ }),+ );+ }+ if (sessionUpdateIsReplay(notification)) {return;}- if (configOption.type === "boolean") {- if (typeof value === "boolean") {- return;+ const startState = yield* Ref.get(startStateRef);+ if (startState._tag === "Starting") {+ if (isStartupMetadataUpdate(notification)) {+ yield* Ref.update(startupMetadataRef, (current) =>+ [+ ...current.filter(+ (previous) =>+ previous.sessionId !== notification.sessionId ||+ previous.update.sessionUpdate !== notification.update.sessionUpdate,+ ),+ notification,+ ].slice(-maxStartupMetadataUpdates),+ );}- return yield* new EffectAcpErrors.AcpRequestError({- code: -32602,- errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected boolean`,- data: {- configId: configOption.id,- expectedType: "boolean",- receivedValue: value,- },- });+ return;}- if (typeof value !== "string") {- return yield* new EffectAcpErrors.AcpRequestError({- code: -32602,- errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected string`,- data: {- configId: configOption.id,- expectedType: "string",- receivedValue: value,- },- });+ if (loadingThisSession) {+ if (notification.update.sessionUpdate === "config_option_update") {+ const candidateConfigOptions = notification.update.configOptions;+ yield* Ref.update(sessionLoadGateRef, (current) =>+ Option.isSome(current)+ ? Option.some({ ...current.value, candidateConfigOptions })+ : current,+ );+ }+ return;}- const allowedValues = collectSessionConfigOptionValues(configOption);- if (allowedValues.includes(value)) {+ // One runtime projects one root ACP session. Child-session updates need+ // explicit lineage routing and must never be flattened into this stream.+ if (+ startState._tag !== "Started" ||+ notification.sessionId !== startState.result.sessionId+ ) {return;}if (- configOption === findModelConfigOption(configOptions) &&- options.customModels?.includes(value)+ !(yield* Ref.get(assistantUpdatesOpenRef)) &&+ (notification.update.sessionUpdate === "agent_message_chunk" ||+ notification.update.sessionUpdate === "agent_thought_chunk")) {return;}+ yield* processSessionUpdate(notification);+ }),+ ),+ );+ yield* Scope.addFinalizer(+ runtimeScope,+ Ref.set(stoppingRef, true).pipe(Effect.andThen(Deferred.succeed(runtimeClosed, undefined))),+ );+ const initializeClientCapabilities = {+ fs: {+ readTextFile: false,+ writeTextFile: false,+ ...options.clientCapabilities?.fs,+ },+ terminal: options.clientCapabilities?.terminal ?? false,+ ...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),+ ...(options.clientCapabilities?.elicitation+ ? { elicitation: options.clientCapabilities.elicitation }+ : {}),+ ...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),+ } satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;++ const getStartedState = Effect.gen(function* () {+ yield* ensureConnected;+ const state = yield* Ref.get(startStateRef);+ if (state._tag === "Started") {+ return state.result;+ }+ return yield* new EffectAcpErrors.AcpTransportError({+ detail: "ACP session runtime has not been started",+ cause: "ACP session runtime has not been started",+ });+ });++ const validateConfigOptionValue = Effect.fn("AcpSessionRuntime.validateConfigOptionValue")(+ function* (+ configId: string,+ value: string | boolean,+ ): Effect.fn.Return<void, EffectAcpErrors.AcpError> {+ const configOptions = yield* Ref.get(configOptionsRef);+ const configOption = findSessionConfigOption(configOptions, configId);+ if (!configOption) {+ return;+ }+ if (configOption.type === "boolean") {+ if (typeof value === "boolean") {+ return;+ }+ return yield* new EffectAcpErrors.AcpRequestError({+ code: -32602,+ errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected boolean`,+ data: {+ configId: configOption.id,+ expectedType: "boolean",+ receivedValue: value,+ },+ });+ }+ if (typeof value !== "string") {return yield* new EffectAcpErrors.AcpRequestError({code: -32602,- errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,+ errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected string`,data: {configId: configOption.id,- allowedValues,+ expectedType: "string",receivedValue: value,},});+ }+ const allowedValues = collectSessionConfigOptionValues(configOption);+ if (allowedValues.includes(value)) {+ return;+ }+ if (+ configOption === findModelConfigOption(configOptions) &&+ options.customModels?.includes(value)+ ) {+ return;+ }+ return yield* new EffectAcpErrors.AcpRequestError({+ code: -32602,+ errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,+ data: {+ configId: configOption.id,+ allowedValues,+ receivedValue: value,+ },});+ },+ );- const updateConfigOptions = Effect.fn("AcpSessionRuntime.updateConfigOptions")(function* (- response:- | EffectAcpSchema.SetSessionConfigOptionResponse- | EffectAcpSchema.ForkSessionResponse- | EffectAcpSchema.LoadSessionResponse- | EffectAcpSchema.NewSessionResponse- | EffectAcpSchema.ResumeSessionResponse,- ) {- const configOptions = sessionConfigOptionsFromSetup(response);- yield* Ref.set(configOptionsRef, configOptions);- yield* Queue.offer(eventQueue, {- _tag: "ConfigOptionsUpdated",- configOptions,- rawPayload: response,- });+ const updateConfigOptions = Effect.fn("AcpSessionRuntime.updateConfigOptions")(function* (+ response:+ | EffectAcpSchema.SetSessionConfigOptionResponse+ | EffectAcpSchema.ForkSessionResponse+ | EffectAcpSchema.LoadSessionResponse+ | EffectAcpSchema.NewSessionResponse+ | EffectAcpSchema.ResumeSessionResponse,+ ) {+ const configOptions = sessionConfigOptionsFromSetup(response);+ yield* Ref.set(configOptionsRef, configOptions);+ yield* Queue.offer(eventQueue, {+ _tag: "ConfigOptionsUpdated",+ configOptions,+ rawPayload: response,});+ });- const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>- Ref.update(modeStateRef, (current) =>- current ? { ...current, currentModeId: modeId } : current,- );+ const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>+ Ref.update(modeStateRef, (current) =>+ current ? { ...current, currentModeId: modeId } : current,+ );- const adoptSession = (- sessionId: string,- sessionSetupResult:- | EffectAcpSchema.ForkSessionResponse- | EffectAcpSchema.LoadSessionResponse- | EffectAcpSchema.NewSessionResponse- | EffectAcpSchema.ResumeSessionResponse,- ): Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError> =>- Effect.gen(function* () {- const current = yield* getStartedState;- const meta = sessionSetupResult._meta;- const syntheticReplayIdle =- meta !== null &&- typeof meta === "object" &&- !Array.isArray(meta) &&- (meta as { readonly t3SessionLoadReady?: unknown }).t3SessionLoadReady === "replay_idle";- const extractedModelConfigId = extractModelConfigId(sessionSetupResult);- const nextModelConfigId =- extractedModelConfigId ?? (syntheticReplayIdle ? current.modelConfigId : undefined);- const nextModeState = parseSessionModeState(sessionSetupResult);- if (nextModeState !== undefined) {- yield* Ref.set(modeStateRef, nextModeState);- } else if (!syntheticReplayIdle) {- yield* Ref.set(modeStateRef, undefined);- }- // Synthetic replay-idle load responses only carry initialize model/mode- // meta; preserve live configOptions so setConfigOption still validates.- if (- sessionSetupResult.configOptions !== undefined &&- sessionSetupResult.configOptions !== null- ) {- yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));- } else if (!syntheticReplayIdle) {- yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));- }- const nextState = {- sessionId,- initializeResult: current.initializeResult,- sessionSetupResult,- modelConfigId: nextModelConfigId,- } satisfies AcpStartedState;- yield* Ref.set(toolCallsRef, new Map());- yield* Ref.set(assistantSegmentRef, { nextSegmentIndex: 0 });- yield* Ref.set(startStateRef, { _tag: "Started", result: nextState });- return nextState;- });+ const adoptSession = Effect.fn("AcpSessionRuntime.adoptSession")(function* (+ sessionId: string,+ sessionSetupResult:+ | EffectAcpSchema.ForkSessionResponse+ | EffectAcpSchema.LoadSessionResponse+ | EffectAcpSchema.NewSessionResponse+ | EffectAcpSchema.ResumeSessionResponse,+ ): Effect.fn.Return<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError> {+ const current = yield* getStartedState;+ const meta = sessionSetupResult._meta;+ const syntheticReplayIdle =+ meta !== null &&+ typeof meta === "object" &&+ !Array.isArray(meta) &&+ (meta as { readonly t3SessionLoadReady?: unknown }).t3SessionLoadReady === "replay_idle";+ const extractedModelConfigId = extractModelConfigId(sessionSetupResult);+ const nextModelConfigId =+ extractedModelConfigId ?? (syntheticReplayIdle ? current.modelConfigId : undefined);+ const nextModeState = parseSessionModeState(sessionSetupResult);+ if (nextModeState !== undefined) {+ yield* Ref.set(modeStateRef, nextModeState);+ } else if (!syntheticReplayIdle) {+ yield* Ref.set(modeStateRef, undefined);+ }+ // Synthetic replay-idle load responses only carry initialize model/mode+ // meta; preserve live configOptions so setConfigOption still validates.+ if (+ sessionSetupResult.configOptions !== undefined &&+ sessionSetupResult.configOptions !== null+ ) {+ yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));+ } else if (!syntheticReplayIdle) {+ yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));+ }+ const nextState = {+ sessionId,+ initializeResult: current.initializeResult,+ sessionSetupResult,+ modelConfigId: nextModelConfigId,+ } satisfies AcpStartedState;+ yield* Ref.set(toolCallsRef, new Map());+ yield* Ref.set(assistantSegmentRef, { nextSegmentIndex: 0 });+ yield* Ref.set(startStateRef, { _tag: "Started", result: nextState });+ return nextState;+ });- const runLoadSessionWithReplayIdle = (- loadPayload: EffectAcpSchema.LoadSessionRequest,- initializeResult: EffectAcpSchema.InitializeResponse,- ): Effect.Effect<EffectAcpSchema.LoadSessionResponse, EffectAcpErrors.AcpError> =>- sessionLoadSemaphore.withPermits(1)(- Effect.gen(function* () {- const sessionLoadTimeout = Duration.fromInputUnsafe(- options.sessionLoadTimeout ?? defaultSessionLoadTimeout,- );- const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(- options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,- );+ const runLoadSessionWithReplayIdle = (+ loadPayload: EffectAcpSchema.LoadSessionRequest,+ initializeResult: EffectAcpSchema.InitializeResponse,+ ): Effect.Effect<EffectAcpSchema.LoadSessionResponse, EffectAcpErrors.AcpError> =>+ sessionLoadSemaphore.withPermits(1)(+ Effect.gen(function* () {+ const sessionLoadTimeout = Duration.fromInputUnsafe(+ options.sessionLoadTimeout ?? defaultSessionLoadTimeout,+ );+ const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(+ options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,+ );- yield* Ref.set(- sessionLoadGateRef,- Option.some({- active: true,- sessionId: loadPayload.sessionId,- lastActivityAtMillis: undefined,- idleGap: sessionLoadReplayIdleGap,- initializeResult,- }),- );+ yield* Ref.set(+ sessionLoadGateRef,+ Option.some({+ active: true,+ sessionId: loadPayload.sessionId,+ lastActivityAtMillis: undefined,+ idleGap: sessionLoadReplayIdleGap,+ initializeResult,+ }),+ );- return yield* Effect.gen(function* () {- yield* logRequest({- method: "session/load",- payload: loadPayload,- status: "started",- });+ return yield* Effect.gen(function* () {+ yield* logRequest({+ method: "session/load",+ payload: loadPayload,+ status: "started",+ });- const idleFiber = yield* waitForSessionLoadReplayIdle({- gateRef: sessionLoadGateRef,- }).pipe(Effect.forkIn(runtimeScope));- const loaded = yield* Effect.raceFirst(- acp.agent.loadSession(loadPayload),- Fiber.join(idleFiber),- ).pipe(- Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),- Effect.timeoutOption(sessionLoadTimeout),- Effect.flatMap((result) =>- Option.match(result, {- onNone: () =>- Effect.fail(- new EffectAcpErrors.AcpTransportError({- operation: "call-rpc",- method: "session/load",- detail:- "session/load timed out waiting for RPC response or replay idle gap",- cause: undefined,- }),- ),- onSome: Effect.succeed,- }),- ),- Effect.tap((result) =>- logRequest({- method: "session/load",- payload: loadPayload,- status: "succeeded",- result,- }),- ),- Effect.onError((cause) =>- logRequest({- method: "session/load",- payload: loadPayload,- status: "failed",- cause,- }),- ),- );+ const idleFiber = yield* waitForSessionLoadReplayIdle({+ gateRef: sessionLoadGateRef,+ }).pipe(Effect.forkIn(runtimeScope));+ const loaded = yield* Effect.raceFirst(+ acp.agent.loadSession(loadPayload),+ Fiber.join(idleFiber),+ ).pipe(+ Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),+ Effect.timeoutOption(sessionLoadTimeout),+ Effect.flatMap((result) =>+ Option.match(result, {+ onNone: () =>+ Effect.fail(+ new EffectAcpErrors.AcpTransportError({+ operation: "call-rpc",+ method: "session/load",+ detail: "session/load timed out waiting for RPC response or replay idle gap",+ cause: undefined,+ }),+ ),+ onSome: Effect.succeed,+ }),+ ),+ Effect.tap((result) =>+ logRequest({+ method: "session/load",+ payload: loadPayload,+ status: "succeeded",+ result,+ }),+ ),+ Effect.onError((cause) =>+ logRequest({+ method: "session/load",+ payload: loadPayload,+ status: "failed",+ cause,+ }),+ ),+ );- const gate = yield* Ref.get(sessionLoadGateRef);- const candidateConfigOptions = Option.isSome(gate)- ? gate.value.candidateConfigOptions- : undefined;- return loaded.configOptions == null && candidateConfigOptions !== undefined- ? { ...loaded, configOptions: candidateConfigOptions }- : loaded;- }).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));- }),- );+ const gate = yield* Ref.get(sessionLoadGateRef);+ const candidateConfigOptions = Option.isSome(gate)+ ? gate.value.candidateConfigOptions+ : undefined;+ return loaded.configOptions == null && candidateConfigOptions !== undefined+ ? { ...loaded, configOptions: candidateConfigOptions }+ : loaded;+ }).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));+ }),+ );- const setConfigOption = (- configId: string,- value: string | boolean,- ): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>- validateConfigOptionValue(configId, value).pipe(- Effect.flatMap(() => getStartedState),- Effect.flatMap((started) =>- Ref.get(configOptionsRef).pipe(- Effect.flatMap((configOptions) => {- const existing = findSessionConfigOption(configOptions, configId);- if (existing && configOptionCurrentValueMatches(existing, value)) {- return Effect.succeed({- configOptions,- } satisfies EffectAcpSchema.SetSessionConfigOptionResponse);- }- const requestPayload =- typeof value === "boolean"- ? ({- sessionId: started.sessionId,- configId,- type: "boolean",- value,- } satisfies EffectAcpSchema.SetSessionConfigOptionRequest)- : ({- sessionId: started.sessionId,- configId,- value: String(value),- } satisfies EffectAcpSchema.SetSessionConfigOptionRequest);- return runLoggedRequest(- "session/set_config_option",- requestPayload,- acp.agent.setSessionConfigOption(requestPayload),- ).pipe(Effect.tap((response) => updateConfigOptions(response)));- }),- ),+ const setConfigOption = (+ configId: string,+ value: string | boolean,+ ): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>+ validateConfigOptionValue(configId, value).pipe(+ Effect.flatMap(() => getStartedState),+ Effect.flatMap((started) =>+ Ref.get(configOptionsRef).pipe(+ Effect.flatMap((configOptions) => {+ const existing = findSessionConfigOption(configOptions, configId);+ if (existing && configOptionCurrentValueMatches(existing, value)) {+ return Effect.succeed({+ configOptions,+ } satisfies EffectAcpSchema.SetSessionConfigOptionResponse);+ }+ const requestPayload =+ typeof value === "boolean"+ ? ({+ sessionId: started.sessionId,+ configId,+ type: "boolean",+ value,+ } satisfies EffectAcpSchema.SetSessionConfigOptionRequest)+ : ({+ sessionId: started.sessionId,+ configId,+ value: String(value),+ } satisfies EffectAcpSchema.SetSessionConfigOptionRequest);+ return runLoggedRequest(+ "session/set_config_option",+ requestPayload,+ acp.agent.setSessionConfigOption(requestPayload),+ ).pipe(Effect.tap((response) => updateConfigOptions(response)));+ }),),- );+ ),+ );- const initializeOnce = Effect.gen(function* () {- const initializePayload = {- protocolVersion: 2,- clientCapabilities: initializeClientCapabilities,- clientInfo: options.clientInfo,- ...(options.initializeMeta === undefined ? {} : { _meta: options.initializeMeta }),- } satisfies EffectAcpSchema.InitializeRequest;-- const initializeResult = yield* runLoggedRequest(- "initialize",- initializePayload,- acp.agent.initialize(initializePayload),- );- yield* options.onInitialized?.(initializeResult) ?? Effect.void;- return initializeResult;- });+ const initializeOnce = Effect.gen(function* () {+ const initializePayload = {+ protocolVersion: 2,+ clientCapabilities: initializeClientCapabilities,+ clientInfo: options.clientInfo,+ ...(options.initializeMeta === undefined ? {} : { _meta: options.initializeMeta }),+ } satisfies EffectAcpSchema.InitializeRequest;++ const initializeResult = yield* runLoggedRequest(+ "initialize",+ initializePayload,+ acp.agent.initialize(initializePayload),+ );+ yield* options.onInitialized?.(initializeResult) ?? Effect.void;+ return initializeResult;+ });- const initialize = Effect.gen(function* () {- yield* ensureConnected;- const deferred = yield* Deferred.make<- EffectAcpSchema.InitializeResponse,- EffectAcpErrors.AcpError- >();- const effect = yield* Ref.modify(initializeStateRef, (state) => {- switch (state._tag) {- case "Started":- return [Effect.succeed(state.result), state] as const;- case "Starting":- return [Deferred.await(state.deferred), state] as const;- case "NotStarted":- return [- initializeOnce.pipe(- Effect.tap((result) =>- Ref.set(initializeStateRef, { _tag: "Started", result }).pipe(- Effect.andThen(Deferred.succeed(deferred, result)),- ),+ const initialize = Effect.gen(function* () {+ yield* ensureConnected;+ const deferred = yield* Deferred.make<+ EffectAcpSchema.InitializeResponse,+ EffectAcpErrors.AcpError+ >();+ const effect = yield* Ref.modify(initializeStateRef, (state) => {+ switch (state._tag) {+ case "Started":+ return [Effect.succeed(state.result), state] as const;+ case "Starting":+ return [Deferred.await(state.deferred), state] as const;+ case "NotStarted":+ return [+ initializeOnce.pipe(+ Effect.tap((result) =>+ Ref.set(initializeStateRef, { _tag: "Started", result }).pipe(+ Effect.andThen(Deferred.succeed(deferred, result)),),- Effect.onError((cause) =>- Deferred.failCause(deferred, cause).pipe(- Effect.andThen(Ref.set(initializeStateRef, { _tag: "NotStarted" })),- ),+ ),+ Effect.onError((cause) =>+ Deferred.failCause(deferred, cause).pipe(+ Effect.andThen(Ref.set(initializeStateRef, { _tag: "NotStarted" })),),),- { _tag: "Starting", deferred } satisfies AcpInitializeState,- ] as const;- }- });- return yield* effect;+ ),+ { _tag: "Starting", deferred } satisfies AcpInitializeState,+ ] as const;+ }});+ return yield* effect;+ });- const sessionMcpServers = (- initializeResult: EffectAcpSchema.InitializeResponse,- activationOptions?: AcpSessionActivationOptions,- ): ReadonlyArray<EffectAcpSchema.McpServer> => {- const acpServers = activationOptions?.acpMcpServers ?? options.acpMcpServers ?? [];- if (- initializeResult.agentCapabilities?.mcpCapabilities?.acp === true &&- acpServers.length > 0- ) {- return acpServers;- }- return activationOptions?.mcpServers ?? options.mcpServers ?? [];- };+ const sessionMcpServers = (+ initializeResult: EffectAcpSchema.InitializeResponse,+ activationOptions?: AcpSessionActivationOptions,+ ): ReadonlyArray<EffectAcpSchema.McpServer> => {+ const acpServers = activationOptions?.acpMcpServers ?? options.acpMcpServers ?? [];+ if (+ initializeResult.agentCapabilities?.mcpCapabilities?.acp === true &&+ acpServers.length > 0+ ) {+ return acpServers;+ }+ return activationOptions?.mcpServers ?? options.mcpServers ?? [];+ };- const startOnce = Effect.gen(function* () {- const initializeResult = yield* initialize;+ const startOnce = Effect.gen(function* () {+ const initializeResult = yield* initialize;- const authenticateAfterRequired = (+ const authenticateAfterRequired = Effect.fn("AcpSessionRuntime.authenticateAfterRequired")(+ function* (authRequiredError: EffectAcpErrors.AcpError,- ): Effect.Effect<void, EffectAcpErrors.AcpError> =>- Effect.gen(function* () {- const configuredAuthMethodId = options.authMethodId?.trim();- const authMethod = selectAcpAgentAuthMethod(- initializeResult.authMethods,- configuredAuthMethodId,- );- if (- configuredAuthMethodId &&- initializeResult.authMethods !== undefined &&- authMethod === undefined- ) {- return yield* new EffectAcpErrors.AcpTransportError({- detail: `ACP agent did not advertise configured authentication method "${configuredAuthMethodId}"`,- cause: { configuredAuthMethodId, authMethods: initializeResult.authMethods },- });- }- if (- authMethod !== undefined &&- authMethod.type !== undefined &&- authMethod.type !== "agent"- ) {- return yield* new EffectAcpErrors.AcpTransportError({- detail: `ACP authentication method "${authMethod.id}" requires ${authMethod.type} authentication, which cannot run inside a headless provider session`,- cause: authMethod,- });- }-- const authMethodId = authMethod?.id ?? configuredAuthMethodId;- if (!authMethodId) {- return yield* authRequiredError;- }-- const authenticatePayload = {- methodId: authMethodId,- } satisfies EffectAcpSchema.AuthenticateRequest;- yield* runLoggedRequest(- "authenticate",- authenticatePayload,- acp.agent.authenticate(authenticatePayload),- );- });-- const setupSession = Effect.gen(function* () {- let sessionId: string;- let sessionSetupResult:- | EffectAcpSchema.LoadSessionResponse- | EffectAcpSchema.NewSessionResponse- | EffectAcpSchema.ResumeSessionResponse;- const additionalDirectories = options.additionalDirectories?.length- ? { additionalDirectories: options.additionalDirectories }- : {};- if (options.resumeSessionId) {- sessionId = options.resumeSessionId;- if (- initializeResult.agentCapabilities?.loadSession === true &&- options.resumeMethod !== "resume"- ) {- const loadPayload = {- sessionId,- cwd: options.cwd,- ...additionalDirectories,- mcpServers: sessionMcpServers(initializeResult),- } satisfies EffectAcpSchema.LoadSessionRequest;- sessionSetupResult = yield* runLoadSessionWithReplayIdle(loadPayload, initializeResult);- } else if (initializeResult.agentCapabilities?.sessionCapabilities?.resume != null) {- const resumePayload = {- sessionId,- cwd: options.cwd,- ...additionalDirectories,- mcpServers: sessionMcpServers(initializeResult),- } satisfies EffectAcpSchema.ResumeSessionRequest;- sessionSetupResult = yield* runLoggedRequest(- "session/resume",- resumePayload,- acp.agent.resumeSession(resumePayload),- );- } else {- return yield* new EffectAcpErrors.AcpRequestError({- code: -32601,- errorMessage: "ACP agent does not advertise session/load or session/resume support",- });- }- } else {- const createPayload = {- cwd: options.cwd,- mcpServers: sessionMcpServers(initializeResult),- ...additionalDirectories,- } satisfies EffectAcpSchema.NewSessionRequest;- const created = yield* runLoggedRequest(- "session/new",- createPayload,- acp.agent.createSession(createPayload),- );- sessionId = created.sessionId;- sessionSetupResult = created;+ ): Effect.fn.Return<void, EffectAcpErrors.AcpError> {+ const configuredAuthMethodId = options.authMethodId?.trim();+ const authMethod = selectAcpAgentAuthMethod(+ initializeResult.authMethods,+ configuredAuthMethodId,+ );+ if (+ configuredAuthMethodId &&+ initializeResult.authMethods !== undefined &&+ authMethod === undefined+ ) {+ return yield* new EffectAcpErrors.AcpTransportError({+ detail: `ACP agent did not advertise configured authentication method "${configuredAuthMethodId}"`,+ cause: { configuredAuthMethodId, authMethods: initializeResult.authMethods },+ });+ }+ if (+ authMethod !== undefined &&+ authMethod.type !== undefined &&+ authMethod.type !== "agent"+ ) {+ return yield* new EffectAcpErrors.AcpTransportError({+ detail: `ACP authentication method "${authMethod.id}" requires ${authMethod.type} authentication, which cannot run inside a headless provider session`,+ cause: authMethod,+ });}- return { sessionId, sessionSetupResult };- });+ const authMethodId = authMethod?.id ?? configuredAuthMethodId;+ if (!authMethodId) {+ return yield* authRequiredError;+ }- if (options.authenticateEagerly === true) {- // The configured method is authoritative here: Antigravity accepts- // methods (API key, Vertex) it does not list in `initialize`.const authenticatePayload = {- methodId: options.authMethodId ?? "",+ methodId: authMethodId,} satisfies EffectAcpSchema.AuthenticateRequest;yield* runLoggedRequest("authenticate",authenticatePayload,acp.agent.authenticate(authenticatePayload),);+ },+ );++ const setupSession = Effect.gen(function* () {+ let sessionId: string;+ let sessionSetupResult:+ | EffectAcpSchema.LoadSessionResponse+ | EffectAcpSchema.NewSessionResponse+ | EffectAcpSchema.ResumeSessionResponse;+ const additionalDirectories = options.additionalDirectories?.length+ ? { additionalDirectories: options.additionalDirectories }+ : {};+ if (options.resumeSessionId) {+ sessionId = options.resumeSessionId;+ if (+ initializeResult.agentCapabilities?.loadSession === true &&+ options.resumeMethod !== "resume"+ ) {+ const loadPayload = {+ sessionId,+ cwd: options.cwd,+ ...additionalDirectories,+ mcpServers: sessionMcpServers(initializeResult),+ } satisfies EffectAcpSchema.LoadSessionRequest;+ sessionSetupResult = yield* runLoadSessionWithReplayIdle(loadPayload, initializeResult);+ } else if (initializeResult.agentCapabilities?.sessionCapabilities?.resume != null) {+ const resumePayload = {+ sessionId,+ cwd: options.cwd,+ ...additionalDirectories,+ mcpServers: sessionMcpServers(initializeResult),+ } satisfies EffectAcpSchema.ResumeSessionRequest;+ sessionSetupResult = yield* runLoggedRequest(+ "session/resume",+ resumePayload,+ acp.agent.resumeSession(resumePayload),+ );+ } else {+ return yield* new EffectAcpErrors.AcpRequestError({+ code: -32601,+ errorMessage: "ACP agent does not advertise session/load or session/resume support",+ });+ }+ } else {+ const createPayload = {+ cwd: options.cwd,+ mcpServers: sessionMcpServers(initializeResult),+ ...additionalDirectories,+ } satisfies EffectAcpSchema.NewSessionRequest;+ const created = yield* runLoggedRequest(+ "session/new",+ createPayload,+ acp.agent.createSession(createPayload),+ );+ sessionId = created.sessionId;+ sessionSetupResult = created;}- const { sessionId, sessionSetupResult } = yield* setupSession.pipe(- Effect.catch((error) =>- !isAcpAuthenticationRequired(error) || options.authenticateOnAuthRequired === false- ? Effect.fail(error)- : authenticateAfterRequired(error).pipe(Effect.andThen(setupSession)),- ),++ return { sessionId, sessionSetupResult };+ });++ if (options.authenticateEagerly === true) {+ // The configured method is authoritative here: Antigravity accepts+ // methods (API key, Vertex) it does not list in `initialize`.+ const authenticatePayload = {+ methodId: options.authMethodId ?? "",+ } satisfies EffectAcpSchema.AuthenticateRequest;+ yield* runLoggedRequest(+ "authenticate",+ authenticatePayload,+ acp.agent.authenticate(authenticatePayload),);+ }+ const { sessionId, sessionSetupResult } = yield* setupSession.pipe(+ Effect.catch((error) =>+ !isAcpAuthenticationRequired(error) || options.authenticateOnAuthRequired === false+ ? Effect.fail(error)+ : authenticateAfterRequired(error).pipe(Effect.andThen(setupSession)),+ ),+ );- yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));- yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));+ yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));+ yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));- const nextState = {- sessionId,- initializeResult,- sessionSetupResult,- modelConfigId: extractModelConfigId(sessionSetupResult),- } satisfies AcpStartedState;- return nextState;- });+ const nextState = {+ sessionId,+ initializeResult,+ sessionSetupResult,+ modelConfigId: extractModelConfigId(sessionSetupResult),+ } satisfies AcpStartedState;+ return nextState;+ });- const start = Effect.gen(function* () {- yield* ensureConnected;- const deferred = yield* Deferred.make<- AcpSessionRuntimeStartResult,- EffectAcpErrors.AcpError- >();- const effect = yield* Ref.modify(startStateRef, (state) => {- switch (state._tag) {- case "Started":- return [Effect.succeed(state.result), state] as const;- case "Starting":- return [Deferred.await(state.deferred), state] as const;- case "NotStarted":- return [- startOnce.pipe(- Effect.tap((result) =>- notificationSemaphore.withPermit(- Effect.gen(function* () {- const error = yield* Ref.get(terminationErrorRef);- if (Option.isSome(error)) {- return yield* error.value;- }- yield* Ref.set(startStateRef, { _tag: "Started", result });- const metadata = yield* Ref.getAndSet(startupMetadataRef, []);- for (const notification of metadata) {- if (notification.sessionId === result.sessionId) {- yield* processSessionUpdate(notification);- }+ const start = Effect.gen(function* () {+ yield* ensureConnected;+ const deferred = yield* Deferred.make<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>();+ const effect = yield* Ref.modify(startStateRef, (state) => {+ switch (state._tag) {+ case "Started":+ return [Effect.succeed(state.result), state] as const;+ case "Starting":+ return [Deferred.await(state.deferred), state] as const;+ case "NotStarted":+ return [+ startOnce.pipe(+ Effect.tap((result) =>+ notificationSemaphore.withPermit(+ Effect.gen(function* () {+ const error = yield* Ref.get(terminationErrorRef);+ if (Option.isSome(error)) {+ return yield* error.value;+ }+ yield* Ref.set(startStateRef, { _tag: "Started", result });+ const metadata = yield* Ref.getAndSet(startupMetadataRef, []);+ for (const notification of metadata) {+ if (notification.sessionId === result.sessionId) {+ yield* processSessionUpdate(notification);}- yield* Deferred.succeed(deferred, result);- }),- ),+ }+ yield* Deferred.succeed(deferred, result);+ }),),- Effect.onError((cause) =>- Deferred.failCause(deferred, cause).pipe(- Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),- Effect.andThen(Ref.set(startupMetadataRef, [])),- ),+ ),+ Effect.onError((cause) =>+ Deferred.failCause(deferred, cause).pipe(+ Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),+ Effect.andThen(Ref.set(startupMetadataRef, [])),),),- { _tag: "Starting", deferred } satisfies AcpStartState,- ] as const;- }- });- return yield* effect;- });-- const drainEvents = Effect.gen(function* () {- if (yield* Ref.get(stoppingRef)) {- return;+ ),+ { _tag: "Starting", deferred } satisfies AcpStartState,+ ] as const;}- const acknowledge = yield* Deferred.make<void>();- yield* notificationSemaphore.withPermit(- Effect.gen(function* () {- if (Option.isNone(yield* Ref.get(activePromptRef))) {- yield* Ref.set(assistantUpdatesOpenRef, false);- yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });- }- yield* Queue.offer(eventQueue, { _tag: "EventStreamBarrier", acknowledge });- }),- );- yield* Effect.raceFirst(Deferred.await(acknowledge), Deferred.await(runtimeClosed));- });-- const retireRuntime = Effect.fn("AcpSessionRuntime.retireRuntime")(function* (- error: EffectAcpErrors.AcpError,- ) {- yield* recordTermination(error);- yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);});+ return yield* effect;+ });- const cancel = Effect.gen(function* () {- const started = yield* getStartedState;- const activePrompt = yield* Ref.get(activePromptRef);- const cancelPayload = {- sessionId: started.sessionId,- ...(options.cancelMeta === undefined ? {} : { _meta: options.cancelMeta }),- } satisfies EffectAcpSchema.CancelNotification;- if (options.cancelBehavior !== "wait-for-prompt") {- if (options.interruptPromptOnCancel === false) {- return yield* acp.agent.cancel(cancelPayload);- }- if (Option.isSome(activePrompt)) {- yield* Fiber.interrupt(activePrompt.value.fiber).pipe(Effect.ignore);+ const drainEvents = Effect.gen(function* () {+ if (yield* Ref.get(stoppingRef)) {+ return;+ }+ const acknowledge = yield* Deferred.make<void>();+ yield* notificationSemaphore.withPermit(+ Effect.gen(function* () {+ if (Option.isNone(yield* Ref.get(activePromptRef))) {+ yield* Ref.set(assistantUpdatesOpenRef, false);+ yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });}- // Write cancel before a replacement prompt can reach the agent.- yield* acp.agent.cancel(cancelPayload).pipe(Effect.ignore);- return;- }+ yield* Queue.offer(eventQueue, { _tag: "EventStreamBarrier", acknowledge });+ }),+ );+ yield* Effect.raceFirst(Deferred.await(acknowledge), Deferred.await(runtimeClosed));+ });- yield* acp.agent.cancel(cancelPayload);- if (Option.isNone(activePrompt)) {- return;+ const retireRuntime = Effect.fn("AcpSessionRuntime.retireRuntime")(function* (+ error: EffectAcpErrors.AcpError,+ ) {+ yield* recordTermination(error);+ yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);+ });++ const cancel = Effect.gen(function* () {+ const started = yield* getStartedState;+ const activePrompt = yield* Ref.get(activePromptRef);+ const cancelPayload = {+ sessionId: started.sessionId,+ ...(options.cancelMeta === undefined ? {} : { _meta: options.cancelMeta }),+ } satisfies EffectAcpSchema.CancelNotification;+ if (options.cancelBehavior !== "wait-for-prompt") {+ if (options.interruptPromptOnCancel === false) {+ return yield* acp.agent.cancel(cancelPayload);}- const completed = yield* Effect.gen(function* () {- const result = yield* Fiber.await(activePrompt.value.fiber);- yield* Deferred.await(activePrompt.value.completed);- if (Option.isNone(yield* Ref.get(terminationErrorRef))) {- yield* drainEvents;- }- return result;- }).pipe(Effect.timeoutOption(options.cancelTimeout ?? defaultCancelTimeout));- if (Option.isNone(completed)) {- const error = new EffectAcpErrors.AcpTransportError({- operation: "call-rpc",- method: "session/cancel",- detail: "The ACP agent did not finish cancellation. Its process was stopped.",- cause: undefined,- });- yield* retireRuntime(error);- return yield* error;+ if (Option.isSome(activePrompt)) {+ yield* Fiber.interrupt(activePrompt.value.fiber).pipe(Effect.ignore);}- if (Exit.isFailure(completed.value)) {- return yield* Effect.failCause(completed.value.cause);+ // Write cancel before a replacement prompt can reach the agent.+ yield* acp.agent.cancel(cancelPayload).pipe(Effect.ignore);+ return;+ }++ yield* acp.agent.cancel(cancelPayload);+ if (Option.isNone(activePrompt)) {+ return;+ }+ const completed = yield* Effect.gen(function* () {+ const result = yield* Fiber.await(activePrompt.value.fiber);+ yield* Deferred.await(activePrompt.value.completed);+ if (Option.isNone(yield* Ref.get(terminationErrorRef))) {+ yield* drainEvents;}- });+ return result;+ }).pipe(Effect.timeoutOption(options.cancelTimeout ?? defaultCancelTimeout));+ if (Option.isNone(completed)) {+ const error = new EffectAcpErrors.AcpTransportError({+ operation: "call-rpc",+ method: "session/cancel",+ detail: "The ACP agent did not finish cancellation. Its process was stopped.",+ cause: undefined,+ });+ yield* retireRuntime(error);+ return yield* error;+ }+ if (Exit.isFailure(completed.value)) {+ return yield* Effect.failCause(completed.value.cause);+ }+ });- return {- processContainment:- linuxCgroupLease !== undefined- ? "cgroup-v2"- : options.ownDescendantProcessGroups === true- ? "process-ledger-reduced-guarantee"- : options.ownDetachedProcessGroup === true- ? "process-group"- : "none",- handleRequestPermission: acp.handleRequestPermission,- handleElicitation: acp.handleElicitation,- handleMcpConnect: acp.handleMcpConnect,- handleMcpMessage: acp.handleMcpMessage,- handleMcpDisconnect: acp.handleMcpDisconnect,- handleMcpNotification: acp.handleMcpNotification,- handleReadTextFile: acp.handleReadTextFile,- handleWriteTextFile: acp.handleWriteTextFile,- handleCreateTerminal: acp.handleCreateTerminal,- handleTerminalOutput: acp.handleTerminalOutput,- handleTerminalWaitForExit: acp.handleTerminalWaitForExit,- handleTerminalKill: acp.handleTerminalKill,- handleTerminalRelease: acp.handleTerminalRelease,- handleSessionUpdate: acp.handleSessionUpdate,- handleElicitationComplete: acp.handleElicitationComplete,- handleUnknownExtRequest: acp.handleUnknownExtRequest,- handleUnknownExtNotification: acp.handleUnknownExtNotification,- handleExtRequest: acp.handleExtRequest,- handleExtNotification: acp.handleExtNotification,- initialize: () => initialize,- authenticate: (methodId) =>- initialize.pipe(- Effect.andThen(- runLoggedRequest("authenticate", { methodId }, acp.agent.authenticate({ methodId })),- ),- Effect.asVoid,- ),- start: () => start,- getEvents: () => Stream.fromQueue(eventQueue),- drainEvents,- getModeState: Ref.get(modeStateRef),- getConfigOptions: Ref.get(configOptionsRef),- loadSession: (sessionId, activationOptions) =>- start.pipe(- Effect.flatMap((started) => {- const requestPayload = {- sessionId,- cwd: options.cwd,- mcpServers: sessionMcpServers(started.initializeResult, activationOptions),- } satisfies EffectAcpSchema.LoadSessionRequest;- return runLoadSessionWithReplayIdle(requestPayload, started.initializeResult);- }),- Effect.flatMap((response) => adoptSession(sessionId, response)),+ return {+ processContainment:+ linuxCgroupLease !== undefined+ ? "cgroup-v2"+ : options.ownDescendantProcessGroups === true+ ? "process-ledger-reduced-guarantee"+ : options.ownDetachedProcessGroup === true+ ? "process-group"+ : "none",+ handleRequestPermission: acp.handleRequestPermission,+ handleElicitation: acp.handleElicitation,+ handleMcpConnect: acp.handleMcpConnect,+ handleMcpMessage: acp.handleMcpMessage,+ handleMcpDisconnect: acp.handleMcpDisconnect,+ handleMcpNotification: acp.handleMcpNotification,+ handleReadTextFile: acp.handleReadTextFile,+ handleWriteTextFile: acp.handleWriteTextFile,+ handleCreateTerminal: acp.handleCreateTerminal,+ handleTerminalOutput: acp.handleTerminalOutput,+ handleTerminalWaitForExit: acp.handleTerminalWaitForExit,+ handleTerminalKill: acp.handleTerminalKill,+ handleTerminalRelease: acp.handleTerminalRelease,+ handleSessionUpdate: acp.handleSessionUpdate,+ handleElicitationComplete: acp.handleElicitationComplete,+ handleUnknownExtRequest: acp.handleUnknownExtRequest,+ handleUnknownExtNotification: acp.handleUnknownExtNotification,+ handleExtRequest: acp.handleExtRequest,+ handleExtNotification: acp.handleExtNotification,+ initialize: () => initialize,+ authenticate: (methodId) =>+ initialize.pipe(+ Effect.andThen(+ runLoggedRequest("authenticate", { methodId }, acp.agent.authenticate({ methodId })),),- resumeSession: (sessionId, activationOptions) =>- start.pipe(- Effect.flatMap((started) => {- const requestPayload = {- sessionId,- cwd: options.cwd,- mcpServers: sessionMcpServers(started.initializeResult, activationOptions),- } satisfies EffectAcpSchema.ResumeSessionRequest;- return runLoggedRequest(- "session/resume",- requestPayload,- acp.agent.resumeSession(requestPayload),- );- }),- Effect.flatMap((response) => adoptSession(sessionId, response)),+ Effect.asVoid,+ ),+ start: () => start,+ getEvents: () => Stream.fromQueue(eventQueue),+ drainEvents,+ getModeState: Ref.get(modeStateRef),+ getConfigOptions: Ref.get(configOptionsRef),+ loadSession: (sessionId, activationOptions) =>+ start.pipe(+ Effect.flatMap((started) => {+ const requestPayload = {+ sessionId,+ cwd: options.cwd,+ mcpServers: sessionMcpServers(started.initializeResult, activationOptions),+ } satisfies EffectAcpSchema.LoadSessionRequest;+ return runLoadSessionWithReplayIdle(requestPayload, started.initializeResult);+ }),+ Effect.flatMap((response) => adoptSession(sessionId, response)),+ ),+ resumeSession: (sessionId, activationOptions) =>+ start.pipe(+ Effect.flatMap((started) => {+ const requestPayload = {+ sessionId,+ cwd: options.cwd,+ mcpServers: sessionMcpServers(started.initializeResult, activationOptions),+ } satisfies EffectAcpSchema.ResumeSessionRequest;+ return runLoggedRequest(+ "session/resume",+ requestPayload,+ acp.agent.resumeSession(requestPayload),+ );+ }),+ Effect.flatMap((response) => adoptSession(sessionId, response)),+ ),+ forkSession: (sessionId, activationOptions) =>+ start.pipe(+ Effect.flatMap((started) => {+ const requestPayload = {+ sessionId,+ cwd: options.cwd,+ mcpServers: sessionMcpServers(started.initializeResult, activationOptions),+ } satisfies EffectAcpSchema.ForkSessionRequest;+ return runLoggedRequest(+ "session/fork",+ requestPayload,+ acp.agent.forkSession(requestPayload),+ );+ }),+ Effect.flatMap((response) => adoptSession(response.sessionId, response)),+ ),+ listSessions: (cursor) => {+ const requestPayload = {+ cwd: options.cwd,+ ...(cursor === undefined ? {} : { cursor }),+ } satisfies EffectAcpSchema.ListSessionsRequest;+ return initialize.pipe(+ Effect.filterOrFail(+ (initialized) => initialized.agentCapabilities?.sessionCapabilities?.list != null,+ () =>+ new EffectAcpErrors.AcpRequestError({+ code: -32601,+ errorMessage: "ACP agent does not advertise session/list support",+ }),),- forkSession: (sessionId, activationOptions) =>- start.pipe(- Effect.flatMap((started) => {- const requestPayload = {- sessionId,- cwd: options.cwd,- mcpServers: sessionMcpServers(started.initializeResult, activationOptions),- } satisfies EffectAcpSchema.ForkSessionRequest;- return runLoggedRequest(- "session/fork",- requestPayload,- acp.agent.forkSession(requestPayload),- );- }),- Effect.flatMap((response) => adoptSession(response.sessionId, response)),+ Effect.andThen(+ runLoggedRequest("session/list", requestPayload, acp.agent.listSessions(requestPayload)),),- listSessions: (cursor) => {- const requestPayload = {- cwd: options.cwd,- ...(cursor === undefined ? {} : { cursor }),- } satisfies EffectAcpSchema.ListSessionsRequest;- return initialize.pipe(- Effect.filterOrFail(- (initialized) => initialized.agentCapabilities?.sessionCapabilities?.list != null,- () =>- new EffectAcpErrors.AcpRequestError({- code: -32601,- errorMessage: "ACP agent does not advertise session/list support",- }),- ),- Effect.andThen(- runLoggedRequest(- "session/list",- requestPayload,- acp.agent.listSessions(requestPayload),- ),- ),- );- },- closeSession: (sessionId) =>- start.pipe(- Effect.flatMap((started) => {- const requestPayload = {- sessionId: sessionId ?? started.sessionId,- } satisfies EffectAcpSchema.CloseSessionRequest;- return runLoggedRequest(- "session/close",- requestPayload,- acp.agent.closeSession(requestPayload),- );- }),+ );+ },+ closeSession: (sessionId) =>+ start.pipe(+ Effect.flatMap((started) => {+ const requestPayload = {+ sessionId: sessionId ?? started.sessionId,+ } satisfies EffectAcpSchema.CloseSessionRequest;+ return runLoggedRequest(+ "session/close",+ requestPayload,+ acp.agent.closeSession(requestPayload),+ );+ }),+ ),+ deleteSession: (sessionId) =>+ initialize.pipe(+ Effect.filterOrFail(+ (initialized) => initialized.agentCapabilities?.sessionCapabilities?.delete != null,+ () =>+ new EffectAcpErrors.AcpRequestError({+ code: -32601,+ errorMessage: "ACP agent does not advertise session/delete support",+ }),),- deleteSession: (sessionId) =>- initialize.pipe(- Effect.filterOrFail(- (initialized) => initialized.agentCapabilities?.sessionCapabilities?.delete != null,- () =>- new EffectAcpErrors.AcpRequestError({- code: -32601,- errorMessage: "ACP agent does not advertise session/delete support",- }),- ),- Effect.andThen(- runLoggedRequest(- "session/delete",- { sessionId },- acp.agent.deleteSession({ sessionId }),- ),- ),+ Effect.andThen(+ runLoggedRequest("session/delete", { sessionId }, acp.agent.deleteSession({ sessionId })),),- listProviders: initialize.pipe(+ ),+ listProviders: initialize.pipe(+ Effect.filterOrFail(+ (initialized) => initialized.agentCapabilities?.providers != null,+ () =>+ new EffectAcpErrors.AcpRequestError({+ code: -32601,+ errorMessage: "ACP agent does not advertise provider configuration support",+ }),+ ),+ Effect.andThen(runLoggedRequest("providers/list", {}, acp.agent.listProviders({}))),+ ),+ setProvider: (provider) =>+ initialize.pipe(Effect.filterOrFail((initialized) => initialized.agentCapabilities?.providers != null,() =>@@ -2528,185 +2522,168 @@ export const make = (errorMessage: "ACP agent does not advertise provider configuration support",}),),- Effect.andThen(runLoggedRequest("providers/list", {}, acp.agent.listProviders({}))),- ),- setProvider: (provider) =>- initialize.pipe(- Effect.filterOrFail(- (initialized) => initialized.agentCapabilities?.providers != null,- () =>- new EffectAcpErrors.AcpRequestError({- code: -32601,- errorMessage: "ACP agent does not advertise provider configuration support",- }),- ),- Effect.andThen(- runLoggedRequest(- "providers/set",- {- ...provider,- ...(provider.headers === undefined- ? {}- : {- headers: Object.fromEntries(- Object.keys(provider.headers).map((name) => [name, "[redacted]"]),- ),- }),- },- acp.agent.setProvider(provider),- ),+ Effect.andThen(+ runLoggedRequest(+ "providers/set",+ {+ ...provider,+ ...(provider.headers === undefined+ ? {}+ : {+ headers: Object.fromEntries(+ Object.keys(provider.headers).map((name) => [name, "[redacted]"]),+ ),+ }),+ },+ acp.agent.setProvider(provider),),),- disableProvider: (providerId) => {- const request = { providerId } satisfies EffectAcpSchema.DisableProviderRequest;- return initialize.pipe(- Effect.filterOrFail(- (initialized) => initialized.agentCapabilities?.providers != null,- () =>- new EffectAcpErrors.AcpRequestError({- code: -32601,- errorMessage: "ACP agent does not advertise provider configuration support",- }),- ),- Effect.andThen(- runLoggedRequest("providers/disable", request, acp.agent.disableProvider(request)),- ),- );- },- logout: initialize.pipe(+ ),+ disableProvider: (providerId) => {+ const request = { providerId } satisfies EffectAcpSchema.DisableProviderRequest;+ return initialize.pipe(Effect.filterOrFail(- (initialized) => initialized.agentCapabilities?.auth?.logout != null,+ (initialized) => initialized.agentCapabilities?.providers != null,() =>new EffectAcpErrors.AcpRequestError({code: -32601,- errorMessage: "ACP agent does not advertise logout support",+ errorMessage: "ACP agent does not advertise provider configuration support",}),),- Effect.andThen(runLoggedRequest("logout", {}, acp.agent.logout({}))),+ Effect.andThen(+ runLoggedRequest("providers/disable", request, acp.agent.disableProvider(request)),+ ),+ );+ },+ logout: initialize.pipe(+ Effect.filterOrFail(+ (initialized) => initialized.agentCapabilities?.auth?.logout != null,+ () =>+ new EffectAcpErrors.AcpRequestError({+ code: -32601,+ errorMessage: "ACP agent does not advertise logout support",+ }),),- prompt: (payload, promptOptions?) =>- promptSerializationSemaphore.withPermit(- Effect.acquireUseRelease(- promptDispatchSemaphore.withPermit(- Effect.gen(function* () {- const started = yield* getStartedState;- yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });- yield* Ref.set(assistantUpdatesOpenRef, true);- const requestPayload = {- sessionId: started.sessionId,- ...payload,- } satisfies EffectAcpSchema.PromptRequest;- const completed = yield* Deferred.make<void>();- const fiber = yield* runLoggedRequest(- "session/prompt",- requestPayload,- acp.agent.prompt(requestPayload),- ).pipe(Effect.forkIn(runtimeScope));- const active = { fiber, completed } satisfies AcpActivePrompt;- yield* Ref.set(activePromptRef, Option.some(active));- if (promptOptions?.dispatched) {- yield* Deferred.succeed(promptOptions.dispatched, undefined);- }- return active;- }).pipe(notificationSemaphore.withPermit),- ),- (activePrompt) =>- Fiber.join(activePrompt.fiber).pipe(- Effect.catchCause((cause) =>- options.cancelBehavior !== "wait-for-prompt" && Cause.hasInterruptsOnly(cause)- ? Effect.succeed({- stopReason: "cancelled",- } satisfies EffectAcpSchema.PromptResponse)- : Effect.failCause(cause),- ),- Effect.tap(() =>- closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }),- ),- ),- (activePrompt, result) =>- Effect.gen(function* () {- if (- options.cancelBehavior === "wait-for-prompt" &&- Exit.isFailure(result) &&- Cause.hasInterrupts(result.cause)- ) {- yield* retireRuntime(- new EffectAcpErrors.AcpTransportError({- method: "session/prompt",- detail: "The ACP prompt stopped before the agent confirmed completion.",- cause: undefined,- }),- );- }- yield* Fiber.interrupt(activePrompt.fiber).pipe(Effect.ignore);- yield* Ref.set(activePromptRef, Option.none());- yield* Deferred.succeed(activePrompt.completed, undefined);- }),+ Effect.andThen(runLoggedRequest("logout", {}, acp.agent.logout({}))),+ ),+ prompt: (payload, promptOptions?) =>+ promptSerializationSemaphore.withPermit(+ Effect.acquireUseRelease(+ promptDispatchSemaphore.withPermit(+ Effect.gen(function* () {+ const started = yield* getStartedState;+ yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });+ yield* Ref.set(assistantUpdatesOpenRef, true);+ const requestPayload = {+ sessionId: started.sessionId,+ ...payload,+ } satisfies EffectAcpSchema.PromptRequest;+ const completed = yield* Deferred.make<void>();+ const fiber = yield* runLoggedRequest(+ "session/prompt",+ requestPayload,+ acp.agent.prompt(requestPayload),+ ).pipe(Effect.forkIn(runtimeScope));+ const active = { fiber, completed } satisfies AcpActivePrompt;+ yield* Ref.set(activePromptRef, Option.some(active));+ if (promptOptions?.dispatched) {+ yield* Deferred.succeed(promptOptions.dispatched, undefined);+ }+ return active;+ }).pipe(notificationSemaphore.withPermit),),+ (activePrompt) =>+ Fiber.join(activePrompt.fiber).pipe(+ Effect.catchCause((cause) =>+ options.cancelBehavior !== "wait-for-prompt" && Cause.hasInterruptsOnly(cause)+ ? Effect.succeed({+ stopReason: "cancelled",+ } satisfies EffectAcpSchema.PromptResponse)+ : Effect.failCause(cause),+ ),+ Effect.tap(() =>+ closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }),+ ),+ ),+ (activePrompt, result) =>+ Effect.gen(function* () {+ if (+ options.cancelBehavior === "wait-for-prompt" &&+ Exit.isFailure(result) &&+ Cause.hasInterrupts(result.cause)+ ) {+ yield* retireRuntime(+ new EffectAcpErrors.AcpTransportError({+ method: "session/prompt",+ detail: "The ACP prompt stopped before the agent confirmed completion.",+ cause: undefined,+ }),+ );+ }+ yield* Fiber.interrupt(activePrompt.fiber).pipe(Effect.ignore);+ yield* Ref.set(activePromptRef, Option.none());+ yield* Deferred.succeed(activePrompt.completed, undefined);+ }),),- cancel:- options.cancelBehavior === "wait-for-prompt"- ? promptDispatchSemaphore.withPermit(cancel)- : cancel,- ...(options.ownDetachedProcessGroup === true ? { terminateProcessGroup } : {}),- // A session's mode is its `category: "mode"` config option. ACP v1 agents- // that only advertise `modes` (gemini-cli) take `session/set_mode`- // instead, which ACP v2 removed.- setMode: (modeId) =>- Effect.gen(function* () {- const modeState = yield* Ref.get(modeStateRef);- if (modeState?.currentModeId === modeId) {- return {} satisfies EffectAcpSchema.SetSessionModeResponse;- }- const modeConfigOption = (yield* Ref.get(configOptionsRef))?.find(- (option) => option.category === "mode" && option.type === "select",- );- if (modeConfigOption === undefined && modeState !== undefined) {- const started = yield* getStartedState;- const payload = { sessionId: started.sessionId, modeId };- yield* runLoggedRequest("session/set_mode", payload, acp.agent.setSessionMode(payload));- yield* updateCurrentModeId(modeId);- return {} satisfies EffectAcpSchema.SetSessionModeResponse;- }- const response = yield* setConfigOption(modeConfigOption?.id ?? "mode", modeId);- const reported = parseSessionModeState({ configOptions: response.configOptions });- if (reported === undefined) {- yield* updateCurrentModeId(modeId);- } else {- yield* updateCurrentModeId(reported.currentModeId);- }- return {} satisfies EffectAcpSchema.SetSessionModeResponse;+ ),+ cancel:+ options.cancelBehavior === "wait-for-prompt"+ ? promptDispatchSemaphore.withPermit(cancel)+ : cancel,+ ...(options.ownDetachedProcessGroup === true ? { terminateProcessGroup } : {}),+ // A session's mode is its `category: "mode"` config option. ACP v1 agents+ // that only advertise `modes` (gemini-cli) take `session/set_mode`+ // instead, which ACP v2 removed.+ setMode: Effect.fn("AcpSessionRuntime.setMode")(function* (modeId) {+ const modeState = yield* Ref.get(modeStateRef);+ if (modeState?.currentModeId === modeId) {+ return {} satisfies EffectAcpSchema.SetSessionModeResponse;+ }+ const modeConfigOption = (yield* Ref.get(configOptionsRef))?.find(+ (option) => option.category === "mode" && option.type === "select",+ );+ if (modeConfigOption === undefined && modeState !== undefined) {+ const started = yield* getStartedState;+ const payload = { sessionId: started.sessionId, modeId };+ yield* runLoggedRequest("session/set_mode", payload, acp.agent.setSessionMode(payload));+ yield* updateCurrentModeId(modeId);+ return {} satisfies EffectAcpSchema.SetSessionModeResponse;+ }+ const response = yield* setConfigOption(modeConfigOption?.id ?? "mode", modeId);+ const reported = parseSessionModeState({ configOptions: response.configOptions });+ if (reported === undefined) {+ yield* updateCurrentModeId(modeId);+ } else {+ yield* updateCurrentModeId(reported.currentModeId);+ }+ return {} satisfies EffectAcpSchema.SetSessionModeResponse;+ }),+ setSessionModel: (modelId, meta) =>+ getStartedState.pipe(+ Effect.flatMap((started) => {+ const payload = {+ sessionId: started.sessionId,+ modelId,+ ...(meta === undefined ? {} : { _meta: meta }),+ };+ return runLoggedRequest("session/set_model", payload, acp.agent.setSessionModel(payload));}),- setSessionModel: (modelId, meta) =>- getStartedState.pipe(- Effect.flatMap((started) => {- const payload = {- sessionId: started.sessionId,- modelId,- ...(meta === undefined ? {} : { _meta: meta }),- };- return runLoggedRequest(- "session/set_model",- payload,- acp.agent.setSessionModel(payload),- );- }),- ),- setConfigOption,- setModel: (model) =>- getStartedState.pipe(- Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),- Effect.asVoid,- ),+ ),+ setConfigOption,+ setModel: (model) =>+ getStartedState.pipe(+ Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),+ Effect.asVoid,+ ),- request: (method, payload) =>- ensureConnected.pipe(- Effect.andThen(runLoggedRequest(method, payload, acp.raw.request(method, payload))),- ),- notify: (method, payload) =>- ensureConnected.pipe(Effect.andThen(acp.raw.notify(method, payload))),- } satisfies AcpSessionRuntime["Service"];- });+ request: (method, payload) =>+ ensureConnected.pipe(+ Effect.andThen(runLoggedRequest(method, payload, acp.raw.request(method, payload))),+ ),+ notify: (method, payload) =>+ ensureConnected.pipe(Effect.andThen(acp.raw.notify(method, payload))),+ } satisfies AcpSessionRuntime["Service"];+});export const layer = (options: AcpSessionRuntimeOptions,@@ -2751,26 +2728,27 @@ function isStartupMetadataUpdate(notification: EffectAcpSchema.SessionNotificati}}-const handleSessionUpdate = ({- queue,- modeStateRef,- configOptionsRef,- toolCallsRef,- shownToolCallIds,- assistantSegmentRef,- assistantItemRuntimeId,- params,-}: {- readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;- readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;- readonly configOptionsRef: Ref.Ref<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;- readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallTrackedState>>;- readonly shownToolCallIds: Set<string>;- readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;- readonly assistantItemRuntimeId: string;- readonly params: EffectAcpSchema.SessionNotification;-}): Effect.Effect<void> =>- Effect.gen(function* () {+const handleSessionUpdate =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* ({+ queue,+ modeStateRef,+ configOptionsRef,+ toolCallsRef,+ shownToolCallIds,+ assistantSegmentRef,+ assistantItemRuntimeId,+ params,+ }: {+ readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;+ readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;+ readonly configOptionsRef: Ref.Ref<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;+ readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallTrackedState>>;+ readonly shownToolCallIds: Set<string>;+ readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;+ readonly assistantItemRuntimeId: string;+ readonly params: EffectAcpSchema.SessionNotification;+ }): Effect.fn.Return<void> {if (params.update.sessionUpdate === "config_option_update") {const configOptions = params.update.configOptions;yield* Ref.set(configOptionsRef, configOptions);diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.tsindex 0a2b7fa3948..5d7ea0b7d28 100644--- a/packages/provider-acp/src/server/adapter.ts+++ b/packages/provider-acp/src/server/adapter.ts@@ -1568,12 +1568,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (return Option.some(yield* effect);}),);- const registerNativeResponseAcknowledgement = (- generation: number,- transportRequestId: string,- acknowledgement: Deferred.Deferred<void, EffectAcpErrors.AcpError>,- ) =>- Effect.gen(function* () {+ const registerNativeResponseAcknowledgement =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ generation: number,+ transportRequestId: string,+ acknowledgement: Deferred.Deferred<void, EffectAcpErrors.AcpError>,+ ) {yield* Ref.update(nativeResponseAcknowledgements, (current) => {const updated = new Map(current);updated.set(transportRequestId, { acknowledgement, generation });@@ -1813,8 +1814,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (const endedBackgroundTaskIds = yield* Ref.make<ReadonlySet<string>>(new Set());const endedBackgroundTaskIdLimit = 128;- const setBackgroundTaskRunning = (taskId: string, running: boolean) =>- Effect.gen(function* () {+ const setBackgroundTaskRunning =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (taskId: string, running: boolean) {if (running && (yield* Ref.get(endedBackgroundTaskIds)).has(taskId)) {return;}@@ -1849,10 +1851,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (? setBackgroundTaskRunning(mutation.taskId, true): markBackgroundTaskEnded(mutation.taskId);- const trackRunningBackgroundTools = (- notification: EffectAcpSchema.SessionNotification,- ): Effect.Effect<void> =>- Effect.gen(function* () {+ const trackRunningBackgroundTools =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ notification: EffectAcpSchema.SessionNotification,+ ): Effect.fn.Return<void> {if (flavor.extractBackgroundTaskId === undefined) return;for (const event of parseSessionUpdateEvent(notification).events) {if (event._tag !== "ToolCallUpdated") continue;@@ -2836,8 +2839,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (return false;};- const rearmDeferredFinalize = (context: ActiveAcpTurn) =>- Effect.gen(function* () {+ const rearmDeferredFinalize =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (context: ActiveAcpTurn) {if (!flavor.deferFinalizeForBackgroundWork) return;if (!context.promptSettled || context.finalized) return;if (hasDeferredBackgroundWork(context)) return;@@ -2851,8 +2855,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (projectedStatus?: ProjectedToolStatus,) => Effect.Effect<void> = () => Effect.void;- const markAwaitingBackgroundHydration = (context: ActiveAcpTurn, taskId: string) =>- Effect.gen(function* () {+ const markAwaitingBackgroundHydration =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (context: ActiveAcpTurn, taskId: string) {if (context.awaitingBackgroundHydration.has(taskId)) return;context.awaitingBackgroundHydration.add(taskId);yield* Effect.gen(function* () {@@ -2871,8 +2876,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (}).pipe(Effect.forkIn(sessionScope), Effect.asVoid);});- const markPendingInjectedReport = (context: ActiveAcpTurn, taskId: string) =>- Effect.gen(function* () {+ const markPendingInjectedReport =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (context: ActiveAcpTurn, taskId: string) {if (!context.promptSettled) return;if (context.pendingInjectedReport.has(taskId)) return;context.pendingInjectedReport.add(taskId);@@ -3421,13 +3427,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (});});- const appendLoadedHistory = (- notification: EffectAcpSchema.SessionNotification,- role: "user" | "assistant" | "thought",- text: string,- replace = false,- ) =>- Effect.gen(function* () {+ const appendLoadedHistory =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ notification: EffectAcpSchema.SessionNotification,+ role: "user" | "assistant" | "thought",+ text: string,+ replace = false,+ ) {if (text.length === 0 && !replace) return;const now = yield* DateTime.now;yield* Ref.update(snapshot, (current) => {@@ -5088,47 +5095,47 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (}});- const projectAcpRuntimeSessionUpdateEffect = (- rawNotification: EffectAcpSchema.SessionNotification,- ) =>- Effect.gen(function* () {- if (clientTerminals !== undefined) {- const embedded = embeddedTerminalIdsFromSessionUpdate(rawNotification);- if (embedded !== undefined) {- rememberEmbeddedTerminals({- ...embedded,- sessionId: rawNotification.sessionId,- });+ const projectAcpRuntimeSessionUpdateEffect =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(+ function* (rawNotification: EffectAcpSchema.SessionNotification) {+ if (clientTerminals !== undefined) {+ const embedded = embeddedTerminalIdsFromSessionUpdate(rawNotification);+ if (embedded !== undefined) {+ rememberEmbeddedTerminals({+ ...embedded,+ sessionId: rawNotification.sessionId,+ });+ }}- }- const notification =- clientTerminals === undefined- ? rawNotification- : resolveEmbeddedTerminalContent(- rawNotification,- clientTerminals.readOutputSnapshot,- );- if (notification.update.sessionUpdate === "available_commands_update") {- yield* (- flavor.onAvailableCommandsUpdate?.(notification.update.availableCommands) ??- Effect.void- );- }- if (- notification.update.sessionUpdate === "config_option_update" ||- notification.update.sessionUpdate === "current_mode_update"- ) {- yield* (- flavor.onSessionConfigurationUpdate?.(- yield* runtime.getConfigOptions,- yield* runtime.getModeState,- ) ?? Effect.void+ const notification =+ clientTerminals === undefined+ ? rawNotification+ : resolveEmbeddedTerminalContent(+ rawNotification,+ clientTerminals.readOutputSnapshot,+ );+ if (notification.update.sessionUpdate === "available_commands_update") {+ yield* (+ flavor.onAvailableCommandsUpdate?.(notification.update.availableCommands) ??+ Effect.void+ );+ }+ if (+ notification.update.sessionUpdate === "config_option_update" ||+ notification.update.sessionUpdate === "current_mode_update"+ ) {+ yield* (+ flavor.onSessionConfigurationUpdate?.(+ yield* runtime.getConfigOptions,+ yield* runtime.getModeState,+ ) ?? Effect.void+ );+ }+ yield* handleSessionUpdate(+ flavor.normalizeSessionUpdate?.(notification) ?? notification,);- }- yield* handleSessionUpdate(- flavor.normalizeSessionUpdate?.(notification) ?? notification,- );- }).pipe(+ },Effect.mapError((cause) =>new EffectAcpErrors.AcpTransportError({diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.tsindex 29d5f852762..c1b32237387 100644--- a/packages/provider-acp/src/server/mcpOverAcpBridge.ts+++ b/packages/provider-acp/src/server/mcpOverAcpBridge.ts@@ -139,94 +139,90 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun}).pipe(Effect.mapError(bridgeError)),);- const disconnect = (+ const disconnect = Effect.fn("mcpOverAcpBridge.disconnect")(function* (request: AcpSchema.DisconnectMcpRequest,- ): Effect.Effect<AcpSchema.DisconnectMcpResponse, AcpMcpOverAcpError> =>- Effect.gen(function* () {- const connection = yield* connectionFor(request.connectionId);- connections.delete(request.connectionId);- const sessionId = connection.sessionId;- if (sessionId !== null) {- const response = yield* Effect.tryPromise({- try: (signal) =>- fetchImplementation(options.endpoint, {- method: "DELETE",- signal,- headers: {- authorization: options.authorization,- "mcp-session-id": sessionId,- ...(connection.protocolVersion === null- ? {}- : { "mcp-protocol-version": connection.protocolVersion }),- },- }),- catch: bridgeError,- });- if (!response.ok && response.status !== 404) {- return yield* Effect.fail(- new AcpMcpOverAcpError(- `T3 Code MCP endpoint rejected disconnect with HTTP ${response.status}.`,- ),- );- }- yield* Effect.promise(- () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(),+ ): Effect.fn.Return<AcpSchema.DisconnectMcpResponse, AcpMcpOverAcpError> {+ const connection = yield* connectionFor(request.connectionId);+ connections.delete(request.connectionId);+ const sessionId = connection.sessionId;+ if (sessionId !== null) {+ const response = yield* Effect.tryPromise({+ try: (signal) =>+ fetchImplementation(options.endpoint, {+ method: "DELETE",+ signal,+ headers: {+ authorization: options.authorization,+ "mcp-session-id": sessionId,+ ...(connection.protocolVersion === null+ ? {}+ : { "mcp-protocol-version": connection.protocolVersion }),+ },+ }),+ catch: bridgeError,+ });+ if (!response.ok && response.status !== 404) {+ return yield* Effect.fail(+ new AcpMcpOverAcpError(+ `T3 Code MCP endpoint rejected disconnect with HTTP ${response.status}.`,+ ),);}- return {};- });+ yield* Effect.promise(+ () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(),+ );+ }+ return {};+ });return {- connect: (request) =>- Effect.gen(function* () {- if (request.serverId !== "t3-code") {- return yield* Effect.fail(- new AcpMcpOverAcpError(`Unknown ACP MCP server "${request.serverId}".`),- );- }- if (connections.size >= MAX_CONNECTIONS) {- return yield* Effect.fail(new AcpMcpOverAcpError("Too many MCP-over-ACP connections."));- }- const connectionId = yield* options.allocateConnectionId;- connections.set(connectionId, {- mutex: yield* Semaphore.make(1),- sessionId: null,- protocolVersion: null,- nextRequestId: 0,- });- return { connectionId };- }),- message: (request) =>- Effect.gen(function* () {- const connection = yield* connectionFor(request.connectionId);- const id = ++connection.nextRequestId;- const payloads = yield* send(connection, {- jsonrpc: "2.0",- id,- method: request.method,- ...(request.params == null ? {} : { params: request.params }),- });- const response = payloads.find((payload) => asEnvelope(payload)?.id === id);- const envelope = asEnvelope(response);- if (envelope === null) {- return yield* Effect.fail(- new AcpMcpOverAcpError("MCP server did not return a matching response."),- );- }- if (envelope.error !== undefined) {- return yield* Effect.fail(new AcpMcpOverAcpError(errorMessage(envelope.error)));- }- return (envelope.result ?? null) as AcpSchema.MessageMcpResponse;- }),- notification: (request) =>- Effect.gen(function* () {- const connection = yield* connectionFor(request.connectionId);- yield* send(connection, {- jsonrpc: "2.0",- method: request.method,- ...(request.params == null ? {} : { params: request.params }),- });- }),+ connect: Effect.fn("mcpOverAcpBridge.connect")(function* (request) {+ if (request.serverId !== "t3-code") {+ return yield* Effect.fail(+ new AcpMcpOverAcpError(`Unknown ACP MCP server "${request.serverId}".`),+ );+ }+ if (connections.size >= MAX_CONNECTIONS) {+ return yield* Effect.fail(new AcpMcpOverAcpError("Too many MCP-over-ACP connections."));+ }+ const connectionId = yield* options.allocateConnectionId;+ connections.set(connectionId, {+ mutex: yield* Semaphore.make(1),+ sessionId: null,+ protocolVersion: null,+ nextRequestId: 0,+ });+ return { connectionId };+ }),+ message: Effect.fn("mcpOverAcpBridge.message")(function* (request) {+ const connection = yield* connectionFor(request.connectionId);+ const id = ++connection.nextRequestId;+ const payloads = yield* send(connection, {+ jsonrpc: "2.0",+ id,+ method: request.method,+ ...(request.params == null ? {} : { params: request.params }),+ });+ const response = payloads.find((payload) => asEnvelope(payload)?.id === id);+ const envelope = asEnvelope(response);+ if (envelope === null) {+ return yield* Effect.fail(+ new AcpMcpOverAcpError("MCP server did not return a matching response."),+ );+ }+ if (envelope.error !== undefined) {+ return yield* Effect.fail(new AcpMcpOverAcpError(errorMessage(envelope.error)));+ }+ return (envelope.result ?? null) as AcpSchema.MessageMcpResponse;+ }),+ notification: Effect.fn("mcpOverAcpBridge.notification")(function* (request) {+ const connection = yield* connectionFor(request.connectionId);+ yield* send(connection, {+ jsonrpc: "2.0",+ method: request.method,+ ...(request.params == null ? {} : { params: request.params }),+ });+ }),disconnect,dispose: Effect.suspend(() =>Effect.forEach(diff --git a/packages/provider-acp/src/server/nativeLogging.ts b/packages/provider-acp/src/server/nativeLogging.tsindex 48188838f2b..b363ae57bbd 100644--- a/packages/provider-acp/src/server/nativeLogging.ts+++ b/packages/provider-acp/src/server/nativeLogging.ts@@ -126,11 +126,8 @@ export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory"readonly threadId: ThreadId;readonly verboseProtocolLogging?: boolean;}): Pick<AcpSessionRuntime.AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> => {- const writeNativeAcpLog = (logInput: {- readonly kind: "request" | "protocol";- readonly payload: unknown;- }) =>- Effect.gen(function* () {+ const writeNativeAcpLog = Effect.fn("AcpNativeLogging.writeNativeAcpLog")(+ function* (logInput: { readonly kind: "request" | "protocol"; readonly payload: unknown }) {if (!input.nativeEventLogger) return;const observedAt = DateTime.formatIso(yield* DateTime.now);yield* input.nativeEventLogger.write(@@ -147,18 +144,18 @@ export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory"},input.threadId,);- }).pipe(- Effect.catchCause((cause) =>- Cause.hasInterrupts(cause)- ? Effect.interrupt- : Effect.logWarning("Failed to write native ACP event log.", {- errorTag: causeErrorTag(cause),- reasonCount: cause.reasons.length,- provider: input.provider,- threadId: input.threadId,- }),- ),- );+ },+ Effect.catchCause((cause) =>+ Cause.hasInterrupts(cause)+ ? Effect.interrupt+ : Effect.logWarning("Failed to write native ACP event log.", {+ errorTag: causeErrorTag(cause),+ reasonCount: cause.reasons.length,+ provider: input.provider,+ threadId: input.threadId,+ }),+ ),+ );return {requestLogger: (event: AcpSessionRuntime.AcpSessionRequestLogEvent) =>diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.tsindex a2a271e5b9b..bad434e938e 100644--- a/packages/provider-acp/src/server/runtimeModel.ts+++ b/packages/provider-acp/src/server/runtimeModel.ts@@ -1287,27 +1287,24 @@ export interface SessionLoadGate {readonly candidateConfigOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption>;}-export const waitForSessionLoadReplayIdle = (input: {+export const waitForSessionLoadReplayIdle = Effect.fn(+ "AcpRuntimeModel.waitForSessionLoadReplayIdle",+)(function* (input: {readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;-}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>- Effect.gen(function* () {- const pollInterval = Duration.millis(25);- while (true) {- const gate = yield* Ref.get(input.gateRef);- if (- Option.isSome(gate) &&- gate.value.active &&- gate.value.lastActivityAtMillis !== undefined- ) {- const idleGapMillis = Duration.toMillis(gate.value.idleGap);- const nowMillis = yield* Clock.currentTimeMillis;- if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {- return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);- }+}): Effect.fn.Return<EffectAcpSchema.LoadSessionResponse, never> {+ const pollInterval = Duration.millis(25);+ while (true) {+ const gate = yield* Ref.get(input.gateRef);+ if (Option.isSome(gate) && gate.value.active && gate.value.lastActivityAtMillis !== undefined) {+ const idleGapMillis = Duration.toMillis(gate.value.idleGap);+ const nowMillis = yield* Clock.currentTimeMillis;+ if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {+ return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);}- yield* Effect.sleep(pollInterval);}- });+ yield* Effect.sleep(pollInterval);+ }+});export function sessionModelStateFromInitialize(initializeResult: EffectAcpSchema.InitializeResponse,diff --git a/packages/provider-cursor/src/server/accountUsage.ts b/packages/provider-cursor/src/server/accountUsage.tsindex 432bf60f94c..85eed312f71 100644--- a/packages/provider-cursor/src/server/accountUsage.ts+++ b/packages/provider-cursor/src/server/accountUsage.ts@@ -176,8 +176,8 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functilet completed = false;const pageSize = 1000;let total: number | undefined;- const readPage = (page: number) =>- Effect.gen(function* () {+ const readPage = Effect.fn("CursorAccountUsage.readPage")(+ function* (page: number) {// A count can include overlapping page boundaries. Allow room to// reconcile them without imposing a fixed account-size limit.if (page > (total === undefined ? 1000 : Math.ceil(total / pageSize) * 2 + 1)) {@@ -243,12 +243,12 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi}if (typeof count === "number") total = count;return events as unknown[];- }).pipe(- Effect.timeoutOrElse({- duration: Duration.seconds(10),- orElse: () => invalid("Account usage request timed out"),- }),- );+ },+ Effect.timeoutOrElse({+ duration: Duration.seconds(10),+ orElse: () => invalid("Account usage request timed out"),+ }),+ );// Cursor caps a page at 1,000 events and takes about a second to answer one, so the pages// the first one's count implies are requested up to six ahead and consumed in page order.const ahead: Fiber.Fiber<diff --git a/packages/provider-cursor/src/server/auth.ts b/packages/provider-cursor/src/server/auth.tsindex 198bbeb3727..2122731a9d7 100644--- a/packages/provider-cursor/src/server/auth.ts+++ b/packages/provider-cursor/src/server/auth.ts@@ -154,8 +154,8 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu}),);- const runLogin = (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) =>- Effect.gen(function* () {+ const runLogin = Effect.fn("CursorAuth.runLogin")(+ function* (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) {yield* stopSessions.pipe(Effect.ensuring(stopSessionsWithCredentials));// The SDK first writes into memory. Cancellation must not save a late login result.const pendingStore = new InMemoryCredentialStore();@@ -243,50 +243,56 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu});}).pipe(Effect.uninterruptible),);- }).pipe(- Effect.scoped,- Effect.timeoutOrElse({- duration: AUTH_TIMEOUT_MS,- orElse: () =>- Effect.fail(- new ProviderSetupError({- instanceId: options.instanceId,- operation: "start",- detail: "Cursor sign-in expired. Start sign-in again.",+ },+ (effect, flow, stopSessions) =>+ effect.pipe(+ Effect.scoped,+ Effect.timeoutOrElse({+ duration: AUTH_TIMEOUT_MS,+ orElse: () =>+ Effect.fail(+ new ProviderSetupError({+ instanceId: options.instanceId,+ operation: "start",+ detail: "Cursor sign-in expired. Start sign-in again.",+ }),+ ),+ }),+ Effect.exit,+ Effect.flatMap((result) =>+ lock.withPermits(1)(+ Effect.gen(function* () {+ if (active !== flow) return;+ active = undefined;+ operation = "idle";+ yield* publish(flow, {+ phase: Exit.isSuccess(result) ? "succeeded" : "failed",+ authorizationUrl: null,+ expiresAt: null,+ message: Exit.isSuccess(result)+ ? "Signed in with Cursor."+ : "Cursor sign-in failed or expired. Start sign-in again.",+ });}),),- }),- Effect.exit,- Effect.flatMap((result) =>- lock.withPermits(1)(- Effect.gen(function* () {- if (active !== flow) return;- active = undefined;- operation = "idle";- yield* publish(flow, {- phase: Exit.isSuccess(result) ? "succeeded" : "failed",- authorizationUrl: null,- expiresAt: null,- message: Exit.isSuccess(result)- ? "Signed in with Cursor."- : "Cursor sign-in failed or expired. Start sign-in again.",- });- }),),),- );+ );- const requireFlow = (owner: string, id: string, name: string) =>- Effect.gen(function* () {- if (!active || active.owner !== owner || active.id !== id) {- return yield* new ProviderSetupError({- instanceId: options.instanceId,- operation: name,- detail: "This sign-in is no longer active in this client.",- });- }- return active;- });+ const requireFlow = Effect.fn("CursorAuth.requireFlow")(function* (+ owner: string,+ id: string,+ name: string,+ ) {+ if (!active || active.owner !== owner || active.id !== id) {+ return yield* new ProviderSetupError({+ instanceId: options.instanceId,+ operation: name,+ detail: "This sign-in is no longer active in this client.",+ });+ }+ return active;+ });const controller: ProviderAuthController = {credentialBinding: options.credentialBinding ?? {diff --git a/packages/provider-cursor/src/server/driver.ts b/packages/provider-cursor/src/server/driver.tsindex 5a3ac63166f..6937c7aa88a 100644--- a/packages/provider-cursor/src/server/driver.ts+++ b/packages/provider-cursor/src/server/driver.ts@@ -86,224 +86,230 @@ export const CursorDriver: ProviderDriver<),),},- create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>- Effect.gen(function* () {- const host = yield* ProviderHost.ProviderHost;- const fileSystem = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const httpClient = yield* HttpClient.HttpClient;- const keychain = yield* CursorKeychain.CursorKeychain;- const sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner;- const processEnv = yield* mergeProviderInstanceEnvironment(environment);- const continuationIdentity = defaultProviderContinuationIdentity({- driverKind: DRIVER_KIND,- instanceId,- });- const stampIdentity = withInstanceIdentity({- instanceId,- driverKind: DRIVER_KIND,- displayName: displayName ?? "Cursor",- accentColor,- continuationGroupKey: continuationIdentity.continuationKey,- });- const effectiveConfig = { ...config, enabled } satisfies CursorSettings;- const credentials = yield* CursorCredentialStore.makeCursorCredentialStore(- instanceId,- path.join(- host.paths.stateDir,- "provider-auth",- encodeURIComponent(instanceId),- "cursor.json",- ),- ).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Could not open the Cursor credential store.",- cause,- }),- ),- );- const auth = yield* makeCursorAuth({- instanceId,- displayName: displayName ?? "Cursor",- enabled,- ...(processEnv.CURSOR_API_KEY ? { apiKey: processEnv.CURSOR_API_KEY } : {}),- store: credentials.store,- credentialBinding: credentials.binding,- onChanged: (signedIn): Effect.Effect<void, ProviderSetupError> =>- snapshot.refresh.pipe(- Effect.flatMap((provider) =>- !signedIn || provider.auth.status === "authenticated"- ? Effect.void- : Effect.fail(- new ProviderSetupError({- instanceId,- operation: "start",- detail: provider.message ?? "Could not verify the Cursor sign-in. Try again.",- }),- ),- ),+ create: Effect.fn("CursorDriver.create")(function* ({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }) {+ const host = yield* ProviderHost.ProviderHost;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const httpClient = yield* HttpClient.HttpClient;+ const keychain = yield* CursorKeychain.CursorKeychain;+ const sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner;+ const processEnv = yield* mergeProviderInstanceEnvironment(environment);+ const continuationIdentity = defaultProviderContinuationIdentity({+ driverKind: DRIVER_KIND,+ instanceId,+ });+ const stampIdentity = withInstanceIdentity({+ instanceId,+ driverKind: DRIVER_KIND,+ displayName: displayName ?? "Cursor",+ accentColor,+ continuationGroupKey: continuationIdentity.continuationKey,+ });+ const effectiveConfig = { ...config, enabled } satisfies CursorSettings;+ const credentials = yield* CursorCredentialStore.makeCursorCredentialStore(+ instanceId,+ path.join(+ host.paths.stateDir,+ "provider-auth",+ encodeURIComponent(instanceId),+ "cursor.json",+ ),+ ).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Could not open the Cursor credential store.",+ cause,+ }),+ ),+ );+ const auth = yield* makeCursorAuth({+ instanceId,+ displayName: displayName ?? "Cursor",+ enabled,+ ...(processEnv.CURSOR_API_KEY ? { apiKey: processEnv.CURSOR_API_KEY } : {}),+ store: credentials.store,+ credentialBinding: credentials.binding,+ onChanged: (signedIn): Effect.Effect<void, ProviderSetupError> =>+ snapshot.refresh.pipe(+ Effect.flatMap((provider) =>+ !signedIn || provider.auth.status === "authenticated"+ ? Effect.void+ : Effect.fail(+ new ProviderSetupError({+ instanceId,+ operation: "start",+ detail: provider.message ?? "Could not verify the Cursor sign-in. Try again.",+ }),+ ),),+ ),+ });+ const stampSnapshot: typeof stampIdentity = (draft) =>+ stampIdentity({+ ...draft,+ setup: { canAuthenticate: !auth.usesApiKey, canInstall: false },+ auth: {+ ...draft.auth,+ canLogout: !auth.usesApiKey,+ },});- const stampSnapshot: typeof stampIdentity = (draft) =>- stampIdentity({- ...draft,- setup: { canAuthenticate: !auth.usesApiKey, canInstall: false },- auth: {- ...draft.auth,- canLogout: !auth.usesApiKey,- },- });- let catalogModels: ReadonlyArray<ServerProviderModel> = [];- const orchestrationAdapter = yield* makeCursorAdapterV2({- instanceId,- settings: effectiveConfig,- environment: processEnv,- getModels: () => catalogModels,- }).pipe(- Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {- ...sdkRunner,- open: (input) =>- auth.requireApiKey.pipe(- Effect.flatMap((apiKey) =>- Effect.acquireRelease(- sdkRunner- .open({ ...input, options: { ...input.options, apiKey } })- .pipe(- Effect.flatMap((session) =>- Effect.cached(session.close).pipe(- Effect.map((close) => ({ ...session, close })),- ),+ let catalogModels: ReadonlyArray<ServerProviderModel> = [];+ const orchestrationAdapter = yield* makeCursorAdapterV2({+ instanceId,+ settings: effectiveConfig,+ environment: processEnv,+ getModels: () => catalogModels,+ }).pipe(+ Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {+ ...sdkRunner,+ open: (input) =>+ auth.requireApiKey.pipe(+ Effect.flatMap((apiKey) =>+ Effect.acquireRelease(+ sdkRunner+ .open({ ...input, options: { ...input.options, apiKey } })+ .pipe(+ Effect.flatMap((session) =>+ Effect.cached(session.close).pipe(+ Effect.map((close) => ({ ...session, close })),),),- (session) => session.close.pipe(Effect.ignore),- ),- ),- auth.withAccess,- Effect.mapError((cause) =>- isSdkRunnerError(cause)- ? cause- : new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "open", cause }),+ ),+ (session) => session.close.pipe(Effect.ignore),),),- }),- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to build Cursor orchestration adapter.",- cause,- }),- ),- );- const textGeneration = yield* makeCursorTextGeneration(- effectiveConfig,- processEnv,- auth.requireApiKey,- auth.withAccess,- );-- const checkProvider = auth.readApiKey.pipe(- Effect.orElseSucceed(() => undefined),- Effect.flatMap((apiKey) =>- checkCursorProviderStatus(- effectiveConfig,- {- ...processEnv,- CURSOR_API_KEY: apiKey,- },- auth.usesApiKey ? "api-key" : "browser",- ).pipe(- Effect.flatMap((snapshot) =>- effectiveConfig.enabled &&- snapshot.installed &&- snapshot.auth.status === "authenticated"- ? host.settings.get.pipe(- Effect.flatMap((settings) =>- readCursorUsageLimits(- effectiveConfig,- { ...processEnv, CURSOR_API_KEY: apiKey },- settings.cursorKeychainUsageEnabled,- ),- ),- Effect.map((usageLimits) => ({ ...snapshot, usageLimits })),- )- : Effect.succeed(snapshot),+ auth.withAccess,+ Effect.mapError((cause) =>+ isSdkRunnerError(cause)+ ? cause+ : new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "open", cause }),),),- ),- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- Effect.provideService(CursorKeychain.CursorKeychain, keychain),- Effect.map(stampSnapshot),- Effect.tap((provider) =>- Effect.sync(() => {- // A failed check lists only custom models, so keep the last loaded catalog.- if (provider.models.some((model) => !model.isCustom)) {- catalogModels = provider.models;- }+ }),+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to build Cursor orchestration adapter.",+ cause,}),- ),- Effect.provide(CursorSdkCatalog.layer),- );+ ),+ );+ const textGeneration = yield* makeCursorTextGeneration(+ effectiveConfig,+ processEnv,+ auth.requireApiKey,+ auth.withAccess,+ );- const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);- const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({- resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),- getSettings: snapshotSettings.getSettings,- streamSettings: snapshotSettings.streamSettings,- haveSettingsChanged: haveProviderSnapshotSettingsChanged,- initialSnapshot: (settings) =>- buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampSnapshot)),- checkProvider,- }).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to build Cursor snapshot.",- cause,- }),+ const checkProvider = auth.readApiKey.pipe(+ Effect.orElseSucceed(() => undefined),+ Effect.flatMap((apiKey) =>+ checkCursorProviderStatus(+ effectiveConfig,+ {+ ...processEnv,+ CURSOR_API_KEY: apiKey,+ },+ auth.usesApiKey ? "api-key" : "browser",+ ).pipe(+ Effect.flatMap((snapshot) =>+ effectiveConfig.enabled &&+ snapshot.installed &&+ snapshot.auth.status === "authenticated"+ ? host.settings.get.pipe(+ Effect.flatMap((settings) =>+ readCursorUsageLimits(+ effectiveConfig,+ { ...processEnv, CURSOR_API_KEY: apiKey },+ settings.cursorKeychainUsageEnabled,+ ),+ ),+ Effect.map((usageLimits) => ({ ...snapshot, usageLimits })),+ )+ : Effect.succeed(snapshot),+ ),),- );+ ),+ Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ Effect.provideService(CursorKeychain.CursorKeychain, keychain),+ Effect.map(stampSnapshot),+ Effect.tap((provider) =>+ Effect.sync(() => {+ // A failed check lists only custom models, so keep the last loaded catalog.+ if (provider.models.some((model) => !model.isCustom)) {+ catalogModels = provider.models;+ }+ }),+ ),+ Effect.provide(CursorSdkCatalog.layer),+ );- return {- instanceId,- driverKind: DRIVER_KIND,- continuationIdentity,- displayName,- accentColor,- enabled,- auth: auth.controller,- snapshot,- snapshotForCwd: (cwd) =>- !effectiveConfig.enabled- ? snapshot.getSnapshot- : Effect.all([- snapshot.getSnapshot,- probeCursorSkills(cwd, processEnv).pipe(- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: `Failed to discover Cursor skills for '${cwd}'`,- cause,- }),- ),+ const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);+ const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({+ resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),+ getSettings: snapshotSettings.getSettings,+ streamSettings: snapshotSettings.streamSettings,+ haveSettingsChanged: haveProviderSnapshotSettingsChanged,+ initialSnapshot: (settings) =>+ buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampSnapshot)),+ checkProvider,+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to build Cursor snapshot.",+ cause,+ }),+ ),+ );++ return {+ instanceId,+ driverKind: DRIVER_KIND,+ continuationIdentity,+ displayName,+ accentColor,+ enabled,+ auth: auth.controller,+ snapshot,+ snapshotForCwd: (cwd) =>+ !effectiveConfig.enabled+ ? snapshot.getSnapshot+ : Effect.all([+ snapshot.getSnapshot,+ probeCursorSkills(cwd, processEnv).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: `Failed to discover Cursor skills for '${cwd}'`,+ cause,+ }),),- ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills }))),- orchestrationAdapter,- textGeneration,- } satisfies ProviderInstance;- }),+ ),+ ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills }))),+ orchestrationAdapter,+ textGeneration,+ } satisfies ProviderInstance;+ }),};diff --git a/packages/provider-cursor/src/server/status.ts b/packages/provider-cursor/src/server/status.tsindex 3b00118688d..2c21a01459b 100644--- a/packages/provider-cursor/src/server/status.ts+++ b/packages/provider-cursor/src/server/status.ts@@ -34,44 +34,42 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({const CURSOR_SDK_CATALOG_TIMEOUT_MS = 15_000;-export function buildInitialCursorProviderSnapshot(- cursorSettings: CursorSettings,-): Effect.Effect<ServerProviderDraft> {- return Effect.gen(function* () {- const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);- const models = getCursorFallbackModels(cursorSettings);-- if (!cursorSettings.enabled) {- return buildServerProvider({- presentation: CURSOR_PRESENTATION,- enabled: false,- checkedAt,- models,- probe: {- installed: false,- version: null,- status: "warning",- auth: { status: "unknown" },- message: "Cursor is disabled in T3 Code settings.",- },- });- }+export const buildInitialCursorProviderSnapshot = Effect.fn(+ "CursorProviderStatus.buildInitialCursorProviderSnapshot",+)(function* (cursorSettings: CursorSettings): Effect.fn.Return<ServerProviderDraft> {+ const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);+ const models = getCursorFallbackModels(cursorSettings);+ if (!cursorSettings.enabled) {return buildServerProvider({presentation: CURSOR_PRESENTATION,- enabled: true,+ enabled: false,checkedAt,models,probe: {- installed: true,+ installed: false,version: null,status: "warning",auth: { status: "unknown" },- message: "Checking Cursor SDK availability...",+ message: "Cursor is disabled in T3 Code settings.",},});+ }++ return buildServerProvider({+ presentation: CURSOR_PRESENTATION,+ enabled: true,+ checkedAt,+ models,+ probe: {+ installed: true,+ version: null,+ status: "warning",+ auth: { status: "unknown" },+ message: "Checking Cursor SDK availability...",+ },});-}+});function getCursorFallbackModels(cursorSettings: Pick<CursorSettings, "customModels">,diff --git a/packages/provider-cursor/src/server/textGeneration.ts b/packages/provider-cursor/src/server/textGeneration.tsindex 1797e5d3852..cd6c1e511f5 100644--- a/packages/provider-cursor/src/server/textGeneration.ts+++ b/packages/provider-cursor/src/server/textGeneration.ts@@ -57,31 +57,35 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fuconst { Agent, SqliteLocalAgentStore } = yield* CursorSdk.CursorSdk;const resolvedEnvironment = environment ?? process.env;- const resolveCursorApiKey = (operation: TextGenerationOperations.Operation) =>- Effect.gen(function* () {- if (!cursorSettings.enabled) {- return yield* new TextGenerationError({- operation,- detail: "Cursor is disabled in T3 Code settings.",- });- }+ const resolveCursorApiKey = Effect.fn("CursorTextGeneration.resolveCursorApiKey")(function* (+ operation: TextGenerationOperations.Operation,+ ) {+ if (!cursorSettings.enabled) {+ return yield* new TextGenerationError({+ operation,+ detail: "Cursor is disabled in T3 Code settings.",+ });+ }- const apiKey = resolveApiKey- ? yield* resolveApiKey- : resolvedEnvironment.CURSOR_API_KEY?.trim();- if (!apiKey) {- return yield* new TextGenerationError({- operation,- detail: "Sign in with Cursor or add CURSOR_API_KEY in provider settings.",- });- }+ const apiKey = resolveApiKey+ ? yield* resolveApiKey+ : resolvedEnvironment.CURSOR_API_KEY?.trim();+ if (!apiKey) {+ return yield* new TextGenerationError({+ operation,+ detail: "Sign in with Cursor or add CURSOR_API_KEY in provider settings.",+ });+ }++ return apiKey;+ });- return apiKey;- });+ const runCursorJson: TextGenerationOperations.Runner = Effect.fn(+ "CursorTextGeneration.runCursorJson",+ )(+ function* (input) {+ const { operation, prompt, modelSelection } = input;- const runCursorJson: TextGenerationOperations.Runner = (input) => {- const { operation, prompt, modelSelection } = input;- return Effect.gen(function* () {const apiKey = yield* resolveCursorApiKey(operation);// The SDK loads sandbox.json independently of settingSources and lets it// expand the writable paths. Its public API cannot override that policy.@@ -187,22 +191,25 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu}return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);- }).pipe(- // Scope this call inside `withAccess`, so sign-out closes the agent before its store.- Effect.scoped,- (effect) => (withAccess ? withAccess(effect) : effect),- Effect.scoped,- Effect.mapError((cause) =>- isTextGenerationError(cause)- ? cause- : new TextGenerationError({- operation,- detail: "Cursor SDK text generation failed.",- cause,- }),- ),- );- };+ },+ (effect, input) => {+ const { operation } = input;+ return effect.pipe(+ Effect.scoped,+ (effect) => (withAccess ? withAccess(effect) : effect),+ Effect.scoped,+ Effect.mapError((cause) =>+ isTextGenerationError(cause)+ ? cause+ : new TextGenerationError({+ operation,+ detail: "Cursor SDK text generation failed.",+ cause,+ }),+ ),+ );+ },+ );return TextGenerationOperations.fromRunner("CursorTextGeneration",diff --git a/packages/provider-grok/src/server/acpSupport.ts b/packages/provider-grok/src/server/acpSupport.tsindex 726e28cd6ff..6ed3e6383ab 100644--- a/packages/provider-grok/src/server/acpSupport.ts+++ b/packages/provider-grok/src/server/acpSupport.ts@@ -145,37 +145,34 @@ export function grokApprovalOptions(];}-export const makeGrokAcpRuntime = (+export const makeGrokAcpRuntime = Effect.fn("GrokAcpSupport.makeGrokAcpRuntime")(function* (input: GrokAcpRuntimeInput,-): Effect.Effect<+): Effect.fn.Return<AcpSessionRuntime.AcpSessionRuntime["Service"],EffectAcpErrors.AcpError,ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope-> =>- Effect.gen(function* () {- const processGroupPlatform = yield* HostProcess.Platform.pipe(- Effect.provide(NodeServices.layer),- );- const acpContext = yield* Layer.build(- AcpSessionRuntime.layer({- ...input,- spawn: buildGrokAcpSpawnInput(- input.grokSettings,- input.cwd,- input.environment,- input.runtimeMode,- ),- authMethodId: resolveGrokAuthMethodId(input.environment),- cancelMeta: { ...input.cancelMeta, ...GROK_ACP_CANCEL_META },- initializeMeta: GROK_ACP_INITIALIZE_META,- ...grokAcpRuntimeProcessOwnership(processGroupPlatform),- }),- );- const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(- Effect.provide(acpContext),- );- return yield* makeXAiPromptCompletionRuntime(runtime);- });+> {+ const processGroupPlatform = yield* HostProcess.Platform.pipe(Effect.provide(NodeServices.layer));+ const acpContext = yield* Layer.build(+ AcpSessionRuntime.layer({+ ...input,+ spawn: buildGrokAcpSpawnInput(+ input.grokSettings,+ input.cwd,+ input.environment,+ input.runtimeMode,+ ),+ authMethodId: resolveGrokAuthMethodId(input.environment),+ cancelMeta: { ...input.cancelMeta, ...GROK_ACP_CANCEL_META },+ initializeMeta: GROK_ACP_INITIALIZE_META,+ ...grokAcpRuntimeProcessOwnership(processGroupPlatform),+ }),+ );+ const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(+ Effect.provide(acpContext),+ );+ return yield* makeXAiPromptCompletionRuntime(runtime);+});/*** It is the CLI's product name, not a model id the ACP accepts, so selecting itdiff --git a/packages/provider-grok/src/server/adapter.ts b/packages/provider-grok/src/server/adapter.tsindex ea8c3b101c5..6b7ec52ed8e 100644--- a/packages/provider-grok/src/server/adapter.ts+++ b/packages/provider-grok/src/server/adapter.ts@@ -264,22 +264,25 @@ export function makeGrokAcpAdapterFlavor(? window: undefined;},- applyModelSelection: ({ runtime, startResult, modelSelection }) =>- Effect.gen(function* () {- const legacy = startResult.initializeResult.protocolVersion === 1;- const options = legacy ? [] : yield* runtime.getConfigOptions;- const configuredModel = findModelConfigOption(options)?.currentValue;- return yield* applyGrokAcpModelSelection({- runtime: legacy- ? runtime- : { setSessionModel: (model) => runtime.setModel(model).pipe(Effect.as({})) },- currentModelId: legacy- ? currentGrokModelIdFromSessionSetup(startResult.sessionSetupResult)- : configuredModel,- requestedModelId: resolveGrokAcpBaseModelId(modelSelection.model),- mapError: (cause) => cause,- });- }),+ applyModelSelection: Effect.fn("GrokAdapter.applyModelSelection")(function* ({+ runtime,+ startResult,+ modelSelection,+ }) {+ const legacy = startResult.initializeResult.protocolVersion === 1;+ const options = legacy ? [] : yield* runtime.getConfigOptions;+ const configuredModel = findModelConfigOption(options)?.currentValue;+ return yield* applyGrokAcpModelSelection({+ runtime: legacy+ ? runtime+ : { setSessionModel: (model) => runtime.setModel(model).pipe(Effect.as({})) },+ currentModelId: legacy+ ? currentGrokModelIdFromSessionSetup(startResult.sessionSetupResult)+ : configuredModel,+ requestedModelId: resolveGrokAcpBaseModelId(modelSelection.model),+ mapError: (cause) => cause,+ });+ }),makeRuntime:options.makeRuntime ??(({ runtimePolicy, ...input }) =>diff --git a/packages/provider-grok/src/server/driver.ts b/packages/provider-grok/src/server/driver.tsindex 4b7fb8de3b7..0c9cfe62f18 100644--- a/packages/provider-grok/src/server/driver.ts+++ b/packages/provider-grok/src/server/driver.ts@@ -111,142 +111,148 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv, Path.Path>configSchema: GrokSettings,defaultConfig: (): GrokSettings => decodeGrokSettings({}),usage: grokUsageReader,- create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>- Effect.gen(function* () {- const crypto = yield* Crypto.Crypto;- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const httpClient = yield* HttpClient.HttpClient;- const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;- const fileSystem = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const host = yield* ProviderHost.ProviderHost;- const { cwd } = host.paths;- const processEnv = yield* mergeProviderInstanceEnvironment(environment);- const continuationIdentity = defaultProviderContinuationIdentity({- driverKind: DRIVER_KIND,- instanceId,- });- const stampIdentity = withInstanceIdentity({- instanceId,- driverKind: DRIVER_KIND,- displayName,- accentColor,- continuationGroupKey: continuationIdentity.continuationKey,- });- const effectiveConfig = { ...config, enabled } satisfies GrokSettings;- const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(- resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {- binaryPath: effectiveConfig.binaryPath,- env: processEnv,- }).pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- ),- );- const orchestrationAdapter = yield* GrokAdapterV2Driver.create({- instanceId,- displayName,- accentColor,- environment,- enabled,- config,+ create: Effect.fn("GrokDriver.create")(function* ({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }) {+ const crypto = yield* Crypto.Crypto;+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const httpClient = yield* HttpClient.HttpClient;+ const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const host = yield* ProviderHost.ProviderHost;+ const { cwd } = host.paths;+ const processEnv = yield* mergeProviderInstanceEnvironment(environment);+ const continuationIdentity = defaultProviderContinuationIdentity({+ driverKind: DRIVER_KIND,+ instanceId,+ });+ const stampIdentity = withInstanceIdentity({+ instanceId,+ driverKind: DRIVER_KIND,+ displayName,+ accentColor,+ continuationGroupKey: continuationIdentity.continuationKey,+ });+ const effectiveConfig = { ...config, enabled } satisfies GrokSettings;+ const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(+ resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {+ binaryPath: effectiveConfig.binaryPath,+ env: processEnv,}).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to build Grok orchestration adapter.",- cause,- }),- ),- );- const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);-- const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv, cwd).pipe(- Effect.flatMap((snapshot) =>- effectiveConfig.enabled && snapshot.installed && snapshot.auth.status === "authenticated"- ? readGrokAccount(processEnv).pipe(- Effect.map(({ email, usageLimits }) => ({- ...snapshot,- auth: email ? { ...snapshot.auth, email } : snapshot.auth,- usageLimits,- })),- )- : Effect.succeed(snapshot),- ),- Effect.map(stampIdentity),- Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),Effect.provideService(FileSystem.FileSystem, fileSystem),Effect.provideService(Path.Path, path),- Effect.provideService(Crypto.Crypto, crypto),- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- );+ ),+ );+ const orchestrationAdapter = yield* GrokAdapterV2Driver.create({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to build Grok orchestration adapter.",+ cause,+ }),+ ),+ );+ const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);- const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);- const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({- resolveMaintenance,- getSettings: snapshotSettings.getSettings,- streamSettings: snapshotSettings.streamSettings,- haveSettingsChanged: haveProviderSnapshotSettingsChanged,- initialSnapshot: (settings) =>- buildInitialGrokProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),- checkProvider,- enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>- resolveMaintenance().pipe(- Effect.flatMap((maintenanceCapabilities) =>- enrichGrokSnapshot({- snapshot: currentSnapshot,- maintenanceCapabilities,- enableProviderUpdateChecks: settings.enableProviderUpdateChecks,- publishSnapshot,- }),- ),- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),- ),- }).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to build Grok snapshot.",- cause,+ const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv, cwd).pipe(+ Effect.flatMap((snapshot) =>+ effectiveConfig.enabled && snapshot.installed && snapshot.auth.status === "authenticated"+ ? readGrokAccount(processEnv).pipe(+ Effect.map(({ email, usageLimits }) => ({+ ...snapshot,+ auth: email ? { ...snapshot.auth, email } : snapshot.auth,+ usageLimits,+ })),+ )+ : Effect.succeed(snapshot),+ ),+ Effect.map(stampIdentity),+ Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ Effect.provideService(Crypto.Crypto, crypto),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ );++ const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);+ const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({+ resolveMaintenance,+ getSettings: snapshotSettings.getSettings,+ streamSettings: snapshotSettings.streamSettings,+ haveSettingsChanged: haveProviderSnapshotSettingsChanged,+ initialSnapshot: (settings) =>+ buildInitialGrokProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),+ checkProvider,+ enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>+ resolveMaintenance().pipe(+ Effect.flatMap((maintenanceCapabilities) =>+ enrichGrokSnapshot({+ snapshot: currentSnapshot,+ maintenanceCapabilities,+ enableProviderUpdateChecks: settings.enableProviderUpdateChecks,+ publishSnapshot,}),+ ),+ Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),),- );- const snapshotForCwd = (workspaceCwd: string) =>- !effectiveConfig.enabled- ? snapshot.getSnapshot- : Effect.all([- snapshot.getSnapshot,- discoverGrokSkills(effectiveConfig, processEnv, workspaceCwd).pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: `Failed to discover Grok skills for '${workspaceCwd}'`,- cause,- }),- ),+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to build Grok snapshot.",+ cause,+ }),+ ),+ );+ const snapshotForCwd = (workspaceCwd: string) =>+ !effectiveConfig.enabled+ ? snapshot.getSnapshot+ : Effect.all([+ snapshot.getSnapshot,+ discoverGrokSkills(effectiveConfig, processEnv, workspaceCwd).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: `Failed to discover Grok skills for '${workspaceCwd}'`,+ cause,+ }),),- ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })));+ ),+ ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })));- return {- instanceId,- driverKind: DRIVER_KIND,- continuationIdentity,- displayName,- accentColor,- enabled,- snapshot,- snapshotForCwd,- orchestrationAdapter,- textGeneration,- } satisfies ProviderInstance;- }),+ return {+ instanceId,+ driverKind: DRIVER_KIND,+ continuationIdentity,+ displayName,+ accentColor,+ enabled,+ snapshot,+ snapshotForCwd,+ orchestrationAdapter,+ textGeneration,+ } satisfies ProviderInstance;+ }),};diff --git a/packages/provider-grok/src/server/status.ts b/packages/provider-grok/src/server/status.tsindex 65322c04a38..825f8080599 100644--- a/packages/provider-grok/src/server/status.ts+++ b/packages/provider-grok/src/server/status.ts@@ -71,44 +71,42 @@ const GROK_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [},];-export function buildInitialGrokProviderSnapshot(- grokSettings: GrokSettings,-): Effect.Effect<ServerProviderDraft> {- return Effect.gen(function* () {- const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);- const models = grokModelsFromSettings(grokSettings.customModels);-- if (!grokSettings.enabled) {- return buildServerProvider({- presentation: GROK_PRESENTATION,- enabled: false,- checkedAt,- models,- probe: {- installed: false,- version: null,- status: "warning",- auth: { status: "unknown" },- message: "Grok is disabled in T3 Code settings.",- },- });- }+export const buildInitialGrokProviderSnapshot = Effect.fn(+ "GrokProviderStatus.buildInitialGrokProviderSnapshot",+)(function* (grokSettings: GrokSettings): Effect.fn.Return<ServerProviderDraft> {+ const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);+ const models = grokModelsFromSettings(grokSettings.customModels);+ if (!grokSettings.enabled) {return buildServerProvider({presentation: GROK_PRESENTATION,- enabled: true,+ enabled: false,checkedAt,models,probe: {- installed: true,+ installed: false,version: null,status: "warning",auth: { status: "unknown" },- message: "Checking Grok CLI availability...",+ message: "Grok is disabled in T3 Code settings.",},});+ }++ return buildServerProvider({+ presentation: GROK_PRESENTATION,+ enabled: true,+ checkedAt,+ models,+ probe: {+ installed: true,+ version: null,+ status: "warning",+ auth: { status: "unknown" },+ message: "Checking Grok CLI availability...",+ },});-}+});function grokModelsFromSettings(customModels: ReadonlyArray<CustomModelSetting> | undefined,@@ -287,22 +285,21 @@ function displayNameFromGrokModelSlug(slug: string): string {.join(" ");}-const runGrokCliCommand = (+const runGrokCliCommand = Effect.fn("GrokProviderStatus.runGrokCliCommand")(function* (grokSettings: GrokSettings,args: ReadonlyArray<string>,environment: NodeJS.ProcessEnv,-) =>- Effect.gen(function* () {- const command = grokSettings.binaryPath || "grok";- const spawnCommand = yield* resolveSpawnCommand(command, args, { env: environment });- return yield* spawnAndCollect(- command,- ChildProcess.make(spawnCommand.command, spawnCommand.args, {- env: environment,- shell: spawnCommand.shell,- }),- );- });+) {+ const command = grokSettings.binaryPath || "grok";+ const spawnCommand = yield* resolveSpawnCommand(command, args, { env: environment });+ return yield* spawnAndCollect(+ command,+ ChildProcess.make(spawnCommand.command, spawnCommand.args, {+ env: environment,+ shell: spawnCommand.shell,+ }),+ );+});const decodeAvailableCommands = Schema.decodeUnknownOption(Schema.Array(Schema.Unknown));const decodeAvailableCommand = Schema.decodeUnknownOption(@@ -343,23 +340,21 @@ export function grokSlashCommandsFromInitialize(* This never calls `authenticate` or `session/new`, so it cannot open a browser login or* boot the workspace's MCP servers.*/-const discoverGrokMetadataViaAcpInitialize = (- grokSettings: GrokSettings,- environment: NodeJS.ProcessEnv,-) =>- Effect.gen(function* () {- const acp = yield* makeGrokAcpRuntime({- grokSettings,- environment,- cwd: process.cwd(),- clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },- });- const initialized = yield* acp.initialize();- return {- models: buildGrokModelsFromSessionModelState(sessionModelStateFromInitialize(initialized)),- slashCommands: grokSlashCommandsFromInitialize(initialized),- };- }).pipe(Effect.scoped);+const discoverGrokMetadataViaAcpInitialize = Effect.fn(+ "GrokProviderStatus.discoverGrokMetadataViaAcpInitialize",+)(function* (grokSettings: GrokSettings, environment: NodeJS.ProcessEnv) {+ const acp = yield* makeGrokAcpRuntime({+ grokSettings,+ environment,+ cwd: process.cwd(),+ clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },+ });+ const initialized = yield* acp.initialize();+ return {+ models: buildGrokModelsFromSessionModelState(sessionModelStateFromInitialize(initialized)),+ slashCommands: grokSlashCommandsFromInitialize(initialized),+ };+}, Effect.scoped);export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (grokSettings: GrokSettings,diff --git a/packages/provider-grok/src/server/textGeneration.ts b/packages/provider-grok/src/server/textGeneration.tsindex 7edf34963ae..9907ad14413 100644--- a/packages/provider-grok/src/server/textGeneration.ts+++ b/packages/provider-grok/src/server/textGeneration.ts@@ -30,9 +30,10 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functiconst crypto = yield* Crypto.Crypto;const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const runGrokJson: TextGenerationOperations.Runner = (request) => {- const { operation, cwd, prompt, modelSelection } = request;- return Effect.gen(function* () {+ const runGrokJson: TextGenerationOperations.Runner = Effect.fn("GrokTextGeneration.runGrokJson")(+ function* (request) {+ const { operation, cwd, prompt, modelSelection } = request;+const outputRef = yield* Ref.make("");const runtime = yield* makeGrokAcpRuntime({grokSettings,@@ -115,19 +116,23 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi}return yield* TextGenerationOperations.decodeJsonReply(request, "Grok Agent", trimmed);- }).pipe(- Effect.mapError((cause) =>- isTextGenerationError(cause)- ? cause- : new TextGenerationError({- operation,- detail: "Grok ACP text generation failed.",- cause,- }),- ),- Effect.scoped,- );- };+ },+ (effect, request) => {+ const { operation } = request;+ return effect.pipe(+ Effect.mapError((cause) =>+ isTextGenerationError(cause)+ ? cause+ : new TextGenerationError({+ operation,+ detail: "Grok ACP text generation failed.",+ cause,+ }),+ ),+ Effect.scoped,+ );+ },+ );return TextGenerationOperations.fromRunner("GrokTextGeneration",diff --git a/packages/provider-grok/src/server/xaiAcpExtension.ts b/packages/provider-grok/src/server/xaiAcpExtension.tsindex c392b88cb0d..56fe64142d6 100644--- a/packages/provider-grok/src/server/xaiAcpExtension.ts+++ b/packages/provider-grok/src/server/xaiAcpExtension.ts@@ -1536,58 +1536,57 @@ export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletion);}): runtime.handleExtNotification(method, payload, handler),- prompt: (payload, promptOptions?) =>- Effect.gen(function* () {- const started = yield* runtime.start();- const promptId = yield* allocatePromptFallbackId;- const fallback = yield* registerXAiPromptCompletionFallback(- pendingXAiPromptCompletionsRef,- started.sessionId,- promptId,- );- const cancelledResponse = promptResponseFromXAi({- sessionId: started.sessionId,- promptId: fallback.promptId,- stopReason: "cancelled",- agentResult: null,- });- const promptRpcFiber = yield* runtime- .prompt(- {- ...payload,- _meta: {- ...payload._meta,- promptId: fallback.promptId,- requestId: fallback.promptId,- },+ prompt: Effect.fn("xaiAcpExtension.prompt")(function* (payload, promptOptions?) {+ const started = yield* runtime.start();+ const promptId = yield* allocatePromptFallbackId;+ const fallback = yield* registerXAiPromptCompletionFallback(+ pendingXAiPromptCompletionsRef,+ started.sessionId,+ promptId,+ );+ const cancelledResponse = promptResponseFromXAi({+ sessionId: started.sessionId,+ promptId: fallback.promptId,+ stopReason: "cancelled",+ agentResult: null,+ });+ const promptRpcFiber = yield* runtime+ .prompt(+ {+ ...payload,+ _meta: {+ ...payload._meta,+ promptId: fallback.promptId,+ requestId: fallback.promptId,},- promptOptions,- )- .pipe(Effect.forkChild);- return yield* Effect.raceFirst(- Fiber.join(promptRpcFiber).pipe(- Effect.catchCause((cause) =>- Cause.hasInterruptsOnly(cause)- ? Effect.succeed(cancelledResponse)- : Effect.failCause(cause),- ),- ),- Deferred.await(fallback.deferred),- ).pipe(- Effect.tap((response) =>- rememberCompletedXAiPromptId(completedXAiPromptIdsRef, response, fallback.promptId),+ },+ promptOptions,+ )+ .pipe(Effect.forkChild);+ return yield* Effect.raceFirst(+ Fiber.join(promptRpcFiber).pipe(+ Effect.catchCause((cause) =>+ Cause.hasInterruptsOnly(cause)+ ? Effect.succeed(cancelledResponse)+ : Effect.failCause(cause),),- Effect.ensuring(- Effect.gen(function* () {- yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);- yield* unregisterXAiPromptCompletionFallback(- pendingXAiPromptCompletionsRef,- fallback.deferred,- );- }),- ),- );- }),+ ),+ Deferred.await(fallback.deferred),+ ).pipe(+ Effect.tap((response) =>+ rememberCompletedXAiPromptId(completedXAiPromptIdsRef, response, fallback.promptId),+ ),+ Effect.ensuring(+ Effect.gen(function* () {+ yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);+ yield* unregisterXAiPromptCompletionFallback(+ pendingXAiPromptCompletionsRef,+ fallback.deferred,+ );+ }),+ ),+ );+ }),cancel: Effect.gen(function* () {// Do not call start here: cancellation must be able to reach the// underlying runtime when startup is stalled.diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.tsindex d762c85d976..202c68089c7 100644--- a/packages/provider-muse/src/server/adapter.ts+++ b/packages/provider-muse/src/server/adapter.ts@@ -2141,8 +2141,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (),),compactThread: (args) => start(args, true).pipe(commands.withPermits(1)),- steerTurn: (args) =>- Effect.gen(function* () {+ steerTurn: Effect.fn("MuseAdapter.steerTurn")(+ function* (args) {const turn = active;if (!turn ||@@ -2158,20 +2158,23 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (}).pipe(Effect.flatMap((value) => decode(MuseTurnStartResult, value)));if (result.turnId !== turn.nativeId)return yield* protocolError("Muse steering targeted a different turn");- }).pipe(- commands.withPermits(1),- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterSteerRunError({- driver: MUSE_PROVIDER,- providerThreadId: args.providerThread.id,- providerTurnId: args.providerTurnId,- cause,- }),+ },+ (effect, args) =>+ effect.pipe(+ commands.withPermits(1),+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterSteerRunError({+ driver: MUSE_PROVIDER,+ providerThreadId: args.providerThread.id,+ providerTurnId: args.providerTurnId,+ cause,+ }),+ ),),- ),- interruptTurn: (args) =>- Effect.gen(function* () {+ ),+ interruptTurn: Effect.fn("MuseAdapter.interruptTurn")(+ function* (args) {const turn = active;if (!turn ||@@ -2207,20 +2210,23 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (Effect.mapError((cause) => protocolError("Muse did not confirm interruption", cause)),Effect.onError((cause) => eventPermit.withPermits(1)(failHost(cause))),);- }).pipe(- commands.withPermits(1),- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterInterruptError({- driver: MUSE_PROVIDER,- providerThreadId: args.providerThread.id,- providerTurnId: args.providerTurnId,- cause,- }),+ },+ (effect, args) =>+ effect.pipe(+ commands.withPermits(1),+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterInterruptError({+ driver: MUSE_PROVIDER,+ providerThreadId: args.providerThread.id,+ providerTurnId: args.providerTurnId,+ cause,+ }),+ ),),- ),- respondToRuntimeRequest: (args) =>- Effect.gen(function* () {+ ),+ respondToRuntimeRequest: Effect.fn("MuseAdapter.respondToRuntimeRequest")(+ function* (args) {const entry = pending.get(args.requestId);if (!entry) return yield* protocolError("This Muse request is no longer pending");if (entry.native.type === "approval") yield* decideApproval(entry, args.decision);@@ -2261,16 +2267,19 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (answers,}).pipe(Effect.tapError(() => Effect.sync(() => delete entry.response)));}- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({- driver: MUSE_PROVIDER,- requestId: args.requestId,- cause,- }),+ },+ (effect, args) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({+ driver: MUSE_PROVIDER,+ requestId: args.requestId,+ cause,+ }),+ ),),- ),+ ),readThreadSnapshot: (args) =>(!validateThread(args.providerThread)? protocolError("Snapshot requested for a different Muse thread")diff --git a/packages/provider-muse/src/server/driver.ts b/packages/provider-muse/src/server/driver.tsindex bf0024a0097..9a39487a5a2 100644--- a/packages/provider-muse/src/server/driver.ts+++ b/packages/provider-muse/src/server/driver.ts@@ -58,136 +58,140 @@ export const MuseDriver: ProviderDriver<MuseSettings, MuseDriverEnv> = {metadata: { displayName: "Muse Code", supportsMultipleInstances: true },configSchema: MuseSettings,defaultConfig: () => decodeMuseSettings({}),- create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>- Effect.gen(function* () {- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const fileSystem = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const httpClient = yield* HttpClient.HttpClient;- const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;- const host = yield* ProviderHost.ProviderHost;- const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;- const { cwd } = host.paths;- const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;- const hostEnvironment = yield* HostProcess.Environment;- // Drop an inherited META_API_KEY so Muse uses its login; an instance value still wins.- const processEnvironment = yield* mergeProviderInstanceEnvironment(- environment,- makeMuseEnvironment(hostEnvironment),- );- const effectiveConfig = {- ...config,- enabled,- binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),- } satisfies MuseSettings;- const continuationIdentity = defaultProviderContinuationIdentity({- driverKind: DRIVER_KIND,- instanceId,- });- const stampIdentity = withInstanceIdentity({- instanceId,- driverKind: DRIVER_KIND,- displayName,- accentColor,- continuationGroupKey: continuationIdentity.continuationKey,- });- const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);- const resolveInstallation = yield* makeCachedProviderMaintenanceResolution(- resolveProviderMaintenanceCapabilitiesEffect(museMaintenance, {- binaryPath: effectiveConfig.binaryPath,- env: processEnvironment,- }).pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- ),- );- const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>- Effect.gen(function* () {- const capabilities = yield* resolveInstallation(options);- // The maintenance runner requests fresh capabilities around an explicit update- // and needs the native target version to verify that the command actually upgraded.- const latestVersion = options?.fresh- ? yield* latestMuseVersion(processEnvironment, { fresh: true }).pipe(- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.provideService(- ProviderLatestVersions.ProviderLatestVersions,- latestVersions,- ),- )- : undefined;- return latestVersion !== undefined ? { ...capabilities, latestVersion } : capabilities;- });- const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<MuseSettings>>({- // Status refresh respects update checks; explicit updates use the resolver below.- resolveMaintenance: (options) =>- host.settings.get.pipe(- Effect.orDie,- Effect.flatMap((settings) =>- settings.enableProviderUpdateChecks- ? resolveMaintenance(options)- : resolveInstallation(options),- ),- ),- getSettings: snapshotSettings.getSettings,- streamSettings: snapshotSettings.streamSettings,- haveSettingsChanged: haveProviderSnapshotSettingsChanged,- initialSnapshot: (settings) =>- makePendingMuseProvider(settings.provider).pipe(Effect.map(stampIdentity)),- checkProvider: checkMuseProviderStatus(effectiveConfig, processEnvironment, cwd).pipe(- Effect.map(stampIdentity),- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- ),- enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>- resolveMaintenance().pipe(- Effect.flatMap((maintenanceCapabilities) =>- enrichMuseSnapshot({- snapshot: currentSnapshot,- maintenanceCapabilities,- enableProviderUpdateChecks: settings.enableProviderUpdateChecks,- environment: processEnvironment,- }),- ),+ create: Effect.fn("MuseDriver.create")(function* ({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }) {+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const httpClient = yield* HttpClient.HttpClient;+ const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;+ const host = yield* ProviderHost.ProviderHost;+ const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;+ const { cwd } = host.paths;+ const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;+ const hostEnvironment = yield* HostProcess.Environment;+ // Drop an inherited META_API_KEY so Muse uses its login; an instance value still wins.+ const processEnvironment = yield* mergeProviderInstanceEnvironment(+ environment,+ makeMuseEnvironment(hostEnvironment),+ );+ const effectiveConfig = {+ ...config,+ enabled,+ binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),+ } satisfies MuseSettings;+ const continuationIdentity = defaultProviderContinuationIdentity({+ driverKind: DRIVER_KIND,+ instanceId,+ });+ const stampIdentity = withInstanceIdentity({+ instanceId,+ driverKind: DRIVER_KIND,+ displayName,+ accentColor,+ continuationGroupKey: continuationIdentity.continuationKey,+ });+ const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);+ const resolveInstallation = yield* makeCachedProviderMaintenanceResolution(+ resolveProviderMaintenanceCapabilitiesEffect(museMaintenance, {+ binaryPath: effectiveConfig.binaryPath,+ env: processEnvironment,+ }).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ ),+ );+ const resolveMaintenance = Effect.fn("MuseDriver.resolveMaintenance")(function* (options?: {+ readonly fresh?: boolean;+ }) {+ const capabilities = yield* resolveInstallation(options);+ // The maintenance runner requests fresh capabilities around an explicit update+ // and needs the native target version to verify that the command actually upgraded.+ const latestVersion = options?.fresh+ ? yield* latestMuseVersion(processEnvironment, { fresh: true }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient),Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),- Effect.flatMap(publishSnapshot),+ )+ : undefined;+ return latestVersion !== undefined ? { ...capabilities, latestVersion } : capabilities;+ });+ const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<MuseSettings>>({+ // Status refresh respects update checks; explicit updates use the resolver below.+ resolveMaintenance: (options) =>+ host.settings.get.pipe(+ Effect.orDie,+ Effect.flatMap((settings) =>+ settings.enableProviderUpdateChecks+ ? resolveMaintenance(options)+ : resolveInstallation(options),),- }).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to build Muse Code snapshot.",- cause,+ ),+ getSettings: snapshotSettings.getSettings,+ streamSettings: snapshotSettings.streamSettings,+ haveSettingsChanged: haveProviderSnapshotSettingsChanged,+ initialSnapshot: (settings) =>+ makePendingMuseProvider(settings.provider).pipe(Effect.map(stampIdentity)),+ checkProvider: checkMuseProviderStatus(effectiveConfig, processEnvironment, cwd).pipe(+ Effect.map(stampIdentity),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ ),+ enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>+ resolveMaintenance().pipe(+ Effect.flatMap((maintenanceCapabilities) =>+ enrichMuseSnapshot({+ snapshot: currentSnapshot,+ maintenanceCapabilities,+ enableProviderUpdateChecks: settings.enableProviderUpdateChecks,+ environment: processEnvironment,}),+ ),+ Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),+ Effect.flatMap(publishSnapshot),),- );- const modelCatalog = snapshot.getSnapshot.pipe(Effect.map((current) => current.models));- const orchestrationAdapter = yield* makeMuseAdapterV2({- instanceId,- settings: effectiveConfig,- environment: processEnvironment,- modelCatalog,- ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),- continuationRequests,- });- const textGeneration = yield* makeMuseTextGeneration(effectiveConfig, {- environment: processEnvironment,- modelCatalog,- });- return {- instanceId,- driverKind: DRIVER_KIND,- continuationIdentity,- displayName,- accentColor,- enabled,- snapshot: { ...snapshot, resolveMaintenance },- orchestrationAdapter,- textGeneration,- } satisfies ProviderInstance;- }),+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to build Muse Code snapshot.",+ cause,+ }),+ ),+ );+ const modelCatalog = snapshot.getSnapshot.pipe(Effect.map((current) => current.models));+ const orchestrationAdapter = yield* makeMuseAdapterV2({+ instanceId,+ settings: effectiveConfig,+ environment: processEnvironment,+ modelCatalog,+ ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),+ continuationRequests,+ });+ const textGeneration = yield* makeMuseTextGeneration(effectiveConfig, {+ environment: processEnvironment,+ modelCatalog,+ });+ return {+ instanceId,+ driverKind: DRIVER_KIND,+ continuationIdentity,+ displayName,+ accentColor,+ enabled,+ snapshot: { ...snapshot, resolveMaintenance },+ orchestrationAdapter,+ textGeneration,+ } satisfies ProviderInstance;+ }),};diff --git a/packages/provider-muse/src/server/maintenance.ts b/packages/provider-muse/src/server/maintenance.tsindex 8295fedd908..0a3a59de128 100644--- a/packages/provider-muse/src/server/maintenance.ts+++ b/packages/provider-muse/src/server/maintenance.ts@@ -39,47 +39,46 @@ export const compareMuseVersions = (current: string, latest: string) =>/** Only the official launcher owns an update channel; a standalone binary cannot update itself. */export const museMaintenance: ProviderMaintenanceCapabilitiesResolver = {- resolve: (context) =>- Effect.gen(function* () {- const manual = {- ...makeManualOnlyProviderMaintenanceCapabilities({ provider: DRIVER, packageName: null }),- compareVersions: compareMuseVersions,- };- if (!context || context.platform === "win32") return manual;- const fs = yield* FileSystem.FileSystem;- const isLauncher = yield* Effect.gen(function* () {- const stat = yield* fs.stat(context.realCommandPath);- if (Number(stat.size) > 128 * 1_024) return false;- const source = yield* fs.readFileString(context.realCommandPath);- return source.includes("muse-code/launcher-") && source.includes("MUSE_SYNC_UPDATE");- }).pipe(Effect.orElseSucceed(() => false));- if (!isLauncher) return manual;- // The launcher has no `update` subcommand. Its documented launch environment- // forces a synchronous refresh of this executable's own installation.- const updateEnv = {- ...(context.env.MUSE_CHANNEL ? { MUSE_CHANNEL: context.env.MUSE_CHANNEL } : {}),- MUSE_NO_AUTO_UPDATE: "0",- MUSE_SYNC_UPDATE: "1",- MUSE_UPDATE_INTERVAL_SECONDS: "0",- };- return {- ...makeProviderMaintenanceCapabilities({- provider: DRIVER,- packageName: null,- updateExecutable: context.resolvedCommandPath,- updateArgs: ["--version"],- updateCommand: [- ...Object.entries(updateEnv).map(([key, value]) => `${key}=${shellQuote(value)}`),- shellQuote(context.resolvedCommandPath),- "--version",- ].join(" "),- updateLockKey: `muse:${context.realCommandPath}`,- platform: context.platform,- env: { ...context.env, ...updateEnv },- }),- compareVersions: compareMuseVersions,- };- }),+ resolve: Effect.fn("MuseMaintenance.resolve")(function* (context) {+ const manual = {+ ...makeManualOnlyProviderMaintenanceCapabilities({ provider: DRIVER, packageName: null }),+ compareVersions: compareMuseVersions,+ };+ if (!context || context.platform === "win32") return manual;+ const fs = yield* FileSystem.FileSystem;+ const isLauncher = yield* Effect.gen(function* () {+ const stat = yield* fs.stat(context.realCommandPath);+ if (Number(stat.size) > 128 * 1_024) return false;+ const source = yield* fs.readFileString(context.realCommandPath);+ return source.includes("muse-code/launcher-") && source.includes("MUSE_SYNC_UPDATE");+ }).pipe(Effect.orElseSucceed(() => false));+ if (!isLauncher) return manual;+ // The launcher has no `update` subcommand. Its documented launch environment+ // forces a synchronous refresh of this executable's own installation.+ const updateEnv = {+ ...(context.env.MUSE_CHANNEL ? { MUSE_CHANNEL: context.env.MUSE_CHANNEL } : {}),+ MUSE_NO_AUTO_UPDATE: "0",+ MUSE_SYNC_UPDATE: "1",+ MUSE_UPDATE_INTERVAL_SECONDS: "0",+ };+ return {+ ...makeProviderMaintenanceCapabilities({+ provider: DRIVER,+ packageName: null,+ updateExecutable: context.resolvedCommandPath,+ updateArgs: ["--version"],+ updateCommand: [+ ...Object.entries(updateEnv).map(([key, value]) => `${key}=${shellQuote(value)}`),+ shellQuote(context.resolvedCommandPath),+ "--version",+ ].join(" "),+ updateLockKey: `muse:${context.realCommandPath}`,+ platform: context.platform,+ env: { ...context.env, ...updateEnv },+ }),+ compareVersions: compareMuseVersions,+ };+ }),};function shellQuote(word: string) {diff --git a/packages/provider-opencode/src/server/OpenCodeRuntime.ts b/packages/provider-opencode/src/server/OpenCodeRuntime.tsindex bff49126ce4..bd17cb81bcb 100644--- a/packages/provider-opencode/src/server/OpenCodeRuntime.ts+++ b/packages/provider-opencode/src/server/OpenCodeRuntime.ts@@ -604,8 +604,10 @@ const makeOpenCodeRuntime = Effect.gen(function* () {const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>resolveSpawnCommand(command, args, { ...(env ? { env } : {}), bypassNpmShim: true });- const runOpenCodeCommand: OpenCodeRuntime["Service"]["runOpenCodeCommand"] = (input) =>- Effect.gen(function* () {+ const runOpenCodeCommand: OpenCodeRuntime["Service"]["runOpenCodeCommand"] = Effect.fn(+ "OpenCodeRuntime.runOpenCodeCommand",+ )(+ function* (input) {const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);const child = yield* spawner.spawn(ChildProcess.make(spawnCommand.command, spawnCommand.args, {@@ -646,16 +648,19 @@ const makeOpenCodeRuntime = Effect.gen(function* () {stderr,code: exitCode,} satisfies OpenCodeCommandResult;- }).pipe(- Effect.scoped,- Effect.mapError((cause) =>- ensureRuntimeError(- "runOpenCodeCommand",- `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,- cause,+ },+ (effect, input) =>+ effect.pipe(+ Effect.scoped,+ Effect.mapError((cause) =>+ ensureRuntimeError(+ "runOpenCodeCommand",+ `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,+ cause,+ ),),),- );+ );const createOpenCodeSdkClient: OpenCodeRuntime["Service"]["createOpenCodeSdkClient"] = (input) =>createOpencodeClient({@@ -671,220 +676,219 @@ const makeOpenCodeRuntime = Effect.gen(function* () {throwOnError: true,});- const startServerAttempt: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = (input) =>- Effect.gen(function* () {- const runtimeScope = yield* Scope.Scope;-- const hostname = input.hostname ?? DEFAULT_HOSTNAME;- const port =- input.port ??- (yield* netService.findAvailablePort(0).pipe(- Effect.mapError(- (cause) =>- new OpenCodeRuntimeError({- operation: "startOpenCodeServerProcess",- detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,- cause,- }),- ),- ));- const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;- const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];- const launch = yield* agentScope.wrap({- command: input.binaryPath,- args,- name: "opencode",- env: input.environment,- });- const spawnCommand = yield* resolveCommand(launch.command, launch.args, input.environment);- const serverPassword = resolveOpenCodeServerPassword({- external: false,- ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),- ...(input.environment !== undefined ? { environment: input.environment } : {}),- });-- // Scopes close in reverse order. Forking this before the group kill is- // registered forgets the ledger entry only once the group is stopped.- const ledgerScope = yield* Scope.fork(runtimeScope);- const child = yield* spawner- .spawn(- ChildProcess.make(spawnCommand.command, spawnCommand.args, {- detached: hostPlatform !== "win32",- shell: spawnCommand.shell,- env: {- ...input.environment,- ...(serverPassword !== undefined ? { OPENCODE_SERVER_PASSWORD: serverPassword } : {}),- // The value is set explicitly (rather than relying on inheritance) because- // `extendEnv` is false whenever `input.environment` is provided.- OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment),- },- extendEnv: input.environment === undefined,- }),- )- .pipe(- Effect.provideService(Scope.Scope, runtimeScope),- Effect.mapError(- (cause) =>- new OpenCodeRuntimeError({- operation: "startOpenCodeServerProcess",- detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,- cause,- }),- ),- );-- const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>- hostPlatform === "win32"- ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)- : Effect.sync(() => {- try {- signalProcessGroup(Number(child.pid), signal);- } catch {}- });- const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(- Effect.andThen(Effect.sleep("1 second")),- Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),- Effect.ignore,- );- // Registered before recording, so an interrupt while the ledger writes- // still stops the group.- yield* Scope.addFinalizer(runtimeScope, terminateChild);- const forgetServer = yield* serverLedger.track({ pid: Number(child.pid), port, args });- yield* Scope.addFinalizer(ledgerScope, forgetServer);-- const stdoutRef = yield* Ref.make<string | null>("");- const stderrRef = yield* Ref.make<string | null>("");- const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();-- const setReadyFromStdoutChunk = (chunk: string) =>- Ref.modify(stdoutRef, (stdout) => {- if (stdout === null) {- return [null, null] as const;- }- const nextStdout = `${stdout}${chunk}`;- return [- parseServerUrlFromOutput(nextStdout),- nextStdout.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),- ] as const;- }).pipe(- Effect.flatMap((parsed) =>- parsed ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore) : Effect.void,- ),- );+ const startServerAttempt: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = Effect.fn(+ "OpenCodeRuntime.startServerAttempt",+ )(function* (input) {+ const runtimeScope = yield* Scope.Scope;++ const hostname = input.hostname ?? DEFAULT_HOSTNAME;+ const port =+ input.port ??+ (yield* netService.findAvailablePort(0).pipe(+ Effect.mapError(+ (cause) =>+ new OpenCodeRuntimeError({+ operation: "startOpenCodeServerProcess",+ detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,+ cause,+ }),+ ),+ ));+ const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;+ const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];+ const launch = yield* agentScope.wrap({+ command: input.binaryPath,+ args,+ name: "opencode",+ env: input.environment,+ });+ const spawnCommand = yield* resolveCommand(launch.command, launch.args, input.environment);+ const serverPassword = resolveOpenCodeServerPassword({+ external: false,+ ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),+ ...(input.environment !== undefined ? { environment: input.environment } : {}),+ });- const stdoutFiber = yield* child.stdout.pipe(- Stream.decodeText(),- Stream.runForEach(setReadyFromStdoutChunk),- Effect.ignore,- Effect.forkIn(runtimeScope),- );- const stderrFiber = yield* child.stderr.pipe(- Stream.decodeText(),- Stream.runForEach((chunk) =>- Ref.update(stderrRef, (stderr) =>- stderr === null- ? null- : `${stderr}${chunk}`.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),- ),+ // Scopes close in reverse order. Forking this before the group kill is+ // registered forgets the ledger entry only once the group is stopped.+ const ledgerScope = yield* Scope.fork(runtimeScope);+ const child = yield* spawner+ .spawn(+ ChildProcess.make(spawnCommand.command, spawnCommand.args, {+ detached: hostPlatform !== "win32",+ shell: spawnCommand.shell,+ env: {+ ...input.environment,+ ...(serverPassword !== undefined ? { OPENCODE_SERVER_PASSWORD: serverPassword } : {}),+ // The value is set explicitly (rather than relying on inheritance) because+ // `extendEnv` is false whenever `input.environment` is provided.+ OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment),+ },+ extendEnv: input.environment === undefined,+ }),+ )+ .pipe(+ Effect.provideService(Scope.Scope, runtimeScope),+ Effect.mapError(+ (cause) =>+ new OpenCodeRuntimeError({+ operation: "startOpenCodeServerProcess",+ detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,+ cause,+ }),),- Effect.ignore,- Effect.forkIn(runtimeScope),);- const exitFiber = yield* child.exitCode.pipe(- Effect.flatMap((code) =>- Effect.gen(function* () {- // Allow trailing diagnostics to drain, but descendants can keep pipes open.- const drained = yield* Fiber.joinAll([stdoutFiber, stderrFiber]).pipe(- Effect.timeoutOption(OPENCODE_SERVER_EXIT_DRAIN_TIMEOUT),- );- if (Option.isNone(drained)) {- yield* Fiber.interruptAll([stdoutFiber, stderrFiber]);- }- const stdout = (yield* Ref.get(stdoutRef)) ?? "";- const stderr = (yield* Ref.get(stderrRef)) ?? "";- const exitCode = Number(code);- const reason = classifyStartupExit(stderr);- yield* Deferred.fail(- readyDeferred,- new OpenCodeRuntimeError({- operation: "startOpenCodeServerProcess",- ...(reason ? { reason } : {}),- detail: [- `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,- stdout.trim() ? `stdout:\n${stdout.trim()}` : null,- stderr.trim() ? `stderr:\n${stderr.trim()}` : null,- ]- .filter(Boolean)- .join("\n\n"),- cause: { exitCode, stdout, stderr },- }),- ).pipe(Effect.ignore);- }),+ const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>+ hostPlatform === "win32"+ ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)+ : Effect.sync(() => {+ try {+ signalProcessGroup(Number(child.pid), signal);+ } catch {}+ });+ const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(+ Effect.andThen(Effect.sleep("1 second")),+ Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),+ Effect.ignore,+ );+ // Registered before recording, so an interrupt while the ledger writes+ // still stops the group.+ yield* Scope.addFinalizer(runtimeScope, terminateChild);+ const forgetServer = yield* serverLedger.track({ pid: Number(child.pid), port, args });+ yield* Scope.addFinalizer(ledgerScope, forgetServer);++ const stdoutRef = yield* Ref.make<string | null>("");+ const stderrRef = yield* Ref.make<string | null>("");+ const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();++ const setReadyFromStdoutChunk = (chunk: string) =>+ Ref.modify(stdoutRef, (stdout) => {+ if (stdout === null) {+ return [null, null] as const;+ }+ const nextStdout = `${stdout}${chunk}`;+ return [+ parseServerUrlFromOutput(nextStdout),+ nextStdout.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),+ ] as const;+ }).pipe(+ Effect.flatMap((parsed) =>+ parsed ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore) : Effect.void,),- Effect.ignore,- Effect.forkIn(runtimeScope),);- const readyExit = yield* Effect.exit(- Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),- );+ const stdoutFiber = yield* child.stdout.pipe(+ Stream.decodeText(),+ Stream.runForEach(setReadyFromStdoutChunk),+ Effect.ignore,+ Effect.forkIn(runtimeScope),+ );+ const stderrFiber = yield* child.stderr.pipe(+ Stream.decodeText(),+ Stream.runForEach((chunk) =>+ Ref.update(stderrRef, (stderr) =>+ stderr === null+ ? null+ : `${stderr}${chunk}`.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),+ ),+ ),+ Effect.ignore,+ Effect.forkIn(runtimeScope),+ );- if (Exit.isFailure(readyExit) || Option.isNone(readyExit.value)) {- yield* Fiber.interruptAll([stdoutFiber, stderrFiber, exitFiber]).pipe(Effect.ignore);- }+ const exitFiber = yield* child.exitCode.pipe(+ Effect.flatMap((code) =>+ Effect.gen(function* () {+ // Allow trailing diagnostics to drain, but descendants can keep pipes open.+ const drained = yield* Fiber.joinAll([stdoutFiber, stderrFiber]).pipe(+ Effect.timeoutOption(OPENCODE_SERVER_EXIT_DRAIN_TIMEOUT),+ );+ if (Option.isNone(drained)) {+ yield* Fiber.interruptAll([stdoutFiber, stderrFiber]);+ }+ const stdout = (yield* Ref.get(stdoutRef)) ?? "";+ const stderr = (yield* Ref.get(stderrRef)) ?? "";+ const exitCode = Number(code);+ const reason = classifyStartupExit(stderr);+ yield* Deferred.fail(+ readyDeferred,+ new OpenCodeRuntimeError({+ operation: "startOpenCodeServerProcess",+ ...(reason ? { reason } : {}),+ detail: [+ `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,+ stdout.trim() ? `stdout:\n${stdout.trim()}` : null,+ stderr.trim() ? `stderr:\n${stderr.trim()}` : null,+ ]+ .filter(Boolean)+ .join("\n\n"),+ cause: { exitCode, stdout, stderr },+ }),+ ).pipe(Effect.ignore);+ }),+ ),+ Effect.ignore,+ Effect.forkIn(runtimeScope),+ );- if (Exit.isFailure(readyExit)) {- const squashed = Cause.squash(readyExit.cause);- return yield* ensureRuntimeError(- "startOpenCodeServerProcess",- `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,- squashed,- );- }+ const readyExit = yield* Effect.exit(+ Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),+ );- const readyOption = readyExit.value;- if (Option.isNone(readyOption)) {- return yield* new OpenCodeRuntimeError({- operation: "startOpenCodeServerProcess",- detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,- });- }+ if (Exit.isFailure(readyExit) || Option.isNone(readyExit.value)) {+ yield* Fiber.interruptAll([stdoutFiber, stderrFiber, exitFiber]).pipe(Effect.ignore);+ }- // Keep draining both pipes until the process scope closes. Stopping the- // readers can block OpenCode when its output buffers fill. Startup output- // is no longer needed, so discard later output instead of retaining it.- yield* Ref.set(stdoutRef, null);- yield* Ref.set(stderrRef, null);-- const url = readyOption.value;- const version = yield* (- input.verify?.(url) ??- verifyOpenCodeServerVersion(- createOpenCodeSdkClient({- baseUrl: url,- directory: input.directory,- ...(serverPassword !== undefined ? { serverPassword } : {}),- }),- )+ if (Exit.isFailure(readyExit)) {+ const squashed = Cause.squash(readyExit.cause);+ return yield* ensureRuntimeError(+ "startOpenCodeServerProcess",+ `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,+ squashed,);+ }- return {- url,- ...(serverPassword !== undefined ? { serverPassword } : {}),- version,- isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)),- exitCode: child.exitCode.pipe(- Effect.map(Number),- Effect.orElseSucceed(() => 0),- ),- } satisfies OpenCodeServerProcess;- });+ const readyOption = readyExit.value;+ if (Option.isNone(readyOption)) {+ return yield* new OpenCodeRuntimeError({+ operation: "startOpenCodeServerProcess",+ detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,+ });+ }- const startOpenCodeServerProcess: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = (- input,- ) =>- Effect.gen(function* () {+ // Keep draining both pipes until the process scope closes. Stopping the+ // readers can block OpenCode when its output buffers fill. Startup output+ // is no longer needed, so discard later output instead of retaining it.+ yield* Ref.set(stdoutRef, null);+ yield* Ref.set(stderrRef, null);++ const url = readyOption.value;+ const version = yield* (+ input.verify?.(url) ??+ verifyOpenCodeServerVersion(+ createOpenCodeSdkClient({+ baseUrl: url,+ directory: input.directory,+ ...(serverPassword !== undefined ? { serverPassword } : {}),+ }),+ )+ );++ return {+ url,+ ...(serverPassword !== undefined ? { serverPassword } : {}),+ version,+ isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)),+ exitCode: child.exitCode.pipe(+ Effect.map(Number),+ Effect.orElseSucceed(() => 0),+ ),+ } satisfies OpenCodeServerProcess;+ });++ const startOpenCodeServerProcess: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] =+ Effect.fn("OpenCodeRuntime.startOpenCodeServerProcess")(function* (input) {const ownerScope = yield* Scope.Scope;const attempt = Effect.gen(function* () {const attemptScope = yield* Scope.fork(ownerScope);@@ -1006,102 +1010,103 @@ const makeOpenCodeRuntime = Effect.gen(function* () {})),);- const loadInventoryFromCli: OpenCodeRuntime["Service"]["loadInventoryFromCli"] = (input) =>- Effect.gen(function* () {- const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});- const commandContext = { cwd: input.cwd, ...env };-- const runModelsCli = () =>- runOpenCodeCommand({- binaryPath: input.binaryPath,- args: ["models", "--verbose"],- ...commandContext,- }).pipe(Effect.exit);- const runAgentsCli = () =>- runOpenCodeCommand({- binaryPath: input.binaryPath,- args: ["agent", "list"],- ...commandContext,- }).pipe(Effect.exit);- const runSkillsCli = () =>- runOpenCodeCommand({- binaryPath: input.binaryPath,- args: ["debug", "skill"],- maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,- ...commandContext,- }).pipe(Effect.exit);-- // Every OpenCode CLI command opens the same shared SQLite database. Running them- // concurrently causes "database is locked" failures, so run them one at a time.- const [initialModelsResult, initialAgentsResult, initialSkillsResult] = yield* Effect.all(- [runModelsCli(), runAgentsCli(), runSkillsCli()],+ const loadInventoryFromCli: OpenCodeRuntime["Service"]["loadInventoryFromCli"] = Effect.fn(+ "OpenCodeRuntime.loadInventoryFromCli",+ )(function* (input) {+ const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});+ const commandContext = { cwd: input.cwd, ...env };++ const runModelsCli = () =>+ runOpenCodeCommand({+ binaryPath: input.binaryPath,+ args: ["models", "--verbose"],+ ...commandContext,+ }).pipe(Effect.exit);+ const runAgentsCli = () =>+ runOpenCodeCommand({+ binaryPath: input.binaryPath,+ args: ["agent", "list"],+ ...commandContext,+ }).pipe(Effect.exit);+ const runSkillsCli = () =>+ runOpenCodeCommand({+ binaryPath: input.binaryPath,+ args: ["debug", "skill"],+ maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,+ ...commandContext,+ }).pipe(Effect.exit);++ // Every OpenCode CLI command opens the same shared SQLite database. Running them+ // concurrently causes "database is locked" failures, so run them one at a time.+ const [initialModelsResult, initialAgentsResult, initialSkillsResult] = yield* Effect.all(+ [runModelsCli(), runAgentsCli(), runSkillsCli()],+ { concurrency: 1 },+ );+ let modelsResult = initialModelsResult;+ let agentsResult = initialAgentsResult;+ let skillsResult = initialSkillsResult;++ const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;+ const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;+ const needsSkillsRetry = skillsResult._tag === "Failure" || skillsResult.value.code !== 0;+ if (needsModelsRetry || needsAgentsRetry || needsSkillsRetry) {+ yield* Effect.sleep("1 second");+ const [m2, a2, s2] = yield* Effect.all(+ [+ needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),+ needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),+ needsSkillsRetry ? runSkillsCli() : Effect.succeed(skillsResult),+ ],{ concurrency: 1 },);- let modelsResult = initialModelsResult;- let agentsResult = initialAgentsResult;- let skillsResult = initialSkillsResult;-- const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;- const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;- const needsSkillsRetry = skillsResult._tag === "Failure" || skillsResult.value.code !== 0;- if (needsModelsRetry || needsAgentsRetry || needsSkillsRetry) {- yield* Effect.sleep("1 second");- const [m2, a2, s2] = yield* Effect.all(- [- needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),- needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),- needsSkillsRetry ? runSkillsCli() : Effect.succeed(skillsResult),- ],- { concurrency: 1 },- );- modelsResult = m2;- agentsResult = a2;- skillsResult = s2;- }-- if (modelsResult._tag === "Failure") {- const cause = Cause.squash(modelsResult.cause);- return yield* ensureRuntimeError(- "loadInventoryFromCli",- `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,- cause,- );- }- if (modelsResult.value.code !== 0) {- return yield* new OpenCodeRuntimeError({- operation: "loadInventoryFromCli",- detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,- });- }+ modelsResult = m2;+ agentsResult = a2;+ skillsResult = s2;+ }- const parsed = parseModelsCliOutput(modelsResult.value.stdout);- const connected = [...parsed.connected];- const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(- (provider) => ({- id: provider.id,- name: provider.name,- source: "config" as const,- env: [],- options: {},- models: provider.models,- }),+ if (modelsResult._tag === "Failure") {+ const cause = Cause.squash(modelsResult.cause);+ return yield* ensureRuntimeError(+ "loadInventoryFromCli",+ `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,+ cause,);+ }+ if (modelsResult.value.code !== 0) {+ return yield* new OpenCodeRuntimeError({+ operation: "loadInventoryFromCli",+ detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,+ });+ }- let agents: ReadonlyArray<Agent> = [];- if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {- agents = parseAgentListCliOutput(agentsResult.value.stdout);- }- let skills: ReadonlyArray<OpenCodeSkill> = [];- if (skillsResult._tag === "Success" && skillsResult.value.code === 0) {- skills = parseSkillsCliOutput(skillsResult.value.stdout);- }+ const parsed = parseModelsCliOutput(modelsResult.value.stdout);+ const connected = [...parsed.connected];+ const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(+ (provider) => ({+ id: provider.id,+ name: provider.name,+ source: "config" as const,+ env: [],+ options: {},+ models: provider.models,+ }),+ );- return {- providerList: { all: allProviders, default: {}, connected },- agents,- skills,- };- });+ let agents: ReadonlyArray<Agent> = [];+ if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {+ agents = parseAgentListCliOutput(agentsResult.value.stdout);+ }+ let skills: ReadonlyArray<OpenCodeSkill> = [];+ if (skillsResult._tag === "Success" && skillsResult.value.code === 0) {+ skills = parseSkillsCliOutput(skillsResult.value.stdout);+ }++ return {+ providerList: { all: allProviders, default: {}, connected },+ agents,+ skills,+ };+ });const loadSkillsFromCli: OpenCodeRuntime["Service"]["loadSkillsFromCli"] = (input) =>runOpenCodeCommand({diff --git a/packages/provider-opencode/src/server/OpenCodeServerLedger.ts b/packages/provider-opencode/src/server/OpenCodeServerLedger.tsindex 9248f22cb87..e5c1866d5e2 100644--- a/packages/provider-opencode/src/server/OpenCodeServerLedger.ts+++ b/packages/provider-opencode/src/server/OpenCodeServerLedger.ts@@ -99,26 +99,26 @@ export const make = Effect.fn("OpenCodeServerLedger.make")(function* (input: {const directory = path.join(input.stateDir, ENTRY_DIRECTORY);const recordable = platform === "linux" || platform === "darwin";- const observeLinux = (pid: number, group?: number) =>- Effect.gen(function* () {- const stat = yield* fs.readFileString(`/proc/${pid}/stat`);- const fields = stat- .slice(stat.lastIndexOf(")") + 2)- .trim()- .split(/\s+/);- const pgid = Number(fields[2]);- const startTime = fields[19];- if (!Number.isSafeInteger(pgid) || startTime === undefined) return undefined;- if (group !== undefined && pgid !== group) return undefined;- const cmdline = yield* fs.readFileString(`/proc/${pid}/cmdline`);- return {- pid,- pgid,- startTime,- command: cmdline.replace(/\0$/, "").replaceAll("\0", " "),- zombie: fields[0] === "Z",- } satisfies ObservedProcess;- });+ // A process-group scan calls this for every /proc entry; avoid a span per process.+ const observeLinux = Effect.fnUntraced(function* (pid: number, group?: number) {+ const stat = yield* fs.readFileString(`/proc/${pid}/stat`);+ const fields = stat+ .slice(stat.lastIndexOf(")") + 2)+ .trim()+ .split(/\s+/);+ const pgid = Number(fields[2]);+ const startTime = fields[19];+ if (!Number.isSafeInteger(pgid) || startTime === undefined) return undefined;+ if (group !== undefined && pgid !== group) return undefined;+ const cmdline = yield* fs.readFileString(`/proc/${pid}/cmdline`);+ return {+ pid,+ pgid,+ startTime,+ command: cmdline.replace(/\0$/, "").replaceAll("\0", " "),+ zombie: fields[0] === "Z",+ } satisfies ObservedProcess;+ });const psDarwin = (selection: ReadonlyArray<string>) =>spawner@@ -183,8 +183,8 @@ export const make = Effect.fn("OpenCodeServerLedger.make")(function* (input: {const owner =ownerProcess === undefined ? undefined : { pid: ownerPid, startTime: ownerProcess.startTime };- const track: OpenCodeServerLedger["Service"]["track"] = (server) =>- Effect.gen(function* () {+ const track: OpenCodeServerLedger["Service"]["track"] = Effect.fn("OpenCodeServerLedger.track")(+ function* (server) {if (!recordable) return Effect.void;const pgid = server.pid;// The spawned process leads the group. If it already exited (a wrapper@@ -232,53 +232,57 @@ export const make = Effect.fn("OpenCodeServerLedger.make")(function* (input: {Effect.logWarning("Could not forget a stopped OpenCode server", { cause }),),);- }).pipe(- Effect.catchCause((cause) =>- Effect.logWarning("Could not record an OpenCode server process", { cause }).pipe(- Effect.as(Effect.void),- ),+ },+ Effect.catchCause((cause) =>+ Effect.logWarning("Could not record an OpenCode server process", { cause }).pipe(+ Effect.as(Effect.void),),- );+ ),+ );// Signals only a group whose recorded member still has the same pid, start// time, group, and full command line, so a recycled pid is never touched.- const stopOrphan = (entry: OpenCodeServerEntry) =>- Effect.gen(function* () {- const observed = yield* observe(entry.pid);- if (- observed === undefined ||- observed.zombie ||- observed.startTime !== entry.startTime ||- observed.pgid !== entry.pgid ||- observed.command !== entry.command- ) {- return;- }- yield* Effect.logInfo("Stopping an OpenCode server left by a previous T3 Code server", {- pid: entry.pgid,- port: entry.port,- });- signalGroup(entry.pgid, "SIGTERM");- for (let attempt = 0; attempt < STOP_POLL_ATTEMPTS && groupExists(entry.pgid); attempt++) {- yield* Effect.sleep(STOP_POLL_INTERVAL);- }- // The group never emptied, so its pgid cannot have been reused.- if (groupExists(entry.pgid)) signalGroup(entry.pgid, "SIGKILL");+ const stopOrphan = Effect.fn("OpenCodeServerLedger.stopOrphan")(function* (+ entry: OpenCodeServerEntry,+ ) {+ const observed = yield* observe(entry.pid);+ if (+ observed === undefined ||+ observed.zombie ||+ observed.startTime !== entry.startTime ||+ observed.pgid !== entry.pgid ||+ observed.command !== entry.command+ ) {+ return;+ }+ yield* Effect.logInfo("Stopping an OpenCode server left by a previous T3 Code server", {+ pid: entry.pgid,+ port: entry.port,});+ signalGroup(entry.pgid, "SIGTERM");+ for (let attempt = 0; attempt < STOP_POLL_ATTEMPTS && groupExists(entry.pgid); attempt++) {+ yield* Effect.sleep(STOP_POLL_INTERVAL);+ }+ // The group never emptied, so its pgid cannot have been reused.+ if (groupExists(entry.pgid)) signalGroup(entry.pgid, "SIGKILL");+ });- const reapEntry = (entryPath: string) =>- Effect.gen(function* () {+ const reapEntry = Effect.fn("OpenCodeServerLedger.reapEntry")(+ function* (entryPath: string) {const entry = decodeEntry(yield* fs.readFileString(entryPath));if (Option.isSome(entry) && entry.value.stateDir === input.stateDir) {if (yield* isRunning(entry.value.owner)) return;yield* stopOrphan(entry.value);}yield* fs.remove(entryPath, { force: true });- }).pipe(- Effect.catchCause((cause) =>- Effect.logWarning("Could not clean up a recorded OpenCode server", { entryPath, cause }),+ },+ (effect, entryPath) =>+ effect.pipe(+ Effect.catchCause((cause) =>+ Effect.logWarning("Could not clean up a recorded OpenCode server", { entryPath, cause }),+ ),),- );+ );const reapOrphans = Effect.gen(function* () {const names = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.tsindex 4a73195d2dc..2d27f83a8ad 100644--- a/packages/provider-opencode/src/server/adapter.ts+++ b/packages/provider-opencode/src/server/adapter.ts@@ -1047,56 +1047,55 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function),);- const abortDescendants = (rootId: string) =>- Effect.gen(function* () {- const visited = new Set([rootId]);- const semaphore = Semaphore.makeUnsafe(8);- const visit = (- sessionId: string,- abort: boolean,- ): Effect.Effect<OpenCodeRuntime.OpenCodeRuntimeError | undefined> =>- Effect.gen(function* () {- const abortResult = abort- ? yield* sdkCall("session.abort", { sessionID: sessionId }, (signal) =>- client.session.abort({ sessionID: sessionId }, { signal }),- ).pipe(- semaphore.withPermit,- Effect.catchIf(isOpenCodeNotFound, () => Effect.void),- Effect.result,- )- : undefined;- const childrenResult = yield* sdkCall(- "session.children",- { sessionID: sessionId },- (signal) => client.session.children({ sessionID: sessionId }, { signal }),+ const abortDescendants = Effect.fn("OpencodeAdapter.abortDescendants")(function* (+ rootId: string,+ ) {+ const visited = new Set([rootId]);+ const semaphore = Semaphore.makeUnsafe(8);+ const visit = Effect.fn("OpencodeAdapter.visit")(function* (+ sessionId: string,+ abort: boolean,+ ): Effect.fn.Return<OpenCodeRuntime.OpenCodeRuntimeError | undefined> {+ const abortResult = abort+ ? yield* sdkCall("session.abort", { sessionID: sessionId }, (signal) =>+ client.session.abort({ sessionID: sessionId }, { signal }),).pipe(semaphore.withPermit,Effect.catchIf(isOpenCodeNotFound, () => Effect.void),Effect.result,- );- const firstFailure =- abortResult?._tag === "Failure" ? abortResult.failure : undefined;- if (childrenResult._tag === "Failure")- return firstFailure ?? childrenResult.failure;- const fresh = (childrenResult.success?.data ?? []).filter((child) => {- if (visited.has(child.id)) return false;- visited.add(child.id);- return true;- });- const failures = yield* Effect.forEach(fresh, (child) => visit(child.id, true), {- concurrency: 8,- });- return firstFailure ?? failures.find((failure) => failure !== undefined);- });- const failure = yield* visit(rootId, false);- if (failure) return yield* Effect.fail(failure);- }).pipe(Effect.timeout("15 seconds"));-- const updateProviderSession = (- status: OrchestrationV2ProviderSession["status"],- lastError: string | null = sessionEntity.lastError,- ) =>- Effect.gen(function* () {+ )+ : undefined;+ const childrenResult = yield* sdkCall(+ "session.children",+ { sessionID: sessionId },+ (signal) => client.session.children({ sessionID: sessionId }, { signal }),+ ).pipe(+ semaphore.withPermit,+ Effect.catchIf(isOpenCodeNotFound, () => Effect.void),+ Effect.result,+ );+ const firstFailure = abortResult?._tag === "Failure" ? abortResult.failure : undefined;+ if (childrenResult._tag === "Failure") return firstFailure ?? childrenResult.failure;+ const fresh = (childrenResult.success?.data ?? []).filter((child) => {+ if (visited.has(child.id)) return false;+ visited.add(child.id);+ return true;+ });+ const failures = yield* Effect.forEach(fresh, (child) => visit(child.id, true), {+ concurrency: 8,+ });+ return firstFailure ?? failures.find((failure) => failure !== undefined);+ });+ const failure = yield* visit(rootId, false);+ if (failure) return yield* Effect.fail(failure);+ }, Effect.timeout("15 seconds"));++ const updateProviderSession =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ status: OrchestrationV2ProviderSession["status"],+ lastError: string | null = sessionEntity.lastError,+ ) {const updatedAt = yield* DateTime.now;sessionEntity = { ...sessionEntity, status, lastError, updatedAt };yield* emitProviderEvent({@@ -1106,11 +1105,12 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function});});- const updateProviderThread = (- state: OpenCodeThreadState,- patch: Partial<OrchestrationV2ProviderThread>,- ) =>- Effect.gen(function* () {+ const updateProviderThread =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ state: OpenCodeThreadState,+ patch: Partial<OrchestrationV2ProviderThread>,+ ) {const updatedAt = yield* DateTime.now;state.providerThread = { ...state.providerThread, ...patch, updatedAt };yield* emitProviderEvent({@@ -2998,8 +2998,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(functionproviderSession: sessionEntity,events: Stream.fromEffectRepeat(Queue.take(events)),hasPendingBackgroundWork: Effect.sync(() => busySessionIds.size > 0),- ensureThread: (threadInput) =>- Effect.gen(function* () {+ ensureThread: Effect.fn("OpencodeAdapter.ensureThread")(+ function* (threadInput) {if (threadInput.existingProviderThread?.nativeThreadRef != null) {return yield* runtimeSession.resumeThread({providerThread: threadInput.existingProviderThread,@@ -3039,18 +3039,21 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function};registerThread(nativeSession, providerThread, null);return providerThread;- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterEnsureThreadError({- driver: OPENCODE_PROVIDER,- threadId: threadInput.threadId,- cause,- }),+ },+ (effect, threadInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterEnsureThreadError({+ driver: OPENCODE_PROVIDER,+ threadId: threadInput.threadId,+ cause,+ }),+ ),),- ),- resumeThread: (threadInput) =>- Effect.gen(function* () {+ ),+ resumeThread: Effect.fn("OpencodeAdapter.resumeThread")(+ function* (threadInput) {const sessionId = nativeThreadId(threadInput.providerThread);const response = yield* sdkCall("session.get", { sessionID: sessionId }, () =>client.session.get({ sessionID: sessionId }),@@ -3065,24 +3068,27 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function};registerThread(nativeSession, providerThread, null);return providerThread;- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterResumeThreadError({- driver: OPENCODE_PROVIDER,- providerSessionId: input.providerSessionId,- providerThreadId: threadInput.providerThread.id,- cause,- }),+ },+ (effect, threadInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterResumeThreadError({+ driver: OPENCODE_PROVIDER,+ providerSessionId: input.providerSessionId,+ providerThreadId: threadInput.providerThread.id,+ cause,+ }),+ ),),- ),+ ),compactThread: (turnInput) =>runtimeSession.startTurn({...turnInput,message: { ...turnInput.message, text: "/compact" },}),- startTurn: (turnInput) =>- Effect.gen(function* () {+ startTurn: Effect.fn("OpencodeAdapter.startTurn")(+ function* (turnInput) {if (nativeStreamFailure !== null) {return yield* protocolError("OpenCode event stream has ended; reconnect the provider session before starting another turn.",@@ -3279,20 +3285,23 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(functionyield* reconcilePromptAdmission(state, turn);}}- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterTurnStartError({- driver: OPENCODE_PROVIDER,- threadId: turnInput.threadId,- providerThreadId: turnInput.providerThread.id,- runId: turnInput.runId,- cause,- }),+ },+ (effect, turnInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterTurnStartError({+ driver: OPENCODE_PROVIDER,+ threadId: turnInput.threadId,+ providerThreadId: turnInput.providerThread.id,+ runId: turnInput.runId,+ cause,+ }),+ ),),- ),- steerTurn: (steerInput) =>- Effect.gen(function* () {+ ),+ steerTurn: Effect.fn("OpencodeAdapter.steerTurn")(+ function* (steerInput) {const sessionId = nativeThreadId(steerInput.providerThread);const state = threads.get(sessionId);const turn = state?.activeTurn;@@ -3369,19 +3378,22 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(functionyield* reconcilePromptAdmission(state, turn);}}- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterSteerRunError({- driver: OPENCODE_PROVIDER,- providerThreadId: steerInput.providerThread.id,- providerTurnId: steerInput.providerTurnId,- cause,- }),+ },+ (effect, steerInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterSteerRunError({+ driver: OPENCODE_PROVIDER,+ providerThreadId: steerInput.providerThread.id,+ providerTurnId: steerInput.providerTurnId,+ cause,+ }),+ ),),- ),- interruptTurn: (interruptInput) =>- Effect.gen(function* () {+ ),+ interruptTurn: Effect.fn("OpencodeAdapter.interruptTurn")(+ function* (interruptInput) {const sessionId = nativeThreadId(interruptInput.providerThread);const state = threads.get(sessionId);const turn = state?.activeTurn;@@ -3432,19 +3444,22 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function// Root abort does not stop child sessions. Report incomplete cleanup// even if the root has already emitted its terminal event.yield* abortDescendants(sessionId);- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterInterruptError({- driver: OPENCODE_PROVIDER,- providerThreadId: interruptInput.providerThread.id,- providerTurnId: interruptInput.providerTurnId,- cause,- }),+ },+ (effect, interruptInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterInterruptError({+ driver: OPENCODE_PROVIDER,+ providerThreadId: interruptInput.providerThread.id,+ providerTurnId: interruptInput.providerTurnId,+ cause,+ }),+ ),),- ),- respondToRuntimeRequest: (requestInput) =>- Effect.gen(function* () {+ ),+ respondToRuntimeRequest: Effect.fn("OpencodeAdapter.respondToRuntimeRequest")(+ function* (requestInput) {const pending = pendingRequests.get(String(requestInput.requestId));if (pending === undefined) {return yield* protocolError(@@ -3493,16 +3508,19 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function{ signal },),).pipe(Effect.timeout("10 seconds"));- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({- driver: OPENCODE_PROVIDER,- requestId: requestInput.requestId,- cause,- }),+ },+ (effect, requestInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({+ driver: OPENCODE_PROVIDER,+ requestId: requestInput.requestId,+ cause,+ }),+ ),),- ),+ ),readThreadSnapshot: (snapshotInput) =>readSnapshot(snapshotInput.providerThread).pipe(Effect.mapError(@@ -3514,8 +3532,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function}),),),- rollbackThread: (rollbackInput) =>- Effect.gen(function* () {+ rollbackThread: Effect.fn("OpencodeAdapter.rollbackThread")(+ function* (rollbackInput) {const sessionId = nativeThreadId(rollbackInput.providerThread);const state = threads.get(sessionId);if (state?.activeTurn !== null && state?.activeTurn !== undefined) {@@ -3587,19 +3605,22 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function: null,},};- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterRollbackThreadError({- driver: OPENCODE_PROVIDER,- providerThreadId: rollbackInput.providerThread.id,- checkpointId: rollbackInput.target.checkpointId,- cause,- }),+ },+ (effect, rollbackInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterRollbackThreadError({+ driver: OPENCODE_PROVIDER,+ providerThreadId: rollbackInput.providerThread.id,+ checkpointId: rollbackInput.target.checkpointId,+ cause,+ }),+ ),),- ),- forkThread: (forkInput) =>- Effect.gen(function* () {+ ),+ forkThread: Effect.fn("OpencodeAdapter.forkThread")(+ function* (forkInput) {const sourceSessionId = nativeThreadId(forkInput.sourceProviderThread);const sourceState = threads.get(sourceSessionId);if (sourceState?.activeTurn !== null && sourceState?.activeTurn !== undefined) {@@ -3651,16 +3672,19 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function});registerThread(nativeSession, providerThread, null);return providerThread;- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterForkThreadError({- driver: OPENCODE_PROVIDER,- providerThreadId: forkInput.sourceProviderThread.id,- cause,- }),+ },+ (effect, forkInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterForkThreadError({+ driver: OPENCODE_PROVIDER,+ providerThreadId: forkInput.sourceProviderThread.id,+ cause,+ }),+ ),),- ),+ ),};return runtimeSession;diff --git a/packages/provider-opencode/src/server/driver.ts b/packages/provider-opencode/src/server/driver.tsindex 9c522d554ce..8c590ca100b 100644--- a/packages/provider-opencode/src/server/driver.ts+++ b/packages/provider-opencode/src/server/driver.ts@@ -186,343 +186,341 @@ export const OpenCodeDriver: ProviderDriver<configSchema: OpenCodeSettings,defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),usage: openCodeUsageReader,- create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>- Effect.gen(function* () {- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const fileSystem = yield* FileSystem.FileSystem;- const pathService = yield* Path.Path;- const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;- const httpClient = yield* HttpClient.HttpClient;- const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;- const crypto = yield* Crypto.Crypto;- const host = yield* ProviderHost.ProviderHost;- const processEnv = yield* mergeProviderInstanceEnvironment(environment);- const continuationIdentity = defaultProviderContinuationIdentity({- driverKind: DRIVER_KIND,- instanceId,- });- const stampIdentity = withInstanceIdentity({- instanceId,- driverKind: DRIVER_KIND,- displayName,- accentColor,- continuationGroupKey: continuationIdentity.continuationKey,- });- const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;- const runtimeProbe = yield* makeOpenCodeRuntimeProbe(- probeOpenCodeRuntime(effectiveConfig, processEnv).pipe(- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),- ),- );- const noUpdate = makeManualOnlyProviderMaintenanceCapabilities({- provider: DRIVER_KIND,- packageName: null,- });- const maintenanceFor = (probed: typeof runtimeProbe.get) =>- probed.pipe(- Effect.map((result) => result.generation),- Effect.option,- Effect.flatMap((generation) =>- Option.isNone(generation)- ? Effect.succeed(noUpdate)- : resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation.value), {- binaryPath: effectiveConfig.binaryPath,- env: processEnv,- }),- ),- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, pathService),- );- const cachedMaintenance = yield* makeCachedProviderMaintenanceResolution(- maintenanceFor(runtimeProbe.get),- );- const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>- !effectiveConfig.enabled- ? Effect.succeed(noUpdate)- : options?.fresh === true- ? runtimeProbe.refresh.pipe(- Effect.ignore,- Effect.andThen(cachedMaintenance({ fresh: true })),- )- : cachedMaintenance();- const openCodeV1Adapter = yield* OpenCodeAdapterV2.OpenCodeAdapterV2Driver.create({- instanceId,- displayName,- accentColor,- environment,- enabled,- config,- }).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to build OpenCode orchestration adapter.",- cause,- }),- ),- );- const openCode2Server = yield* OpenCode2Server.make({- binaryPath: effectiveConfig.binaryPath,- serverUrl: effectiveConfig.serverUrl,- serverPassword: effectiveConfig.serverPassword,- directory: host.paths.cwd,- environment: processEnv,- }).pipe(+ create: Effect.fn("OpencodeDriver.create")(function* ({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }) {+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const fileSystem = yield* FileSystem.FileSystem;+ const pathService = yield* Path.Path;+ const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;+ const httpClient = yield* HttpClient.HttpClient;+ const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;+ const crypto = yield* Crypto.Crypto;+ const host = yield* ProviderHost.ProviderHost;+ const processEnv = yield* mergeProviderInstanceEnvironment(environment);+ const continuationIdentity = defaultProviderContinuationIdentity({+ driverKind: DRIVER_KIND,+ instanceId,+ });+ const stampIdentity = withInstanceIdentity({+ instanceId,+ driverKind: DRIVER_KIND,+ displayName,+ accentColor,+ continuationGroupKey: continuationIdentity.continuationKey,+ });+ const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;+ const runtimeProbe = yield* makeOpenCodeRuntimeProbe(+ probeOpenCodeRuntime(effectiveConfig, processEnv).pipe(+ Effect.provideService(HttpClient.HttpClient, httpClient),Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),- Effect.provideService(- OpenCode2Client.OpenCode2Client,- yield* OpenCode2Client.make.pipe(- Effect.provideService(HttpClient.HttpClient, httpClient),- ),- ),- );- const orchestrationAdapter = selectOpenCodeRuntimeAdapter({- probe: runtimeProbe,- v1: openCodeV1Adapter,- v2: yield* OpenCode2AdapterV2.make(instanceId).pipe(- Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),- ),- });- const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(- openCode2Server.withConnection(({ client }) =>- loadOpenCode2Catalog(client, host.paths.cwd),+ ),+ );+ const noUpdate = makeManualOnlyProviderMaintenanceCapabilities({+ provider: DRIVER_KIND,+ packageName: null,+ });+ const maintenanceFor = (probed: typeof runtimeProbe.get) =>+ probed.pipe(+ Effect.map((result) => result.generation),+ Effect.option,+ Effect.flatMap((generation) =>+ Option.isNone(generation)+ ? Effect.succeed(noUpdate)+ : resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation.value), {+ binaryPath: effectiveConfig.binaryPath,+ env: processEnv,+ }),),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, pathService),);- const listOpenCode2Workspace = (cwd: string) =>- openCode2Server.withConnection(({ client, events }) =>- Effect.gen(function* () {- const location = { directory: cwd };- const scanned = yield* Deferred.make<void>();- const pending = new Set(["command.updated", "skill.updated"]);- const stream = yield* events.pipe(Effect.option);- if (stream._tag === "Some") {- yield* stream.value.pipe(- Stream.runForEach((event) =>- "location" in event &&- event.location?.directory === cwd &&- pending.delete(event.type) &&- pending.size === 0- ? Deferred.succeed(scanned, undefined)- : Effect.void,- ),- Effect.ignore,- Effect.forkScoped,- );- }- return yield* loadOpenCode2Workspace(- Effect.all(- {- skills: client.skill.list({ location }).pipe(Effect.map((list) => list.data)),- commands: client.command.list({ location }).pipe(Effect.map((list) => list.data)),- },- { concurrency: "unbounded" },+ const cachedMaintenance = yield* makeCachedProviderMaintenanceResolution(+ maintenanceFor(runtimeProbe.get),+ );+ const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>+ !effectiveConfig.enabled+ ? Effect.succeed(noUpdate)+ : options?.fresh === true+ ? runtimeProbe.refresh.pipe(+ Effect.ignore,+ Effect.andThen(cachedMaintenance({ fresh: true })),+ )+ : cachedMaintenance();+ const openCodeV1Adapter = yield* OpenCodeAdapterV2.OpenCodeAdapterV2Driver.create({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to build OpenCode orchestration adapter.",+ cause,+ }),+ ),+ );+ const openCode2Server = yield* OpenCode2Server.make({+ binaryPath: effectiveConfig.binaryPath,+ serverUrl: effectiveConfig.serverUrl,+ serverPassword: effectiveConfig.serverPassword,+ directory: host.paths.cwd,+ environment: processEnv,+ }).pipe(+ Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),+ Effect.provideService(+ OpenCode2Client.OpenCode2Client,+ yield* OpenCode2Client.make.pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),+ ),+ );+ const orchestrationAdapter = selectOpenCodeRuntimeAdapter({+ probe: runtimeProbe,+ v1: openCodeV1Adapter,+ v2: yield* OpenCode2AdapterV2.make(instanceId).pipe(+ Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),+ ),+ });+ const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(+ openCode2Server.withConnection(({ client }) => loadOpenCode2Catalog(client, host.paths.cwd)),+ );+ const listOpenCode2Workspace = (cwd: string) =>+ openCode2Server.withConnection(({ client, events }) =>+ Effect.gen(function* () {+ const location = { directory: cwd };+ const scanned = yield* Deferred.make<void>();+ const pending = new Set(["command.updated", "skill.updated"]);+ const stream = yield* events.pipe(Effect.option);+ if (stream._tag === "Some") {+ yield* stream.value.pipe(+ Stream.runForEach((event) =>+ "location" in event &&+ event.location?.directory === cwd &&+ pending.delete(event.type) &&+ pending.size === 0+ ? Deferred.succeed(scanned, undefined)+ : Effect.void,),- Deferred.await(scanned),+ Effect.ignore,+ Effect.forkScoped,);- }).pipe(Effect.scoped),- );- const serverOwner = yield* OpenCodeServerOwner.make({- binaryPath: effectiveConfig.binaryPath,- directory: host.paths.cwd,- ...(effectiveConfig.serverPassword- ? { serverPassword: effectiveConfig.serverPassword }- : {}),- environment: processEnv,- });- const textGeneration = selectOpenCodeRuntimeTextGeneration(- runtimeProbe,- yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(- Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),- ),- yield* OpenCode2TextGeneration.make().pipe(- Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),- ),+ }+ return yield* loadOpenCode2Workspace(+ Effect.all(+ {+ skills: client.skill.list({ location }).pipe(Effect.map((list) => list.data)),+ commands: client.command.list({ location }).pipe(Effect.map((list) => list.data)),+ },+ { concurrency: "unbounded" },+ ),+ Deferred.await(scanned),+ );+ }).pipe(Effect.scoped),);+ const serverOwner = yield* OpenCodeServerOwner.make({+ binaryPath: effectiveConfig.binaryPath,+ directory: host.paths.cwd,+ ...(effectiveConfig.serverPassword ? { serverPassword: effectiveConfig.serverPassword } : {}),+ environment: processEnv,+ });+ const textGeneration = selectOpenCodeRuntimeTextGeneration(+ runtimeProbe,+ yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(+ Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),+ ),+ yield* OpenCode2TextGeneration.make().pipe(+ Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),+ ),+ );- const checkProvider = Effect.all(+ const checkProvider = Effect.all(+ {+ provider: checkOpenCodeProviderStatus(+ effectiveConfig,+ host.paths.cwd,+ runtimeProbe.refresh,+ loadOpenCode2Models,+ ),+ usageLimits: readOpenCodeGoUsageLimits({+ enabled: effectiveConfig.enabled,+ serverUrl: effectiveConfig.serverUrl,+ environment: processEnv,+ }),+ },+ { concurrency: "unbounded" },+ ).pipe(+ Effect.map(({ provider, usageLimits }) => ({ ...provider, usageLimits })),+ Effect.map(stampIdentity),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, pathService),+ Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(Crypto.Crypto, crypto),+ Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),+ Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),+ );+ // The CLI writes its full JSON inventory to stdout, but the Bun-compiled binary does not+ // flush more than one 64KB pipe buffer to a non-TTY stdout, so the piped output arrives+ // truncated and unparseable — which degrades to an empty skill list and poisons the workspace+ // snapshot the `$` picker reads.+ const loadWorkspaceInventory = (+ client: Parameters<typeof OpenCodeRuntime.loadOpenCodeCommands>[0],+ ) =>+ Effect.all({- provider: checkOpenCodeProviderStatus(- effectiveConfig,- host.paths.cwd,- runtimeProbe.refresh,- loadOpenCode2Models,+ skills: openCodeRuntime.loadOpenCodeSkills(client),+ commands: OpenCodeRuntime.loadOpenCodeCommands(client).pipe(+ Effect.timeout("10 seconds"),+ Effect.option,),- usageLimits: readOpenCodeGoUsageLimits({- enabled: effectiveConfig.enabled,- serverUrl: effectiveConfig.serverUrl,- environment: processEnv,- }),},{ concurrency: "unbounded" },).pipe(- Effect.map(({ provider, usageLimits }) => ({ ...provider, usageLimits })),- Effect.map(stampIdentity),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, pathService),- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.provideService(Crypto.Crypto, crypto),- Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),- Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),+ // Only a finished lookup is reported as complete. A failed one leaves+ // the flag unset, so the registry decides from the provider's health.+ Effect.map(({ skills, commands }) => ({+ skills,+ commands: Option.getOrElse(commands, () => []),+ slashCommandsPending: Option.isSome(commands) ? false : undefined,+ })),);- // The CLI writes its full JSON inventory to stdout, but the Bun-compiled binary does not- // flush more than one 64KB pipe buffer to a non-TTY stdout, so the piped output arrives- // truncated and unparseable — which degrades to an empty skill list and poisons the workspace- // snapshot the `$` picker reads.- const loadWorkspaceInventory = (- client: Parameters<typeof OpenCodeRuntime.loadOpenCodeCommands>[0],- ) =>- Effect.all(- {- skills: openCodeRuntime.loadOpenCodeSkills(client),- commands: OpenCodeRuntime.loadOpenCodeCommands(client).pipe(- Effect.timeout("10 seconds"),- Effect.option,- ),- },- { concurrency: "unbounded" },- ).pipe(- // Only a finished lookup is reported as complete. A failed one leaves- // the flag unset, so the registry decides from the provider's health.- Effect.map(({ skills, commands }) => ({- skills,- commands: Option.getOrElse(commands, () => []),- slashCommandsPending: Option.isSome(commands) ? false : undefined,- })),- );- const loadWorkspaceForCwd = (cwd: string) =>- effectiveConfig.serverUrl.trim().length > 0- ? Effect.scoped(- Effect.gen(function* () {- const server = yield* openCodeRuntime.connectToOpenCodeServer({- binaryPath: effectiveConfig.binaryPath,- directory: cwd,- serverUrl: effectiveConfig.serverUrl,- ...(effectiveConfig.serverPassword- ? { serverPassword: effectiveConfig.serverPassword }- : {}),- environment: processEnv,- });- const client = openCodeRuntime.createOpenCodeSdkClient({- baseUrl: server.url,- directory: cwd,- ...(effectiveConfig.serverPassword- ? { serverPassword: effectiveConfig.serverPassword }- : {}),- });- return yield* loadWorkspaceInventory(client);+ const loadWorkspaceForCwd = (cwd: string) =>+ effectiveConfig.serverUrl.trim().length > 0+ ? Effect.scoped(+ Effect.gen(function* () {+ const server = yield* openCodeRuntime.connectToOpenCodeServer({+ binaryPath: effectiveConfig.binaryPath,+ directory: cwd,+ serverUrl: effectiveConfig.serverUrl,+ ...(effectiveConfig.serverPassword+ ? { serverPassword: effectiveConfig.serverPassword }+ : {}),+ environment: processEnv,+ });+ const client = openCodeRuntime.createOpenCodeSdkClient({+ baseUrl: server.url,+ directory: cwd,+ ...(effectiveConfig.serverPassword+ ? { serverPassword: effectiveConfig.serverPassword }+ : {}),+ });+ return yield* loadWorkspaceInventory(client);+ }),+ )+ : serverOwner.withServer((server) =>+ loadWorkspaceInventory(+ openCodeRuntime.createOpenCodeSdkClient({+ baseUrl: server.url,+ directory: cwd,+ ...(server.serverPassword !== undefined+ ? { serverPassword: server.serverPassword }+ : {}),}),- )- : serverOwner.withServer((server) =>- loadWorkspaceInventory(- openCodeRuntime.createOpenCodeSdkClient({- baseUrl: server.url,- directory: cwd,- ...(server.serverPassword !== undefined- ? { serverPassword: server.serverPassword }- : {}),- }),- ),- );-- const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);- const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(- {- resolveMaintenance,- getSettings: snapshotSettings.getSettings,- streamSettings: snapshotSettings.streamSettings,- haveSettingsChanged: haveProviderSnapshotSettingsChanged,- checkProviderOnSettingsChange: () => false,- refreshOnInterval: false,- initialSnapshot: (settings) =>- makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),- checkProvider,- enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>- resolveMaintenance().pipe(- Effect.flatMap((maintenanceCapabilities) =>- enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {- enableProviderUpdateChecks: settings.enableProviderUpdateChecks,- }),- ),- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),- Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),),- },- ).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,- cause,+ );++ const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);+ const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>({+ resolveMaintenance,+ getSettings: snapshotSettings.getSettings,+ streamSettings: snapshotSettings.streamSettings,+ haveSettingsChanged: haveProviderSnapshotSettingsChanged,+ checkProviderOnSettingsChange: () => false,+ refreshOnInterval: false,+ initialSnapshot: (settings) =>+ makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),+ checkProvider,+ enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>+ resolveMaintenance().pipe(+ Effect.flatMap((maintenanceCapabilities) =>+ enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {+ enableProviderUpdateChecks: settings.enableProviderUpdateChecks,}),+ ),+ Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),+ Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),),- );+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,+ cause,+ }),+ ),+ );- return {- instanceId,- driverKind: DRIVER_KIND,- continuationIdentity,- displayName,- accentColor,- enabled,- snapshot,- snapshotForCwd: (cwd) =>- !effectiveConfig.enabled- ? snapshot.getSnapshot- : byOpenCodeRuntime(runtimeProbe.get, {- v2: Effect.all([- snapshot.getSnapshot,- listOpenCode2Workspace(cwd).pipe(- Effect.timeout("20 seconds"),- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: `Failed to list OpenCode commands and skills for '${cwd}'`,- cause,- }),- ),- ),- ]).pipe(- Effect.map(([machineSnapshot, { skills, commands }]) => ({- ...machineSnapshot,- skills: openCode2SkillsToServerProviderSkills(skills),- slashCommands: openCode2CommandsToServerProviderSlashCommands(commands),- // A finished scan lists at least the built-ins. None means it- // timed out, so the registry decides from the provider's health.- slashCommandsPending: commands.length > 0 ? false : undefined,- })),- ),- v1: Effect.all([- snapshot.getSnapshot,- loadWorkspaceForCwd(cwd).pipe(Effect.timeout("20 seconds")),- ]).pipe(- Effect.map(([machineSnapshot, { skills, commands, slashCommandsPending }]) => ({- ...machineSnapshot,- skills: openCodeSkillsToServerProviderSkills(skills),- slashCommands: openCodeCommandsToServerProviderSlashCommands(commands),- slashCommandsPending,- })),+ return {+ instanceId,+ driverKind: DRIVER_KIND,+ continuationIdentity,+ displayName,+ accentColor,+ enabled,+ snapshot,+ snapshotForCwd: (cwd) =>+ !effectiveConfig.enabled+ ? snapshot.getSnapshot+ : byOpenCodeRuntime(runtimeProbe.get, {+ v2: Effect.all([+ snapshot.getSnapshot,+ listOpenCode2Workspace(cwd).pipe(+ Effect.timeout("20 seconds"),Effect.mapError((cause) =>new ProviderDriverError({driver: DRIVER_KIND,instanceId,- detail: `Failed to probe OpenCode commands and skills for '${cwd}'`,+ detail: `Failed to list OpenCode commands and skills for '${cwd}'`,cause,}),),),- }),- orchestrationAdapter,- textGeneration,- } satisfies ProviderInstance;- }),+ ]).pipe(+ Effect.map(([machineSnapshot, { skills, commands }]) => ({+ ...machineSnapshot,+ skills: openCode2SkillsToServerProviderSkills(skills),+ slashCommands: openCode2CommandsToServerProviderSlashCommands(commands),+ // A finished scan lists at least the built-ins. None means it+ // timed out, so the registry decides from the provider's health.+ slashCommandsPending: commands.length > 0 ? false : undefined,+ })),+ ),+ v1: Effect.all([+ snapshot.getSnapshot,+ loadWorkspaceForCwd(cwd).pipe(Effect.timeout("20 seconds")),+ ]).pipe(+ Effect.map(([machineSnapshot, { skills, commands, slashCommandsPending }]) => ({+ ...machineSnapshot,+ skills: openCodeSkillsToServerProviderSkills(skills),+ slashCommands: openCodeCommandsToServerProviderSlashCommands(commands),+ slashCommandsPending,+ })),+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: `Failed to probe OpenCode commands and skills for '${cwd}'`,+ cause,+ }),+ ),+ ),+ }),+ orchestrationAdapter,+ textGeneration,+ } satisfies ProviderInstance;+ }),};diff --git a/packages/provider-opencode/src/server/status.ts b/packages/provider-opencode/src/server/status.tsindex 4557ce3f972..1fe35dfadb1 100644--- a/packages/provider-opencode/src/server/status.ts+++ b/packages/provider-opencode/src/server/status.ts@@ -328,39 +328,20 @@ export function openCodeCommandsToServerProviderSlashCommands(return commands;}-export const makePendingOpenCodeProvider = (- openCodeSettings: OpenCodeSettings,-): Effect.Effect<ServerProviderDraft> =>- Effect.gen(function* () {- const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);- const models = providerModelsFromSettings(- [],- openCodeSettings.customModels,- DEFAULT_OPENCODE_MODEL_CAPABILITIES,- );-- if (!openCodeSettings.enabled) {- return buildServerProvider({- presentation: OPENCODE_PRESENTATION,- enabled: false,- checkedAt,- models,- probe: {- installed: false,- version: null,- status: "warning",- auth: { status: "unknown" },- message:- openCodeSettings.serverUrl.trim().length > 0- ? "OpenCode is disabled in T3 Code settings. A server URL is configured."- : "OpenCode is disabled in T3 Code settings.",- },- });- }+export const makePendingOpenCodeProvider = Effect.fn(+ "OpencodeProviderStatus.makePendingOpenCodeProvider",+)(function* (openCodeSettings: OpenCodeSettings): Effect.fn.Return<ServerProviderDraft> {+ const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);+ const models = providerModelsFromSettings(+ [],+ openCodeSettings.customModels,+ DEFAULT_OPENCODE_MODEL_CAPABILITIES,+ );+ if (!openCodeSettings.enabled) {return buildServerProvider({presentation: OPENCODE_PRESENTATION,- enabled: true,+ enabled: false,checkedAt,models,probe: {@@ -368,10 +349,28 @@ export const makePendingOpenCodeProvider = (version: null,status: "warning",auth: { status: "unknown" },- message: "OpenCode provider status has not been checked in this session yet.",+ message:+ openCodeSettings.serverUrl.trim().length > 0+ ? "OpenCode is disabled in T3 Code settings. A server URL is configured."+ : "OpenCode is disabled in T3 Code settings.",},});+ }++ return buildServerProvider({+ presentation: OPENCODE_PRESENTATION,+ enabled: true,+ checkedAt,+ models,+ probe: {+ installed: false,+ version: null,+ status: "warning",+ auth: { status: "unknown" },+ message: "OpenCode provider status has not been checked in this session yet.",+ },});+});export interface OpenCode2Model {readonly providerID: string;@@ -461,16 +460,14 @@ export interface OpenCode2Workspace {* for the directory end the scan. `scanned` must be listening before `read` runs, since* the read is what starts the scan.*/-export const loadOpenCode2Workspace = <E>(- read: Effect.Effect<OpenCode2Workspace, E>,- scanned: Effect.Effect<void>,-) =>- Effect.gen(function* () {+export const loadOpenCode2Workspace = Effect.fn("OpencodeProviderStatus.loadOpenCode2Workspace")(+ function* <E>(read: Effect.Effect<OpenCode2Workspace, E>, scanned: Effect.Effect<void>) {const first = yield* read;if (first.commands.length > 0) return first;yield* scanned.pipe(Effect.timeoutOption("10 seconds"));return yield* read;- });+ },+);export function openCode2SkillsToServerProviderSkills(skills: OpenCode2Workspace["skills"],diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.tsindex 88a56ad00cd..41d11a70cbc 100644--- a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts+++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts@@ -91,34 +91,34 @@ const decodeEnvelope = Schema.decodeUnknownOption(),);-const undecodable = (data: string) =>- Effect.gen(function* () {- const envelope = decodeEnvelope(data);- const type = envelope._tag === "Some" ? envelope.value.type.slice(0, 80) : "<unreadable>";- const sessionID = envelope._tag === "Some" ? envelope.value.data?.sessionID : undefined;- if (isExecutionEnd(type) && sessionID !== undefined) {- yield* Effect.logWarning(- "Ended an OpenCode execution from an event this build cannot decode.",- {- type,- },- );- return Result.succeed<OpenCode2StreamEvent>({- type: "unreadable.execution.ended",- executionType: type,- sessionID,- });- }- if (type === "session.execution.started" && sessionID !== undefined) {- yield* Effect.logDebug("Read an OpenCode execution start this build cannot decode.");- return Result.succeed<OpenCode2StreamEvent>({- type: "unreadable.execution.started",- sessionID,- });- }- yield* Effect.logDebug("Skipped an OpenCode event this build cannot decode.", { type });- return Result.failVoid;- });+// Rejected stream frames can be frequent when the server introduces new event types.+const undecodable = Effect.fnUntraced(function* (data: string) {+ const envelope = decodeEnvelope(data);+ const type = envelope._tag === "Some" ? envelope.value.type.slice(0, 80) : "<unreadable>";+ const sessionID = envelope._tag === "Some" ? envelope.value.data?.sessionID : undefined;+ if (isExecutionEnd(type) && sessionID !== undefined) {+ yield* Effect.logWarning(+ "Ended an OpenCode execution from an event this build cannot decode.",+ {+ type,+ },+ );+ return Result.succeed<OpenCode2StreamEvent>({+ type: "unreadable.execution.ended",+ executionType: type,+ sessionID,+ });+ }+ if (type === "session.execution.started" && sessionID !== undefined) {+ yield* Effect.logDebug("Read an OpenCode execution start this build cannot decode.");+ return Result.succeed<OpenCode2StreamEvent>({+ type: "unreadable.execution.started",+ sessionID,+ });+ }+ yield* Effect.logDebug("Skipped an OpenCode event this build cannot decode.", { type });+ return Result.failVoid;+});const readEvents = HttpClient.get("/api/event", {headers: { accept: "text/event-stream" },diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Server.ts b/packages/provider-opencode/src/server/v2/OpenCode2Server.tsindex 5991d575862..c8a71531fe3 100644--- a/packages/provider-opencode/src/server/v2/OpenCode2Server.ts+++ b/packages/provider-opencode/src/server/v2/OpenCode2Server.ts@@ -136,12 +136,15 @@ export const make = Effect.fn("OpenCode2Server.make")(function* (input: {readonly environment: NodeJS.ProcessEnv;}) {const opencode = yield* OpenCode2Client.OpenCode2Client;- const connectTo = (url: string, password: Redacted.Redacted, external: boolean) =>- Effect.gen(function* () {- const api = yield* opencode.connect({ baseUrl: url, password });- const version = yield* verifyServer(api.client);- return { ...api, url, version, external } satisfies OpenCode2Connection;- });+ const connectTo = Effect.fn("OpenCode2Server.connectTo")(function* (+ url: string,+ password: Redacted.Redacted,+ external: boolean,+ ) {+ const api = yield* opencode.connect({ baseUrl: url, password });+ const version = yield* verifyServer(api.client);+ return { ...api, url, version, external } satisfies OpenCode2Connection;+ });let latest: OpenCode2Connection | undefined;const remember = (connection: OpenCode2Connection) =>Effect.sync(() => {diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.tsindex b664eabd8ab..9887cb554ed 100644--- a/packages/provider-opencode/src/server/v2/adapter.ts+++ b/packages/provider-opencode/src/server/v2/adapter.ts@@ -839,11 +839,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Prconst hasBackground = (thread: ThreadState) => sessionsOf(thread).some(owesWork);- const setSessionStatus = (- status: OrchestrationV2ProviderSession["status"],- lastError: string | null,- ) =>- Effect.gen(function* () {+ const setSessionStatus =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ status: OrchestrationV2ProviderSession["status"],+ lastError: string | null,+ ) {// The session is shared by every thread on this instance and is persisted// once per attached thread, so a repeat of the same state is not worth a write.if (session.status === status && session.lastError === lastError) return;@@ -3051,55 +3052,54 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Prif (turn !== undefined) turn.before = before;});- const beginTurn = (+ const beginTurn = Effect.fn("OpenCode2Adapter.beginTurn")(function* (state: ThreadState,turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,awaitingStart: boolean,- ) =>- Effect.gen(function* () {- const startedAt = yield* DateTime.now;- const nativeTurnId = `${state.sessionId}:attempt:${turnInput.attemptId}`;- const providerTurn: OrchestrationV2ProviderTurn = {- id: idAllocator.derive.providerTurn({ driver, nativeTurnId }),- providerThreadId: turnInput.providerThread.id,- nodeId: turnInput.rootNodeId,- runAttemptId: turnInput.attemptId,- nativeTurnRef: ref(- isContinuation(turnInput)- ? wakeTurnId(state.sessionId, turnInput.attemptId)- : turnPromptId(state.sessionId, turnInput.attemptId),- "weak",- ),- ordinal: turnInput.providerTurnOrdinal,- status: "running",- startedAt,- completedAt: null,- };- const turn = makeTurn(turnInput, providerTurn, { scope: "", awaitingStart });- if (streamFailure !== undefined) {- return yield* new ProviderAdapter.ProviderAdapterEventStreamError({- driver,- providerSessionId: input.providerSessionId,- cause: streamFailure,- });- }- state.active = turn;- yield* emitProviderTurn(state, turn, providerTurn);- state.providerThread = {- ...state.providerThread,- status: "active",- firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,- lastRunOrdinal: turnInput.runOrdinal,- updatedAt: startedAt,- };- yield* emit({- type: "provider_thread.updated",+ ) {+ const startedAt = yield* DateTime.now;+ const nativeTurnId = `${state.sessionId}:attempt:${turnInput.attemptId}`;+ const providerTurn: OrchestrationV2ProviderTurn = {+ id: idAllocator.derive.providerTurn({ driver, nativeTurnId }),+ providerThreadId: turnInput.providerThread.id,+ nodeId: turnInput.rootNodeId,+ runAttemptId: turnInput.attemptId,+ nativeTurnRef: ref(+ isContinuation(turnInput)+ ? wakeTurnId(state.sessionId, turnInput.attemptId)+ : turnPromptId(state.sessionId, turnInput.attemptId),+ "weak",+ ),+ ordinal: turnInput.providerTurnOrdinal,+ status: "running",+ startedAt,+ completedAt: null,+ };+ const turn = makeTurn(turnInput, providerTurn, { scope: "", awaitingStart });+ if (streamFailure !== undefined) {+ return yield* new ProviderAdapter.ProviderAdapterEventStreamError({driver,- providerThread: state.providerThread,+ providerSessionId: input.providerSessionId,+ cause: streamFailure,});- yield* setSessionStatus("running", null);- return turn;+ }+ state.active = turn;+ yield* emitProviderTurn(state, turn, providerTurn);+ state.providerThread = {+ ...state.providerThread,+ status: "active",+ firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,+ lastRunOrdinal: turnInput.runOrdinal,+ updatedAt: startedAt,+ };+ yield* emit({+ type: "provider_thread.updated",+ driver,+ providerThread: state.providerThread,});+ yield* setSessionStatus("running", null);+ return turn;+ });const replay = Effect.fnUntraced(function* (wake: Wake) {wake.dropped = true;@@ -3344,8 +3344,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Prselection.instanceId === instanceId? windowOf(cwd === undefined ? session.cwd : cwd, selection.model): undefined,- ensureThread: (threadInput) =>- Effect.gen(function* () {+ ensureThread: Effect.fn("OpenCode2Adapter.ensureThread")(+ function* (threadInput) {if (threadInput.existingProviderThread?.nativeThreadRef != null) {return yield* runtime.resumeThread({providerThread: threadInput.existingProviderThread,@@ -3410,19 +3410,22 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr);state.policy = policy;return state.providerThread;- }).pipe(- Effect.mapError((cause) =>- isProviderAdapterError(cause)- ? cause- : new ProviderAdapter.ProviderAdapterEnsureThreadError({- driver,- threadId: threadInput.threadId,- cause,- }),+ },+ (effect, threadInput) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProviderAdapterError(cause)+ ? cause+ : new ProviderAdapter.ProviderAdapterEnsureThreadError({+ driver,+ threadId: threadInput.threadId,+ cause,+ }),+ ),),- ),- resumeThread: (threadInput) =>- Effect.gen(function* () {+ ),+ resumeThread: Effect.fn("OpenCode2Adapter.resumeThread")(+ function* (threadInput) {const sessionId = yield* sessionIdOf(threadInput.providerThread);if (threadInput.runtimePolicy !== undefined) {yield* readModelsOnce(threadInput.runtimePolicy.cwd);@@ -3446,22 +3449,25 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr});}return state.providerThread;- }).pipe(- Effect.mapError((cause) =>- isProviderAdapterError(cause)- ? cause- : new ProviderAdapter.ProviderAdapterResumeThreadError({- driver,- providerSessionId: input.providerSessionId,- providerThreadId: threadInput.providerThread.id,- cause,- }),+ },+ (effect, threadInput) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProviderAdapterError(cause)+ ? cause+ : new ProviderAdapter.ProviderAdapterResumeThreadError({+ driver,+ providerSessionId: input.providerSessionId,+ providerThreadId: threadInput.providerThread.id,+ cause,+ }),+ ),),- ),+ ),compactThread: (turnInput) =>runtime.startTurn({ ...turnInput, message: { ...turnInput.message, text: "/compact" } }),- startTurn: (turnInput) =>- Effect.gen(function* () {+ startTurn: Effect.fn("OpenCode2Adapter.startTurn")(+ function* (turnInput) {// Waited out before the session's gate, so a rollback or fork is not// held behind a reconnect.if (streamFailure !== undefined) {@@ -3604,21 +3610,24 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr: Effect.void,),);- }).pipe(- Effect.mapError((cause) =>- isProviderAdapterError(cause)- ? cause- : new ProviderAdapter.ProviderAdapterTurnStartError({- driver,- threadId: turnInput.threadId,- providerThreadId: turnInput.providerThread.id,- runId: turnInput.runId,- cause,- }),+ },+ (effect, turnInput) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProviderAdapterError(cause)+ ? cause+ : new ProviderAdapter.ProviderAdapterTurnStartError({+ driver,+ threadId: turnInput.threadId,+ providerThreadId: turnInput.providerThread.id,+ runId: turnInput.runId,+ cause,+ }),+ ),),- ),- steerTurn: (steerInput) =>- Effect.gen(function* () {+ ),+ steerTurn: Effect.fn("OpenCode2Adapter.steerTurn")(+ function* (steerInput) {const sessionId = yield* sessionIdOf(steerInput.providerThread);const state = threads.get(sessionId);const turn = state?.active;@@ -3680,20 +3689,23 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr),),);- }).pipe(- Effect.mapError((cause) =>- isProviderAdapterError(cause)- ? cause- : new ProviderAdapter.ProviderAdapterSteerRunError({- driver,- providerThreadId: steerInput.providerThread.id,- providerTurnId: steerInput.providerTurnId,- cause,- }),+ },+ (effect, steerInput) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProviderAdapterError(cause)+ ? cause+ : new ProviderAdapter.ProviderAdapterSteerRunError({+ driver,+ providerThreadId: steerInput.providerThread.id,+ providerTurnId: steerInput.providerTurnId,+ cause,+ }),+ ),),- ),- interruptTurn: (interruptInput) =>- Effect.gen(function* () {+ ),+ interruptTurn: Effect.fn("OpenCode2Adapter.interruptTurn")(+ function* (interruptInput) {const sessionId = yield* sessionIdOf(interruptInput.providerThread);const state = threads.get(sessionId);if (state === undefined) return;@@ -3738,40 +3750,42 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Prdetail: `OpenCode session ${sessionId} had nothing running to stop`,});}- }).pipe(- Effect.mapError((cause) =>- isProviderAdapterError(cause)- ? cause- : new ProviderAdapter.ProviderAdapterInterruptError({- driver,- providerThreadId: interruptInput.providerThread.id,- providerTurnId: interruptInput.providerTurnId,- cause,- }),+ },+ (effect, interruptInput) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProviderAdapterError(cause)+ ? cause+ : new ProviderAdapter.ProviderAdapterInterruptError({+ driver,+ providerThreadId: interruptInput.providerThread.id,+ providerTurnId: interruptInput.providerTurnId,+ cause,+ }),+ ),),- ),- unloadThread: ({ providerThread }) =>- Effect.gen(function* () {- const nativeId = providerThread.nativeThreadRef?.nativeId;- const state = nativeId == null ? undefined : threads.get(nativeId);- if (- nativeId == null ||- state === undefined ||- state.active !== undefined ||- hasBackground(state)- ) {- return;- }- threads.delete(nativeId);- for (const [child, owner] of childOwners) {- if (owner !== state) continue;- childOwners.delete(child);- threads.delete(child);- }- if (state.mcp !== undefined) yield* removeMcp(state.mcp);- }),- respondToRuntimeRequest: (requestInput) =>- Effect.gen(function* () {+ ),+ unloadThread: Effect.fn("OpenCode2Adapter.unloadThread")(function* ({ providerThread }) {+ const nativeId = providerThread.nativeThreadRef?.nativeId;+ const state = nativeId == null ? undefined : threads.get(nativeId);+ if (+ nativeId == null ||+ state === undefined ||+ state.active !== undefined ||+ hasBackground(state)+ ) {+ return;+ }+ threads.delete(nativeId);+ for (const [child, owner] of childOwners) {+ if (owner !== state) continue;+ childOwners.delete(child);+ threads.delete(child);+ }+ if (state.mcp !== undefined) yield* removeMcp(state.mcp);+ }),+ respondToRuntimeRequest: Effect.fn("OpenCode2Adapter.respondToRuntimeRequest")(+ function* (requestInput) {const entry = pending.get(requestInput.requestId);if (entry === undefined || entry.answering) {return yield* new ProviderAdapter.ProviderAdapterProtocolError({@@ -3844,34 +3858,40 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr);yield* forgetRequest(entry);if (!delivered) yield* abandonRequest(asker, "answer not delivered");- }).pipe(- Effect.mapError((cause) =>- isProviderAdapterError(cause)- ? cause- : new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({- driver,- requestId: requestInput.requestId,- cause,- }),+ },+ (effect, requestInput) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProviderAdapterError(cause)+ ? cause+ : new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({+ driver,+ requestId: requestInput.requestId,+ cause,+ }),+ ),),- ),- readThreadSnapshot: ({ providerThread }) =>- Effect.gen(function* () {+ ),+ readThreadSnapshot: Effect.fn("OpenCode2Adapter.readThreadSnapshot")(+ function* ({ providerThread }) {const sessionId = yield* sessionIdOf(providerThread);return yield* snapshotOf(providerThread, sessionId);- }).pipe(- Effect.mapError((cause) =>- isProviderAdapterError(cause)- ? cause- : new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({- driver,- providerThreadId: providerThread.id,- cause,- }),+ },+ (effect, { providerThread }) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProviderAdapterError(cause)+ ? cause+ : new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({+ driver,+ providerThreadId: providerThread.id,+ cause,+ }),+ ),),- ),- rollbackThread: (rollbackInput) =>- Effect.gen(function* () {+ ),+ rollbackThread: Effect.fn("OpenCode2Adapter.rollbackThread")(+ function* (rollbackInput) {const { providerThread, target } = rollbackInput;const sessionId = yield* sessionIdOf(providerThread);yield* ensureQuiet(sessionId, "roll back");@@ -3904,21 +3924,24 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr);for (const turn of snapshot.providerTurns) kept.set(turn.id, turn);return { ...snapshot, providerTurns: [...kept.values()] };- }).pipe(- exclusive(rollbackInput.providerThread),- Effect.mapError((cause) =>- isProviderAdapterError(cause)- ? cause- : new ProviderAdapter.ProviderAdapterRollbackThreadError({- driver,- providerThreadId: rollbackInput.providerThread.id,- checkpointId: rollbackInput.target.checkpointId,- cause,- }),+ },+ (effect, rollbackInput) =>+ effect.pipe(+ exclusive(rollbackInput.providerThread),+ Effect.mapError((cause) =>+ isProviderAdapterError(cause)+ ? cause+ : new ProviderAdapter.ProviderAdapterRollbackThreadError({+ driver,+ providerThreadId: rollbackInput.providerThread.id,+ checkpointId: rollbackInput.target.checkpointId,+ cause,+ }),+ ),),- ),- forkThread: (forkInput) =>- Effect.gen(function* () {+ ),+ forkThread: Effect.fn("OpenCode2Adapter.forkThread")(+ function* (forkInput) {const source = forkInput.sourceProviderThread;const sourceId = yield* sessionIdOf(source);// OpenCode forks whatever history the source has, so a fork taken@@ -3983,18 +4006,21 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr});}return state.providerThread;- }).pipe(- exclusive(forkInput.sourceProviderThread),- Effect.mapError((cause) =>- isProviderAdapterError(cause)- ? cause- : new ProviderAdapter.ProviderAdapterForkThreadError({- driver,- providerThreadId: forkInput.sourceProviderThread.id,- cause,- }),+ },+ (effect, forkInput) =>+ effect.pipe(+ exclusive(forkInput.sourceProviderThread),+ Effect.mapError((cause) =>+ isProviderAdapterError(cause)+ ? cause+ : new ProviderAdapter.ProviderAdapterForkThreadError({+ driver,+ providerThreadId: forkInput.sourceProviderThread.id,+ cause,+ }),+ ),),- ),+ ),};return runtime;});@@ -4006,21 +4032,24 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: PrplanSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),// The session borrows the instance's server for as long as it is open, so a// spawned server is not idle-stopped under a long tool call.- openSession: (input) =>- Effect.gen(function* () {+ openSession: Effect.fn("OpenCode2Adapter.borrowAndOpenSession")(+ function* (input) {const scope = yield* Scope.make();yield* Effect.addFinalizer((exit) => Scope.close(scope, exit));const connection = yield* borrow.pipe(Effect.provideService(Scope.Scope, scope));return yield* openSession(input, { connection, scope });- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterOpenSessionError({- driver,- providerSessionId: input.providerSessionId,- cause,- }),+ },+ (effect, input) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterOpenSessionError({+ driver,+ providerSessionId: input.providerSessionId,+ cause,+ }),+ ),),- ),+ ),});});diff --git a/packages/provider-opencode/src/server/v2/textGeneration.ts b/packages/provider-opencode/src/server/v2/textGeneration.tsindex 252431bc359..108271afc67 100644--- a/packages/provider-opencode/src/server/v2/textGeneration.ts+++ b/packages/provider-opencode/src/server/v2/textGeneration.ts@@ -32,149 +32,148 @@ type Outcome =| { readonly _tag: "text"; readonly text: string }| { readonly _tag: "failed"; readonly detail: string; readonly cause?: unknown };-const runOnServer = (+const runOnServer = Effect.fn("Opencode2TextGeneration.runOnServer")(function* (connection: OpenCode2Server.OpenCode2Connection,input: TextGenerationOperations.Request<Schema.Top>,-) =>- Effect.gen(function* () {- const { resolveAttachmentPath } = yield* ProviderHost.ProviderHost;- const { client } = connection;- const parsed = OpenCodeRuntime.parseOpenCodeModelSlug(input.modelSelection.model);- if (parsed === null) {- return yield* new TextGenerationError({- operation: input.operation,- detail: "OpenCode model selection must use the 'provider/model' format.",- });- }- const variant = getModelSelectionStringOptionValue(input.modelSelection, "variant");- const outcome = yield* Deferred.make<Outcome>();- let sessionId: string | undefined;- const texts = new Map<string, string>();- // Subscribed first: the stream is volatile, and the reply arrives on it.- const events = yield* connection.events;- yield* events.pipe(- Stream.runForEach((event) => {- // An execution end a newer server sent in a shape this build cannot- // read still ends the generation, as it ends a turn in the adapter.- if (event.type === "unreadable.execution.ended") {- if (event.sessionID !== sessionId) return Effect.void;- return Deferred.succeed(- outcome,- event.executionType === "session.execution.succeeded"- ? { _tag: "text", text: [...texts.values()].join("\n").trim() }- : {- _tag: "failed",- detail: "OpenCode ended the generation in a way this version cannot read.",- cause: event,- },- );- }- if (- sessionId === undefined ||- !("data" in event) ||- !("sessionID" in event.data) ||- event.data.sessionID !== sessionId- ) {+) {+ const { resolveAttachmentPath } = yield* ProviderHost.ProviderHost;+ const { client } = connection;+ const parsed = OpenCodeRuntime.parseOpenCodeModelSlug(input.modelSelection.model);+ if (parsed === null) {+ return yield* new TextGenerationError({+ operation: input.operation,+ detail: "OpenCode model selection must use the 'provider/model' format.",+ });+ }+ const variant = getModelSelectionStringOptionValue(input.modelSelection, "variant");+ const outcome = yield* Deferred.make<Outcome>();+ let sessionId: string | undefined;+ const texts = new Map<string, string>();+ // Subscribed first: the stream is volatile, and the reply arrives on it.+ const events = yield* connection.events;+ yield* events.pipe(+ Stream.runForEach((event) => {+ // An execution end a newer server sent in a shape this build cannot+ // read still ends the generation, as it ends a turn in the adapter.+ if (event.type === "unreadable.execution.ended") {+ if (event.sessionID !== sessionId) return Effect.void;+ return Deferred.succeed(+ outcome,+ event.executionType === "session.execution.succeeded"+ ? { _tag: "text", text: [...texts.values()].join("\n").trim() }+ : {+ _tag: "failed",+ detail: "OpenCode ended the generation in a way this version cannot read.",+ cause: event,+ },+ );+ }+ if (+ sessionId === undefined ||+ !("data" in event) ||+ !("sessionID" in event.data) ||+ event.data.sessionID !== sessionId+ ) {+ return Effect.void;+ }+ switch (event.type) {+ case "session.text.ended":+ texts.set(`${event.data.assistantMessageID}:${event.data.ordinal}`, event.data.text);return Effect.void;- }- switch (event.type) {- case "session.text.ended":- texts.set(`${event.data.assistantMessageID}:${event.data.ordinal}`, event.data.text);- return Effect.void;- case "permission.asked":- return client.permission- .reply({- sessionID: event.data.sessionID,- requestID: event.data.id,- decision: "reject",- message: "Tools are not available while generating text.",- })- .pipe(Effect.ignore({ log: true }));- case "session.execution.succeeded":- return Deferred.succeed(outcome, {- _tag: "text",- text: [...texts.values()].join("\n").trim(),- });- case "session.execution.failed":- return Deferred.succeed(outcome, {- _tag: "failed",- detail: "OpenCode could not generate the text.",- cause: event.data.error,- });- case "session.execution.interrupted":- return Deferred.succeed(outcome, {- _tag: "failed",- detail: "OpenCode stopped the generation.",- });- default:- return Effect.void;- }- }),- // The reply only arrives on this stream, so a lost stream ends the wait.- Effect.exit,- Effect.flatMap((exit) =>- Deferred.succeed(outcome, {- _tag: "failed",- detail: "The OpenCode event stream was lost.",- cause: exit,- }),- ),- Effect.forkScoped,- );- const session = yield* client.session.create({- title: `T3 Code ${input.operation}`,- location: Location.PublicRef.make({ directory: AbsolutePath.make(input.cwd) }),- model: Model.Ref.make({- providerID: Provider.ID.make(parsed.providerID),- id: Model.ID.make(parsed.modelID),- ...(variant === undefined ? {} : { variant: Model.VariantID.make(variant) }),+ case "permission.asked":+ return client.permission+ .reply({+ sessionID: event.data.sessionID,+ requestID: event.data.id,+ decision: "reject",+ message: "Tools are not available while generating text.",+ })+ .pipe(Effect.ignore({ log: true }));+ case "session.execution.succeeded":+ return Deferred.succeed(outcome, {+ _tag: "text",+ text: [...texts.values()].join("\n").trim(),+ });+ case "session.execution.failed":+ return Deferred.succeed(outcome, {+ _tag: "failed",+ detail: "OpenCode could not generate the text.",+ cause: event.data.error,+ });+ case "session.execution.interrupted":+ return Deferred.succeed(outcome, {+ _tag: "failed",+ detail: "OpenCode stopped the generation.",+ });+ default:+ return Effect.void;+ }+ }),+ // The reply only arrives on this stream, so a lost stream ends the wait.+ Effect.exit,+ Effect.flatMap((exit) =>+ Deferred.succeed(outcome, {+ _tag: "failed",+ detail: "The OpenCode event stream was lost.",+ cause: exit,}),- permissions: GENERATION_PERMISSIONS,- });- sessionId = session.id;- yield* Effect.addFinalizer(() =>- client.session- .remove({ sessionID: session.id })- .pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })),- );- const images = (input.attachments ?? []).flatMap((attachment) => {- if (attachment.type !== "image") return [];- const path = resolveAttachmentPath(attachment);- return path === null ? [] : [{ uri: `file://${path}`, name: attachment.name }];+ ),+ Effect.forkScoped,+ );+ const session = yield* client.session.create({+ title: `T3 Code ${input.operation}`,+ location: Location.PublicRef.make({ directory: AbsolutePath.make(input.cwd) }),+ model: Model.Ref.make({+ providerID: Provider.ID.make(parsed.providerID),+ id: Model.ID.make(parsed.modelID),+ ...(variant === undefined ? {} : { variant: Model.VariantID.make(variant) }),+ }),+ permissions: GENERATION_PERMISSIONS,+ });+ sessionId = session.id;+ yield* Effect.addFinalizer(() =>+ client.session+ .remove({ sessionID: session.id })+ .pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })),+ );+ const images = (input.attachments ?? []).flatMap((attachment) => {+ if (attachment.type !== "image") return [];+ const path = resolveAttachmentPath(attachment);+ return path === null ? [] : [{ uri: `file://${path}`, name: attachment.name }];+ });+ yield* client.session.prompt({+ sessionID: session.id,+ text: input.prompt,+ ...(images.length === 0 ? {} : { files: images }),+ });+ const result = yield* Deferred.await(outcome).pipe(+ Effect.timeoutOrElse({+ duration: GENERATION_TIMEOUT,+ orElse: () =>+ client.session.interrupt({ sessionID: Session.ID.make(session.id) }).pipe(+ Effect.ignore,+ Effect.as<Outcome>({+ _tag: "failed",+ detail: "OpenCode did not finish generating in time.",+ }),+ ),+ }),+ );+ if (result._tag === "failed") {+ return yield* new TextGenerationError({+ operation: input.operation,+ detail: result.detail,+ ...(result.cause === undefined ? {} : { cause: result.cause }),});- yield* client.session.prompt({- sessionID: session.id,- text: input.prompt,- ...(images.length === 0 ? {} : { files: images }),+ }+ if (result.text.length === 0) {+ return yield* new TextGenerationError({+ operation: input.operation,+ detail: "OpenCode returned empty output.",});- const result = yield* Deferred.await(outcome).pipe(- Effect.timeoutOrElse({- duration: GENERATION_TIMEOUT,- orElse: () =>- client.session.interrupt({ sessionID: Session.ID.make(session.id) }).pipe(- Effect.ignore,- Effect.as<Outcome>({- _tag: "failed",- detail: "OpenCode did not finish generating in time.",- }),- ),- }),- );- if (result._tag === "failed") {- return yield* new TextGenerationError({- operation: input.operation,- detail: result.detail,- ...(result.cause === undefined ? {} : { cause: result.cause }),- });- }- if (result.text.length === 0) {- return yield* new TextGenerationError({- operation: input.operation,- detail: "OpenCode returned empty output.",- });- }- return result.text;- }).pipe(Effect.scoped);+ }+ return result.text;+}, Effect.scoped);export const make = Effect.fn("OpenCode2TextGeneration.make")(function* () {const server = yield* OpenCode2Server.OpenCode2Server;diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.tsindex bf3d88bcf57..4a8f34c821d 100644--- a/packages/provider-pi/src/server/adapter.ts+++ b/packages/provider-pi/src/server/adapter.ts@@ -582,11 +582,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (const emit = (event: ProviderAdapter.ProviderAdapterV2Event) =>Queue.offer(events, event).pipe(Effect.asVoid);- const updateProviderSession = (- status: OrchestrationV2ProviderSession["status"],- lastError: string | null = sessionEntity.lastError,- ) =>- Effect.gen(function* () {+ const updateProviderSession =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ status: OrchestrationV2ProviderSession["status"],+ lastError: string | null = sessionEntity.lastError,+ ) {const updatedAt = yield* DateTime.now;sessionEntity = { ...sessionEntity, status, lastError, updatedAt };yield* emit({@@ -596,12 +597,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (});});- const updateProviderThread = (- state: PiThreadState,- patch: Partial<OrchestrationV2ProviderThread>,- retainedNativeTurnIds?: ReadonlyArray<string>,- ) =>- Effect.gen(function* () {+ const updateProviderThread =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ state: PiThreadState,+ patch: Partial<OrchestrationV2ProviderThread>,+ retainedNativeTurnIds?: ReadonlyArray<string>,+ ) {const updatedAt = yield* DateTime.now;state.providerThread = { ...state.providerThread, ...patch, updatedAt };yield* emit({@@ -692,8 +694,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (/*** Pi attaches the current message's cumulative usage to every streaming update (0.84.2+).*/- const reportLiveUsage = (turn: ActivePiTurn, usage: unknown) =>- Effect.gen(function* () {+ const reportLiveUsage =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (turn: ActivePiTurn, usage: unknown) {const usedTokens = nonNegativeInteger(usage, "totalTokens");if (usedTokens === undefined ||@@ -849,8 +852,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (});});- const emitStreamItem = (turn: ActivePiTurn, item: PiStreamItemState, streaming: boolean) =>- Effect.gen(function* () {+ const emitStreamItem =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ turn: ActivePiTurn,+ item: PiStreamItemState,+ streaming: boolean,+ ) {const emittedAt = yield* DateTime.now;const base = baseItemFields(turn, item.nativeItemId, item.startedAt, emittedAt);yield* emitItemNode(@@ -918,8 +926,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (});});- const scheduleStreamFlush = (turn: ActivePiTurn, item: PiStreamItemState) =>- Effect.gen(function* () {+ const scheduleStreamFlush =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (turn: ActivePiTurn, item: PiStreamItemState) {if (item.flushScheduled || item.completed) return;item.flushScheduled = true;yield* Effect.sleep(Duration.millis(STREAM_FLUSH_MS)).pipe(@@ -1159,52 +1168,55 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (}});- const cancelPrompt = (pending: PendingPiPrompt, resolvedAt: DateTime.Utc) =>- Effect.gen(function* () {- if (pending.expirationFiber !== null) yield* Fiber.interrupt(pending.expirationFiber);- yield* connection- .send({- type: "extension_ui_response",- id: pending.nativeRequestId,- cancelled: true,- })- .pipe(Effect.ignore);- pending.runtimeRequest = {- ...pending.runtimeRequest,+ const cancelPrompt = Effect.fn("PiAdapter.cancelPrompt")(function* (+ pending: PendingPiPrompt,+ resolvedAt: DateTime.Utc,+ ) {+ if (pending.expirationFiber !== null) yield* Fiber.interrupt(pending.expirationFiber);+ yield* connection+ .send({+ type: "extension_ui_response",+ id: pending.nativeRequestId,+ cancelled: true,+ })+ .pipe(Effect.ignore);+ pending.runtimeRequest = {+ ...pending.runtimeRequest,+ status: "cancelled",+ resolvedAt,+ };+ yield* emit({+ type: "runtime_request.updated",+ driver: PI_PROVIDER,+ threadId: pending.node.threadId,+ runtimeRequest: pending.runtimeRequest,+ });+ yield* emit({+ type: "node.updated",+ driver: PI_PROVIDER,+ node: { ...pending.node, status: "cancelled", completedAt: resolvedAt },+ });+ yield* emit({+ type: "turn_item.updated",+ driver: PI_PROVIDER,+ turnItem: {+ ...pending.turnItem,status: "cancelled",- resolvedAt,- };- yield* emit({- type: "runtime_request.updated",- driver: PI_PROVIDER,- threadId: pending.node.threadId,- runtimeRequest: pending.runtimeRequest,- });- yield* emit({- type: "node.updated",- driver: PI_PROVIDER,- node: { ...pending.node, status: "cancelled", completedAt: resolvedAt },- });- yield* emit({- type: "turn_item.updated",- driver: PI_PROVIDER,- turnItem: {- ...pending.turnItem,- status: "cancelled",- completedAt: resolvedAt,- updatedAt: resolvedAt,- },- });+ completedAt: resolvedAt,+ updatedAt: resolvedAt,+ },});+ });- const cancelPendingPrompts = (resolvedAt: DateTime.Utc) =>- Effect.gen(function* () {- const pending = Array.from(pendingPrompts.values());- pendingPrompts.clear();- yield* Effect.forEach(pending, (prompt) => cancelPrompt(prompt, resolvedAt), {- discard: true,- });+ const cancelPendingPrompts = Effect.fn("PiAdapter.cancelPendingPrompts")(function* (+ resolvedAt: DateTime.Utc,+ ) {+ const pending = Array.from(pendingPrompts.values());+ pendingPrompts.clear();+ yield* Effect.forEach(pending, (prompt) => cancelPrompt(prompt, resolvedAt), {+ discard: true,});+ });const handleExtensionUiRequest = Effect.fnUntraced(function* (event: PiRpcRecord) {const method = recordString(event, "method");@@ -2409,8 +2421,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (...turnInput,message: { ...turnInput.message, text: "/compact" },}),- startTurn: (turnInput) =>- Effect.gen(function* () {+ startTurn: Effect.fn("PiAdapter.startTurn")(+ function* (turnInput) {if (rollbackBarrier !== null)return yield* protocolError("Cannot start a Pi turn during rollback");const state = threadState;@@ -2585,20 +2597,23 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (// and extension commands may block on user dialogs indefinitely.// Rejections therefore return later as id-less response records// handled by the event pump.- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterTurnStartError({- driver: PI_PROVIDER,- threadId: turnInput.threadId,- providerThreadId: turnInput.providerThread.id,- runId: turnInput.runId,- cause,- }),+ },+ (effect, turnInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterTurnStartError({+ driver: PI_PROVIDER,+ threadId: turnInput.threadId,+ providerThreadId: turnInput.providerThread.id,+ runId: turnInput.runId,+ cause,+ }),+ ),),- ),- steerTurn: (steerInput: ProviderAdapter.ProviderAdapterV2SteerInput) =>- Effect.gen(function* () {+ ),+ steerTurn: Effect.fn("PiAdapter.steerTurn")(+ function* (steerInput: ProviderAdapter.ProviderAdapterV2SteerInput) {const turn = threadState?.activeTurn ?? null;if (turn === null || turn.providerTurn.id !== steerInput.providerTurnId) {return yield* protocolError(`Pi turn ${steerInput.providerTurnId} is not active`);@@ -2645,19 +2660,22 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (turn.settleProbeGeneration += 1;}),);- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterSteerRunError({- driver: PI_PROVIDER,- providerThreadId: steerInput.providerThread.id,- providerTurnId: steerInput.providerTurnId,- cause,- }),+ },+ (effect, steerInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterSteerRunError({+ driver: PI_PROVIDER,+ providerThreadId: steerInput.providerThread.id,+ providerTurnId: steerInput.providerTurnId,+ cause,+ }),+ ),),- ),- interruptTurn: (interruptInput) =>- Effect.gen(function* () {+ ),+ interruptTurn: Effect.fn("PiAdapter.interruptTurn")(+ function* (interruptInput) {const turn = threadState?.activeTurn ?? null;if (turn === null && interruptInput.requestRuntimeRestart === true) {if (pendingWake !== null)@@ -2697,19 +2715,22 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (yield* request({ type: "abort" }).pipe(Effect.tapError(() => Effect.sync(() => (turn.interrupted = false))),);- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterInterruptError({- driver: PI_PROVIDER,- providerThreadId: interruptInput.providerThread.id,- providerTurnId: interruptInput.providerTurnId,- cause,- }),+ },+ (effect, interruptInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterInterruptError({+ driver: PI_PROVIDER,+ providerThreadId: interruptInput.providerThread.id,+ providerTurnId: interruptInput.providerTurnId,+ cause,+ }),+ ),),- ),- respondToRuntimeRequest: (requestInput) =>- Effect.gen(function* () {+ ),+ respondToRuntimeRequest: Effect.fn("PiAdapter.respondToRuntimeRequest")(+ function* (requestInput) {const pending = pendingPrompts.get(String(requestInput.requestId));if (pending === undefined) {return yield* protocolError(@@ -2765,19 +2786,22 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (updatedAt: resolvedAt,},});- }).pipe(- sessionEventPermit.withPermits(1),- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({- driver: PI_PROVIDER,- requestId: requestInput.requestId,- cause,- }),+ },+ (effect, requestInput) =>+ effect.pipe(+ sessionEventPermit.withPermits(1),+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({+ driver: PI_PROVIDER,+ requestId: requestInput.requestId,+ cause,+ }),+ ),),- ),- readThreadSnapshot: (snapshotInput) =>- Effect.gen(function* () {+ ),+ readThreadSnapshot: Effect.fn("PiAdapter.readThreadSnapshot")(+ function* (snapshotInput) {const state = threadState;const boundNativeId = state?.providerThread.nativeThreadRef?.nativeId;const wantedNativeId = snapshotInput.providerThread.nativeThreadRef?.nativeId;@@ -2830,18 +2854,21 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (messages,runtimeRequests: [],};- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({- driver: PI_PROVIDER,- providerThreadId: snapshotInput.providerThread.id,- cause,- }),+ },+ (effect, snapshotInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({+ driver: PI_PROVIDER,+ providerThreadId: snapshotInput.providerThread.id,+ cause,+ }),+ ),),- ),- rollbackThread: (rollbackInput) =>- Effect.gen(function* () {+ ),+ rollbackThread: Effect.fn("PiAdapter.rollbackThread")(+ function* (rollbackInput) {const state = threadState;if (state === null) {return yield* protocolError("Pi session has no registered thread");@@ -2952,19 +2979,22 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (if (rollbackBarrier === barrier) rollbackBarrier = null;}),);- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterRollbackThreadError({- driver: PI_PROVIDER,- providerThreadId: rollbackInput.providerThread.id,- checkpointId: rollbackInput.target.checkpointId,- cause,- }),+ },+ (effect, rollbackInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterRollbackThreadError({+ driver: PI_PROVIDER,+ providerThreadId: rollbackInput.providerThread.id,+ checkpointId: rollbackInput.target.checkpointId,+ cause,+ }),+ ),),- ),- forkThread: (forkInput) =>- Effect.gen(function* () {+ ),+ forkThread: Effect.fn("PiAdapter.forkThread")(+ function* (forkInput) {if (threadState?.activeTurn != null) {return yield* protocolError("Cannot fork while a Pi turn is active");}@@ -3063,16 +3093,19 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (},false,);- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterForkThreadError({- driver: PI_PROVIDER,- providerThreadId: forkInput.sourceProviderThread.id,- cause,- }),+ },+ (effect, forkInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterForkThreadError({+ driver: PI_PROVIDER,+ providerThreadId: forkInput.sourceProviderThread.id,+ cause,+ }),+ ),),- ),+ ),};return runtime;}),diff --git a/packages/provider-pi/src/server/driver.ts b/packages/provider-pi/src/server/driver.tsindex 42e240fdc7b..e48700ff6af 100644--- a/packages/provider-pi/src/server/driver.ts+++ b/packages/provider-pi/src/server/driver.ts@@ -85,131 +85,137 @@ export const PiDriver: ProviderDriver<PiSettings, PiDriverEnv, Path.Path> = {usage: piUsageReader,configSchema: PiSettings,defaultConfig: (): PiSettings => decodePiSettings({}),- create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>- Effect.gen(function* () {- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const fileSystem = yield* FileSystem.FileSystem;- const pathService = yield* Path.Path;- const httpClient = yield* HttpClient.HttpClient;- const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;- const host = yield* ProviderHost.ProviderHost;- const { cwd } = host.paths;- const processEnv = yield* mergeProviderInstanceEnvironment(environment);- const continuationIdentity = defaultProviderContinuationIdentity({- driverKind: DRIVER_KIND,- instanceId,- });- const stampIdentity = withInstanceIdentity({- instanceId,- displayName,- accentColor,- continuationGroupKey: continuationIdentity.continuationKey,- });- const effectiveConfig = { ...config, enabled } satisfies PiSettings;- const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(- resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {- binaryPath: effectiveConfig.binaryPath,- env: processEnv,- }).pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, pathService),- ),- );-- const orchestrationAdapter = yield* PiAdapterV2Driver.create({- instanceId,- displayName,- accentColor,- environment,- enabled,- config,+ create: Effect.fn("PiDriver.create")(function* ({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }) {+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const fileSystem = yield* FileSystem.FileSystem;+ const pathService = yield* Path.Path;+ const httpClient = yield* HttpClient.HttpClient;+ const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;+ const host = yield* ProviderHost.ProviderHost;+ const { cwd } = host.paths;+ const processEnv = yield* mergeProviderInstanceEnvironment(environment);+ const continuationIdentity = defaultProviderContinuationIdentity({+ driverKind: DRIVER_KIND,+ instanceId,+ });+ const stampIdentity = withInstanceIdentity({+ instanceId,+ displayName,+ accentColor,+ continuationGroupKey: continuationIdentity.continuationKey,+ });+ const effectiveConfig = { ...config, enabled } satisfies PiSettings;+ const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(+ resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {+ binaryPath: effectiveConfig.binaryPath,+ env: processEnv,}).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to build Pi orchestration adapter.",- cause,- }),- ),- );- const textGeneration = yield* makePiTextGeneration(effectiveConfig, processEnv);-- const checkProvider = checkPiProviderStatus(effectiveConfig, processEnv, cwd).pipe(- Effect.map(stampIdentity),Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- );+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, pathService),+ ),+ );- const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);- const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<PiSettings>>({- resolveMaintenance,- getSettings: snapshotSettings.getSettings,- streamSettings: snapshotSettings.streamSettings,- haveSettingsChanged: haveProviderSnapshotSettingsChanged,- initialSnapshot: (settings) =>- buildInitialPiProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),- checkProvider,- enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>- resolveMaintenance().pipe(- Effect.flatMap((maintenanceCapabilities) =>- enrichPiSnapshot({- snapshot: currentSnapshot,- maintenanceCapabilities,- enableProviderUpdateChecks: settings.enableProviderUpdateChecks,- publishSnapshot,- }),- ),- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),- ),- }).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to build Pi snapshot.",- cause,+ const orchestrationAdapter = yield* PiAdapterV2Driver.create({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to build Pi orchestration adapter.",+ cause,+ }),+ ),+ );+ const textGeneration = yield* makePiTextGeneration(effectiveConfig, processEnv);++ const checkProvider = checkPiProviderStatus(effectiveConfig, processEnv, cwd).pipe(+ Effect.map(stampIdentity),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ );++ const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);+ const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<PiSettings>>({+ resolveMaintenance,+ getSettings: snapshotSettings.getSettings,+ streamSettings: snapshotSettings.streamSettings,+ haveSettingsChanged: haveProviderSnapshotSettingsChanged,+ initialSnapshot: (settings) =>+ buildInitialPiProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),+ checkProvider,+ enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>+ resolveMaintenance().pipe(+ Effect.flatMap((maintenanceCapabilities) =>+ enrichPiSnapshot({+ snapshot: currentSnapshot,+ maintenanceCapabilities,+ enableProviderUpdateChecks: settings.enableProviderUpdateChecks,+ publishSnapshot,}),+ ),+ Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),),- );+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to build Pi snapshot.",+ cause,+ }),+ ),+ );- return {- instanceId,- driverKind: DRIVER_KIND,- continuationIdentity,- displayName,- accentColor,- enabled,- snapshot,- snapshotForCwd: (workspaceCwd) =>- !effectiveConfig.enabled- ? snapshot.getSnapshot- : Effect.all([- snapshot.getSnapshot,- discoverPiCommandsForCwd(effectiveConfig, processEnv, workspaceCwd).pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to discover Pi workspace commands.",- cause,- }),- ),+ return {+ instanceId,+ driverKind: DRIVER_KIND,+ continuationIdentity,+ displayName,+ accentColor,+ enabled,+ snapshot,+ snapshotForCwd: (workspaceCwd) =>+ !effectiveConfig.enabled+ ? snapshot.getSnapshot+ : Effect.all([+ snapshot.getSnapshot,+ discoverPiCommandsForCwd(effectiveConfig, processEnv, workspaceCwd).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to discover Pi workspace commands.",+ cause,+ }),),- ]).pipe(- Effect.map(([machineSnapshot, commands]) => ({- ...machineSnapshot,- ...commands,- slashCommandsPending: false,- })),),- orchestrationAdapter,- textGeneration,- } satisfies ProviderInstance;- }),+ ]).pipe(+ Effect.map(([machineSnapshot, commands]) => ({+ ...machineSnapshot,+ ...commands,+ slashCommandsPending: false,+ })),+ ),+ orchestrationAdapter,+ textGeneration,+ } satisfies ProviderInstance;+ }),};diff --git a/packages/provider-pi/src/server/rpc.ts b/packages/provider-pi/src/server/rpc.tsindex aabce9e8ca3..c36a231051e 100644--- a/packages/provider-pi/src/server/rpc.ts+++ b/packages/provider-pi/src/server/rpc.ts@@ -167,14 +167,16 @@ function parsePiRecord(line: string): PiRpcRecord | undefined {* gone its pid/pgid can be recycled by the OS, so escalating blindly could* deliver SIGKILL to an unrelated process.*/-const terminatePiProcess = (kill: (signal: NodeJS.Signals) => boolean, hasExited: () => boolean) =>- Effect.gen(function* () {- if (hasExited()) return;- if (!kill("SIGTERM")) return;- yield* Effect.sleep(TERMINATION_GRACE);- if (hasExited()) return;- kill("SIGKILL");- });+const terminatePiProcess = Effect.fn("PiRpc.terminatePiProcess")(function* (+ kill: (signal: NodeJS.Signals) => boolean,+ hasExited: () => boolean,+) {+ if (hasExited()) return;+ if (!kill("SIGTERM")) return;+ yield* Effect.sleep(TERMINATION_GRACE);+ if (hasExited()) return;+ kill("SIGKILL");+});export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSpawnOptions) {const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;@@ -251,20 +253,20 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSpconst exitDeferred = yield* Deferred.make<number, PiRpcError>();let nextRequestId = 0;- const failTransport = (error: PiRpcError) =>- Effect.gen(function* () {- const claimed = yield* Deferred.fail(transportDown, error);- if (!claimed) return;- for (const [key, pending] of pendingRequests) {- pendingRequests.delete(key);- yield* Deferred.fail(pending.deferred, error);- }- yield* Queue.fail(outgoing, error);- yield* Queue.fail(events, error);- });+ const failTransport = Effect.fn("PiRpc.failTransport")(function* (error: PiRpcError) {+ const claimed = yield* Deferred.fail(transportDown, error);+ if (!claimed) return;+ for (const [key, pending] of pendingRequests) {+ pendingRequests.delete(key);+ yield* Deferred.fail(pending.deferred, error);+ }+ yield* Queue.fail(outgoing, error);+ yield* Queue.fail(events, error);+ });- const routeRecord = (record: PiRpcRecord) =>- Effect.gen(function* () {+ const routeRecord =+ /* Protocol records and writes include streaming deltas; avoid a span per record. */+ Effect.fnUntraced(function* (record: PiRpcRecord) {if (record["type"] === "response" && typeof record["id"] === "string") {const pending = pendingRequests.get(record["id"]);if (pending !== undefined) {@@ -386,8 +388,9 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSpEffect.forkIn(scope),);- const send = (record: PiRpcRecord): Effect.Effect<void, PiRpcError> =>- Effect.gen(function* () {+ const send =+ /* Protocol records and writes include streaming deltas; avoid a span per record. */+ Effect.fnUntraced(function* (record: PiRpcRecord): Effect.fn.Return<void, PiRpcError> {const accepted = yield* Queue.offer(outgoing,new TextEncoder().encode(`${encodeJsonLine(record)}\n`),@@ -397,32 +400,31 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSp}});- const request = (+ const request = Effect.fn("PiRpc.request")(function* (record: PiRpcRecord,timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,- ): Effect.Effect<unknown, PiRpcError | PiRpcTimeoutError> =>- Effect.gen(function* () {- const id = `t3-${nextRequestId++}`;- const deferred = yield* Deferred.make<unknown, PiRpcError>();- pendingRequests.set(id, { deferred });- yield* send({ ...record, id }).pipe(- Effect.tapError(() => Effect.sync(() => pendingRequests.delete(id))),- );- return yield* Effect.raceFirst(Deferred.await(deferred), Deferred.await(transportDown)).pipe(- Effect.timeoutOrElse({- duration: Duration.millis(timeoutMs),- orElse: () =>- Effect.fail(- new PiRpcTimeoutError({- operation: String(record["type"] ?? "request"),- timeoutMs,- }),- ),- }),- Effect.onInterrupt(() => Effect.sync(() => pendingRequests.delete(id))),- Effect.onError(() => Effect.sync(() => pendingRequests.delete(id))),- );- });+ ): Effect.fn.Return<unknown, PiRpcError | PiRpcTimeoutError> {+ const id = `t3-${nextRequestId++}`;+ const deferred = yield* Deferred.make<unknown, PiRpcError>();+ pendingRequests.set(id, { deferred });+ yield* send({ ...record, id }).pipe(+ Effect.tapError(() => Effect.sync(() => pendingRequests.delete(id))),+ );+ return yield* Effect.raceFirst(Deferred.await(deferred), Deferred.await(transportDown)).pipe(+ Effect.timeoutOrElse({+ duration: Duration.millis(timeoutMs),+ orElse: () =>+ Effect.fail(+ new PiRpcTimeoutError({+ operation: String(record["type"] ?? "request"),+ timeoutMs,+ }),+ ),+ }),+ Effect.onInterrupt(() => Effect.sync(() => pendingRequests.delete(id))),+ Effect.onError(() => Effect.sync(() => pendingRequests.delete(id))),+ );+ });return {send,diff --git a/packages/provider-pi/src/server/status.ts b/packages/provider-pi/src/server/status.tsindex 7e964389c31..3030200c245 100644--- a/packages/provider-pi/src/server/status.ts+++ b/packages/provider-pi/src/server/status.ts@@ -156,28 +156,27 @@ const makePiDiscoveryConnection = Effect.fnUntraced(function* (return connection;});-const discoverPiViaRpc = (+const discoverPiViaRpc = Effect.fn("PiProviderStatus.discoverPiViaRpc")(function* (piSettings: PiSettings,environment: NodeJS.ProcessEnv,launchArgs: ReadonlyArray<string>,cwd?: string,-) =>- Effect.gen(function* () {- const connection = yield* makePiDiscoveryConnection(piSettings, environment, launchArgs, cwd);- const stateData = yield* connection.request({ type: "get_state" });- const modelsData = yield* connection.request({ type: "get_available_models" });- const commandsData = yield* connection- .request({ type: "get_commands" })- .pipe(Effect.orElseSucceed(() => undefined));- const discoveredModels = yield* Effect.fromResult(parseDiscoveredModels(modelsData, stateData));- const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);- return {- models: discoveredModels,- slashCommands: withPiBuiltinSlashCommands(slashCommands),- skills,- authenticated: discoveredModels.length > 0,- } satisfies PiDiscovery;- }).pipe(Effect.scoped);+) {+ const connection = yield* makePiDiscoveryConnection(piSettings, environment, launchArgs, cwd);+ const stateData = yield* connection.request({ type: "get_state" });+ const modelsData = yield* connection.request({ type: "get_available_models" });+ const commandsData = yield* connection+ .request({ type: "get_commands" })+ .pipe(Effect.orElseSucceed(() => undefined));+ const discoveredModels = yield* Effect.fromResult(parseDiscoveredModels(modelsData, stateData));+ const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);+ return {+ models: discoveredModels,+ slashCommands: withPiBuiltinSlashCommands(slashCommands),+ skills,+ authenticated: discoveredModels.length > 0,+ } satisfies PiDiscovery;+}, Effect.scoped);export const discoverPiCommandsForCwd = Effect.fn("discoverPiCommandsForCwd")(function* (piSettings: PiSettings, environment: NodeJS.ProcessEnv, cwd: string) {@@ -206,57 +205,57 @@ export const discoverPiCommandsForCwd = Effect.fn("discoverPiCommandsForCwd")(}),);-const runPiVersionCommand = (piSettings: PiSettings, environment: NodeJS.ProcessEnv) =>- Effect.gen(function* () {- const command = piSettings.binaryPath || "pi";- const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {- env: environment,- });- return yield* spawnAndCollect(- command,- ChildProcess.make(spawnCommand.command, spawnCommand.args, {- env: environment,- shell: spawnCommand.shell,- }),- );+const runPiVersionCommand = Effect.fn("PiProviderStatus.runPiVersionCommand")(function* (+ piSettings: PiSettings,+ environment: NodeJS.ProcessEnv,+) {+ const command = piSettings.binaryPath || "pi";+ const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {+ env: environment,});+ return yield* spawnAndCollect(+ command,+ ChildProcess.make(spawnCommand.command, spawnCommand.args, {+ env: environment,+ shell: spawnCommand.shell,+ }),+ );+});-export function buildInitialPiProviderSnapshot(- piSettings: PiSettings,-): Effect.Effect<ServerProviderDraft> {- return Effect.gen(function* () {- const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);- const models = piModelsFromSettings(piSettings.customModels);- if (!piSettings.enabled) {- return buildServerProvider({- presentation: PI_PRESENTATION,- enabled: false,- checkedAt,- models,- probe: {- installed: false,- version: null,- status: "warning",- auth: { status: "unknown" },- message: "Pi is disabled in T3 Code settings.",- },- });- }+export const buildInitialPiProviderSnapshot = Effect.fn(+ "PiProviderStatus.buildInitialPiProviderSnapshot",+)(function* (piSettings: PiSettings): Effect.fn.Return<ServerProviderDraft> {+ const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);+ const models = piModelsFromSettings(piSettings.customModels);+ if (!piSettings.enabled) {return buildServerProvider({presentation: PI_PRESENTATION,- enabled: true,+ enabled: false,checkedAt,models,probe: {- installed: true,+ installed: false,version: null,status: "warning",auth: { status: "unknown" },- message: "Checking Pi CLI availability...",+ message: "Pi is disabled in T3 Code settings.",},});+ }+ return buildServerProvider({+ presentation: PI_PRESENTATION,+ enabled: true,+ checkedAt,+ models,+ probe: {+ installed: true,+ version: null,+ status: "warning",+ auth: { status: "unknown" },+ message: "Checking Pi CLI availability...",+ },});-}+});export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function* (piSettings: PiSettings,diff --git a/packages/provider-pi/src/server/textGeneration.ts b/packages/provider-pi/src/server/textGeneration.tsindex d36770a40d7..29bf67c3d59 100644--- a/packages/provider-pi/src/server/textGeneration.ts+++ b/packages/provider-pi/src/server/textGeneration.ts@@ -21,9 +21,10 @@ export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function*) {const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const runPiJson: TextGenerationOperations.Runner = (request) => {- const { operation, cwd, prompt, modelSelection } = request;- return Effect.gen(function* () {+ const runPiJson: TextGenerationOperations.Runner = Effect.fn("PiTextGeneration.runPiJson")(+ function* (request) {+ const { operation, cwd, prompt, modelSelection } = request;+const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);if (!resolvedLaunchArgs.ok) {return yield* new TextGenerationError({@@ -87,27 +88,31 @@ export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function*});}return yield* TextGenerationOperations.decodeJsonReply(request, "Pi", text);- }).pipe(- Effect.timeoutOption(PI_TIMEOUT_MS),- Effect.flatMap(- Option.match({- onNone: () =>- Effect.fail(new TextGenerationError({ operation, detail: "Pi request timed out." })),- onSome: (value) => Effect.succeed(value),- }),- ),- Effect.mapError((cause) =>- isTextGenerationError(cause)- ? cause- : new TextGenerationError({- operation,- detail: "Pi text generation failed.",- cause,- }),- ),- Effect.scoped,- );- };+ },+ (effect, request) => {+ const { operation } = request;+ return effect.pipe(+ Effect.timeoutOption(PI_TIMEOUT_MS),+ Effect.flatMap(+ Option.match({+ onNone: () =>+ Effect.fail(new TextGenerationError({ operation, detail: "Pi request timed out." })),+ onSome: (value) => Effect.succeed(value),+ }),+ ),+ Effect.mapError((cause) =>+ isTextGenerationError(cause)+ ? cause+ : new TextGenerationError({+ operation,+ detail: "Pi text generation failed.",+ cause,+ }),+ ),+ Effect.scoped,+ );+ },+ );return TextGenerationOperations.fromRunner("PiTextGeneration",