@devries-cameron20 / t3code Mirror · read-only / commits / 05ad901e49
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 00:30 UTC

refactor(provider): trace adapter operations without per-chunk spans (#21992)

Julius Marminge committed Oct 19, 2026 at 18:30 UTC 05ad901e4947aacf7ddfea5945f1933e7bf4aed3
33 files changed +4058 -3945
packages/provider-acp/src/server/AcpSessionRuntime.ts
+1318 -1340
@@ -1256,1270 +1256,1264 @@ interface AcpActivePrompt {
1256 readonly completed: Deferred.Deferred<void>;
1257 }
1258
1259 -export const make = (
1259 +export const make = Effect.fn("AcpSessionRuntime.make")(function* (
1260 options: AcpSessionRuntimeOptions,
1261 -): Effect.Effect<
1261 +): Effect.fn.Return<
1262 AcpSessionRuntime["Service"],
1263 EffectAcpErrors.AcpError,
1264 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
1265 -> =>
1266 - Effect.gen(function* () {
1267 - const crypto = yield* Crypto.Crypto;
1268 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1269 - const runtimeScope = yield* Scope.fork(yield* Scope.Scope);
1270 - const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
1271 - const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
1272 - const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallTrackedState>());
1273 - const shownToolCallIds = new Set<string>();
1274 - const assistantItemRuntimeId = yield* crypto.randomUUIDv4().pipe(
1275 - Effect.mapError(
1276 - (cause) =>
1277 - new EffectAcpErrors.AcpTransportError({
1278 - detail: "Failed to generate an ACP assistant item runtime identifier.",
1279 - cause,
1265 +> {
1266 + const crypto = yield* Crypto.Crypto;
1267 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1268 + const runtimeScope = yield* Scope.fork(yield* Scope.Scope);
1269 + const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
1270 + const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
1271 + const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallTrackedState>());
1272 + const shownToolCallIds = new Set<string>();
1273 + const assistantItemRuntimeId = yield* crypto.randomUUIDv4().pipe(
1274 + Effect.mapError(
1275 + (cause) =>
1276 + new EffectAcpErrors.AcpTransportError({
1277 + detail: "Failed to generate an ACP assistant item runtime identifier.",
1278 + cause,
1279 + }),
1280 + ),
1281 + );
1282 + const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
1283 + const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
1284 + const initializeStateRef = yield* Ref.make<AcpInitializeState>({ _tag: "NotStarted" });
1285 + const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
1286 + const startupMetadataRef = yield* Ref.make<ReadonlyArray<EffectAcpSchema.SessionNotification>>(
1287 + [],
1288 + );
1289 + const notificationSemaphore = yield* Semaphore.make(1);
1290 + const terminationErrorRef = yield* Ref.make<Option.Option<EffectAcpErrors.AcpError>>(
1291 + Option.none(),
1292 + );
1293 + const stoppingRef = yield* Ref.make(false);
1294 + const stderrFailure = yield* Deferred.make<never, EffectAcpErrors.AcpError>();
1295 + const stderrTailRef = yield* Ref.make("");
1296 + const homeDirectory = yield* HostProcess.HomeDirectory;
1297 + const stderrDrained = yield* Deferred.make<void>();
1298 + const runtimeClosed = yield* Deferred.make<void>();
1299 + const promptSerializationSemaphore = yield* Semaphore.make(1);
1300 + const sessionLoadSemaphore = yield* Semaphore.make(1);
1301 + const promptDispatchSemaphore = yield* Semaphore.make(1);
1302 + const activePromptRef = yield* Ref.make<Option.Option<AcpActivePrompt>>(Option.none());
1303 + const assistantUpdatesOpenRef = yield* Ref.make(true);
1304 + const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());
1305 +
1306 + const ensureConnected = Effect.gen(function* () {
1307 + const error = yield* Ref.get(terminationErrorRef);
1308 + if (Option.isSome(error)) {
1309 + return yield* error.value;
1310 + }
1311 + if (yield* Ref.get(stoppingRef)) {
1312 + return yield* new EffectAcpErrors.AcpTransportError({
1313 + detail: "The ACP session runtime is closed.",
1314 + cause: undefined,
1315 + });
1316 + }
1317 + });
1318 +
1319 + const enrichProcessExitWithStderr = (
1320 + error: EffectAcpErrors.AcpError,
1321 + ): Effect.Effect<EffectAcpErrors.AcpError> =>
1322 + error._tag !== "AcpProcessExitedError" || (error.stderr?.trim().length ?? 0) > 0
1323 + ? Effect.succeed(error)
1324 + : Deferred.await(stderrDrained).pipe(
1325 + Effect.timeout("250 millis"),
1326 + Effect.ignore,
1327 + Effect.andThen(Ref.get(stderrTailRef)),
1328 + Effect.map((tail) => {
1329 + const stderr = sanitizeAcpStderrExcerpt(tail, homeDirectory);
1330 + return stderr.length === 0
1331 + ? error
1332 + : new EffectAcpErrors.AcpProcessExitedError({
1333 + ...(error.code !== undefined ? { code: error.code } : {}),
1334 + ...(error.pid !== undefined ? { pid: error.pid } : {}),
1335 + stderr,
1336 + ...(error.cause !== undefined ? { cause: error.cause } : {}),
1337 + });
1338 }),
1281 - ),
1282 - );
1283 - const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
1284 - const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
1285 - const initializeStateRef = yield* Ref.make<AcpInitializeState>({ _tag: "NotStarted" });
1286 - const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
1287 - const startupMetadataRef = yield* Ref.make<ReadonlyArray<EffectAcpSchema.SessionNotification>>(
1288 - [],
1289 - );
1290 - const notificationSemaphore = yield* Semaphore.make(1);
1291 - const terminationErrorRef = yield* Ref.make<Option.Option<EffectAcpErrors.AcpError>>(
1292 - Option.none(),
1339 + );
1340 +
1341 + const recordTermination = Effect.fn("AcpSessionRuntime.recordTermination")(function* (
1342 + error: EffectAcpErrors.AcpError,
1343 + ) {
1344 + if (yield* Ref.get(stoppingRef)) {
1345 + return;
1346 + }
1347 + const enriched = yield* enrichProcessExitWithStderr(error);
1348 + const firstTermination = yield* Ref.modify(terminationErrorRef, (current) =>
1349 + Option.isSome(current)
1350 + ? ([false, current] as const)
1351 + : ([true, Option.some(enriched)] as const),
1352 );
1294 - const stoppingRef = yield* Ref.make(false);
1295 - const stderrFailure = yield* Deferred.make<never, EffectAcpErrors.AcpError>();
1296 - const stderrTailRef = yield* Ref.make("");
1297 - const homeDirectory = yield* HostProcess.HomeDirectory;
1298 - const stderrDrained = yield* Deferred.make<void>();
1299 - const runtimeClosed = yield* Deferred.make<void>();
1300 - const promptSerializationSemaphore = yield* Semaphore.make(1);
1301 - const sessionLoadSemaphore = yield* Semaphore.make(1);
1302 - const promptDispatchSemaphore = yield* Semaphore.make(1);
1303 - const activePromptRef = yield* Ref.make<Option.Option<AcpActivePrompt>>(Option.none());
1304 - const assistantUpdatesOpenRef = yield* Ref.make(true);
1305 - const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());
1306 -
1307 - const ensureConnected = Effect.gen(function* () {
1308 - const error = yield* Ref.get(terminationErrorRef);
1309 - if (Option.isSome(error)) {
1310 - return yield* error.value;
1311 - }
1312 - if (yield* Ref.get(stoppingRef)) {
1313 - return yield* new EffectAcpErrors.AcpTransportError({
1314 - detail: "The ACP session runtime is closed.",
1315 - cause: undefined,
1316 - });
1317 - }
1318 - });
1353 + if (!firstTermination) {
1354 + return;
1355 + }
1356 + yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
1357 + yield* Queue.offer(eventQueue, { _tag: "ConnectionTerminated", error: enriched });
1358 + });
1359
1320 - const enrichProcessExitWithStderr = (
1321 - error: EffectAcpErrors.AcpError,
1322 - ): Effect.Effect<EffectAcpErrors.AcpError> =>
1323 - error._tag !== "AcpProcessExitedError" || (error.stderr?.trim().length ?? 0) > 0
1324 - ? Effect.succeed(error)
1325 - : Deferred.await(stderrDrained).pipe(
1326 - Effect.timeout("250 millis"),
1327 - Effect.ignore,
1328 - Effect.andThen(Ref.get(stderrTailRef)),
1329 - Effect.map((tail) => {
1330 - const stderr = sanitizeAcpStderrExcerpt(tail, homeDirectory);
1331 - return stderr.length === 0
1332 - ? error
1333 - : new EffectAcpErrors.AcpProcessExitedError({
1334 - ...(error.code !== undefined ? { code: error.code } : {}),
1335 - ...(error.pid !== undefined ? { pid: error.pid } : {}),
1336 - stderr,
1337 - ...(error.cause !== undefined ? { cause: error.cause } : {}),
1338 - });
1360 + const logRequest = (event: AcpSessionRequestLogEvent) =>
1361 + options.requestLogger ? options.requestLogger(event) : Effect.void;
1362 +
1363 + const runLoggedRequest = <A>(
1364 + method: string,
1365 + payload: unknown,
1366 + effect: Effect.Effect<A, EffectAcpErrors.AcpError>,
1367 + ): Effect.Effect<A, EffectAcpErrors.AcpError> =>
1368 + logRequest({ method, payload, status: "started" }).pipe(
1369 + Effect.flatMap(() =>
1370 + (options.onStderr ? Effect.raceFirst(effect, Deferred.await(stderrFailure)) : effect).pipe(
1371 + Effect.catch((error) =>
1372 + enrichProcessExitWithStderr(error).pipe(Effect.flatMap(Effect.fail)),
1373 + ),
1374 + Effect.tap((result) =>
1375 + logRequest({
1376 + method,
1377 + payload,
1378 + status: "succeeded",
1379 + result,
1380 }),
1340 - );
1341 -
1342 - const recordTermination = Effect.fn("AcpSessionRuntime.recordTermination")(function* (
1343 - error: EffectAcpErrors.AcpError,
1344 - ) {
1345 - if (yield* Ref.get(stoppingRef)) {
1346 - return;
1347 - }
1348 - const enriched = yield* enrichProcessExitWithStderr(error);
1349 - const firstTermination = yield* Ref.modify(terminationErrorRef, (current) =>
1350 - Option.isSome(current)
1351 - ? ([false, current] as const)
1352 - : ([true, Option.some(enriched)] as const),
1353 - );
1354 - if (!firstTermination) {
1355 - return;
1356 - }
1357 - yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
1358 - yield* Queue.offer(eventQueue, { _tag: "ConnectionTerminated", error: enriched });
1359 - });
1360 -
1361 - const logRequest = (event: AcpSessionRequestLogEvent) =>
1362 - options.requestLogger ? options.requestLogger(event) : Effect.void;
1363 -
1364 - const runLoggedRequest = <A>(
1365 - method: string,
1366 - payload: unknown,
1367 - effect: Effect.Effect<A, EffectAcpErrors.AcpError>,
1368 - ): Effect.Effect<A, EffectAcpErrors.AcpError> =>
1369 - logRequest({ method, payload, status: "started" }).pipe(
1370 - Effect.flatMap(() =>
1371 - (options.onStderr
1372 - ? Effect.raceFirst(effect, Deferred.await(stderrFailure))
1373 - : effect
1374 - ).pipe(
1375 - Effect.catch((error) =>
1376 - enrichProcessExitWithStderr(error).pipe(Effect.flatMap(Effect.fail)),
1377 - ),
1378 - Effect.tap((result) =>
1379 - logRequest({
1380 - method,
1381 - payload,
1382 - status: "succeeded",
1383 - result,
1384 - }),
1385 - ),
1386 - Effect.onError((cause) =>
1387 - logRequest({
1388 - method,
1389 - payload,
1390 - status: "failed",
1391 - cause,
1392 - }),
1393 - ),
1381 ),
1395 - ),
1396 - );
1397 -
1398 - const spawnCommand =
1399 - options.spawn.shell === false
1400 - ? { command: options.spawn.command, args: options.spawn.args, shell: false }
1401 - : yield* resolveSpawnCommand(options.spawn.command, options.spawn.args, {
1402 - ...(options.spawn.env ? { env: options.spawn.env } : {}),
1403 - extendEnv: options.spawn.extendEnv ?? true,
1404 - });
1405 - const linuxCgroupLease =
1406 - options.ownDescendantProcessGroups === true && options.processGroupPlatform === "linux"
1407 - ? yield* Effect.sync(() => {
1408 - try {
1409 - if (options.linuxCgroupController === null) return undefined;
1410 - return (options.linuxCgroupController ?? makeLinuxCgroupController()).create();
1411 - } catch {
1412 - return undefined;
1413 - }
1414 - })
1415 - : undefined;
1416 - // This is lifecycle containment for inherited provider work. It is not a
1417 - // security boundary against a provider that can modify its delegated cgroup.
1418 - if (linuxCgroupLease !== undefined) {
1419 - yield* Scope.addFinalizer(
1420 - runtimeScope,
1421 - Effect.uninterruptible(terminateLinuxCgroupLease(linuxCgroupLease)).pipe(
1422 - Effect.ignoreCause({ log: true }),
1423 - ),
1424 - );
1425 - }
1426 - const containedTargetCommand =
1427 - linuxCgroupLease === undefined || NodePath.isAbsolute(spawnCommand.command)
1428 - ? spawnCommand.command
1429 - : yield* Effect.gen(function* () {
1430 - const resolved = resolveLinuxCgroupTargetCommand(
1431 - spawnCommand.command,
1432 - options.spawn.cwd ?? options.cwd,
1433 - { ...process.env, ...options.spawn.env },
1434 - );
1435 - if (resolved !== undefined) return resolved;
1436 - return yield* new EffectAcpErrors.AcpSpawnError({
1437 - command: options.spawn.command,
1438 - cause: new Error("Contained ACP command was not found on PATH"),
1439 - });
1440 - });
1441 - const scopedSpawnCommand =
1442 - linuxCgroupLease !== undefined || spawnCommand.shell
1443 - ? spawnCommand
1444 - : {
1445 - ...(yield* (yield* AgentScope).wrap({
1446 - command: spawnCommand.command,
1447 - args: spawnCommand.args,
1448 - name: "acp",
1449 - threadId: yield* AgentScopeThreadId,
1450 - env: { ...process.env, ...options.spawn.env },
1451 - })),
1452 - shell: false,
1453 - };
1454 - const containedSpawnCommand =
1455 - linuxCgroupLease === undefined
1456 - ? scopedSpawnCommand
1457 - : {
1458 - ...wrapCommandForLinuxCgroup(
1459 - linuxCgroupLease,
1460 - containedTargetCommand,
1461 - spawnCommand.args,
1462 - ),
1463 - shell: false,
1464 - };
1465 - const spawnEnvironment =
1466 - linuxCgroupLease === undefined
1467 - ? options.spawn.env
1468 - : {
1469 - ...options.spawn.env,
1470 - ELECTRON_RUN_AS_NODE: "1",
1471 - T3_ACP_CGROUP_WRAPPER: "1",
1472 - };
1473 - const child = yield* spawner
1474 - .spawn(
1475 - ChildProcess.make(containedSpawnCommand.command, containedSpawnCommand.args, {
1476 - ...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),
1477 - ...(spawnEnvironment ? { env: spawnEnvironment } : {}),
1478 - extendEnv: options.spawn.extendEnv ?? true,
1479 - ...(options.ownDetachedProcessGroup === undefined
1480 - ? {}
1481 - : { detached: options.ownDetachedProcessGroup }),
1482 - shell: containedSpawnCommand.shell,
1483 - }),
1484 - )
1485 - .pipe(
1486 - Effect.provideService(Scope.Scope, runtimeScope),
1487 - Effect.mapError(
1488 - (cause) =>
1489 - new EffectAcpErrors.AcpSpawnError({
1490 - command: options.spawn.command,
1382 + Effect.onError((cause) =>
1383 + logRequest({
1384 + method,
1385 + payload,
1386 + status: "failed",
1387 cause,
1388 }),
1389 + ),
1390 ),
1494 - );
1391 + ),
1392 + );
1393
1496 - const posixOwnershipLedger = new Map<string, AcpOwnedPosixProcess>();
1497 - const posixOwnershipFrontier = new Map<number, AcpOwnedPosixProcess>();
1498 - const posixOwnershipChildQueues = new Map<number, Array<number>>();
1499 - const posixOwnershipRoot: AcpPosixOwnershipRoot = { value: undefined };
1500 - const posixController =
1501 - options.ownDescendantProcessGroups === true
1502 - ? yield* Effect.try({
1503 - try: () => {
1504 - if (options.posixProcessTreeController !== undefined) {
1505 - return options.posixProcessTreeController;
1506 - }
1507 - if (options.processGroupPlatform === undefined) {
1508 - throw new AcpProcessGroupTerminationError({
1509 - detail: "POSIX ACP descendant ownership requires a supported host platform",
1510 - });
1511 - }
1512 - return makePosixProcessTreeController(options.processGroupPlatform);
1513 - },
1514 - catch: (cause) =>
1515 - new EffectAcpErrors.AcpSpawnError({ command: options.spawn.command, cause }),
1516 - })
1517 - : undefined;
1518 - if (posixController !== undefined) {
1519 - const observeOwnership = () =>
1520 - observePosixOwnershipLedger({
1521 - childQueues: posixOwnershipChildQueues,
1522 - controller: posixController,
1523 - frontier: posixOwnershipFrontier,
1524 - ledger: posixOwnershipLedger,
1525 - root: posixOwnershipRoot,
1526 - rootPid: Number(child.pid),
1394 + const spawnCommand =
1395 + options.spawn.shell === false
1396 + ? { command: options.spawn.command, args: options.spawn.args, shell: false }
1397 + : yield* resolveSpawnCommand(options.spawn.command, options.spawn.args, {
1398 + ...(options.spawn.env ? { env: options.spawn.env } : {}),
1399 + extendEnv: options.spawn.extendEnv ?? true,
1400 });
1528 - yield* Effect.try({
1529 - try: observeOwnership,
1530 - catch: (cause) =>
1531 - new EffectAcpErrors.AcpSpawnError({ command: options.spawn.command, cause }),
1532 - });
1533 - yield* observePosixOwnershipLedgerContinuously({
1401 + const linuxCgroupLease =
1402 + options.ownDescendantProcessGroups === true && options.processGroupPlatform === "linux"
1403 + ? yield* Effect.sync(() => {
1404 + try {
1405 + if (options.linuxCgroupController === null) return undefined;
1406 + return (options.linuxCgroupController ?? makeLinuxCgroupController()).create();
1407 + } catch {
1408 + return undefined;
1409 + }
1410 + })
1411 + : undefined;
1412 + // This is lifecycle containment for inherited provider work. It is not a
1413 + // security boundary against a provider that can modify its delegated cgroup.
1414 + if (linuxCgroupLease !== undefined) {
1415 + yield* Scope.addFinalizer(
1416 + runtimeScope,
1417 + Effect.uninterruptible(terminateLinuxCgroupLease(linuxCgroupLease)).pipe(
1418 + Effect.ignoreCause({ log: true }),
1419 + ),
1420 + );
1421 + }
1422 + const containedTargetCommand =
1423 + linuxCgroupLease === undefined || NodePath.isAbsolute(spawnCommand.command)
1424 + ? spawnCommand.command
1425 + : yield* Effect.gen(function* () {
1426 + const resolved = resolveLinuxCgroupTargetCommand(
1427 + spawnCommand.command,
1428 + options.spawn.cwd ?? options.cwd,
1429 + { ...process.env, ...options.spawn.env },
1430 + );
1431 + if (resolved !== undefined) return resolved;
1432 + return yield* new EffectAcpErrors.AcpSpawnError({
1433 + command: options.spawn.command,
1434 + cause: new Error("Contained ACP command was not found on PATH"),
1435 + });
1436 + });
1437 + const scopedSpawnCommand =
1438 + linuxCgroupLease !== undefined || spawnCommand.shell
1439 + ? spawnCommand
1440 + : {
1441 + ...(yield* (yield* AgentScope).wrap({
1442 + command: spawnCommand.command,
1443 + args: spawnCommand.args,
1444 + name: "acp",
1445 + threadId: yield* AgentScopeThreadId,
1446 + env: { ...process.env, ...options.spawn.env },
1447 + })),
1448 + shell: false,
1449 + };
1450 + const containedSpawnCommand =
1451 + linuxCgroupLease === undefined
1452 + ? scopedSpawnCommand
1453 + : {
1454 + ...wrapCommandForLinuxCgroup(linuxCgroupLease, containedTargetCommand, spawnCommand.args),
1455 + shell: false,
1456 + };
1457 + const spawnEnvironment =
1458 + linuxCgroupLease === undefined
1459 + ? options.spawn.env
1460 + : {
1461 + ...options.spawn.env,
1462 + ELECTRON_RUN_AS_NODE: "1",
1463 + T3_ACP_CGROUP_WRAPPER: "1",
1464 + };
1465 + const child = yield* spawner
1466 + .spawn(
1467 + ChildProcess.make(containedSpawnCommand.command, containedSpawnCommand.args, {
1468 + ...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),
1469 + ...(spawnEnvironment ? { env: spawnEnvironment } : {}),
1470 + extendEnv: options.spawn.extendEnv ?? true,
1471 + ...(options.ownDetachedProcessGroup === undefined
1472 + ? {}
1473 + : { detached: options.ownDetachedProcessGroup }),
1474 + shell: containedSpawnCommand.shell,
1475 + }),
1476 + )
1477 + .pipe(
1478 + Effect.provideService(Scope.Scope, runtimeScope),
1479 + Effect.mapError(
1480 + (cause) =>
1481 + new EffectAcpErrors.AcpSpawnError({
1482 + command: options.spawn.command,
1483 + cause,
1484 + }),
1485 + ),
1486 + );
1487 +
1488 + const posixOwnershipLedger = new Map<string, AcpOwnedPosixProcess>();
1489 + const posixOwnershipFrontier = new Map<number, AcpOwnedPosixProcess>();
1490 + const posixOwnershipChildQueues = new Map<number, Array<number>>();
1491 + const posixOwnershipRoot: AcpPosixOwnershipRoot = { value: undefined };
1492 + const posixController =
1493 + options.ownDescendantProcessGroups === true
1494 + ? yield* Effect.try({
1495 + try: () => {
1496 + if (options.posixProcessTreeController !== undefined) {
1497 + return options.posixProcessTreeController;
1498 + }
1499 + if (options.processGroupPlatform === undefined) {
1500 + throw new AcpProcessGroupTerminationError({
1501 + detail: "POSIX ACP descendant ownership requires a supported host platform",
1502 + });
1503 + }
1504 + return makePosixProcessTreeController(options.processGroupPlatform);
1505 + },
1506 + catch: (cause) =>
1507 + new EffectAcpErrors.AcpSpawnError({ command: options.spawn.command, cause }),
1508 + })
1509 + : undefined;
1510 + if (posixController !== undefined) {
1511 + const observeOwnership = () =>
1512 + observePosixOwnershipLedger({
1513 childQueues: posixOwnershipChildQueues,
1514 controller: posixController,
1515 frontier: posixOwnershipFrontier,
1516 ledger: posixOwnershipLedger,
1517 root: posixOwnershipRoot,
1518 rootPid: Number(child.pid),
1540 - }).pipe(Effect.forkIn(runtimeScope));
1541 - }
1519 + });
1520 + yield* Effect.try({
1521 + try: observeOwnership,
1522 + catch: (cause) =>
1523 + new EffectAcpErrors.AcpSpawnError({ command: options.spawn.command, cause }),
1524 + });
1525 + yield* observePosixOwnershipLedgerContinuously({
1526 + childQueues: posixOwnershipChildQueues,
1527 + controller: posixController,
1528 + frontier: posixOwnershipFrontier,
1529 + ledger: posixOwnershipLedger,
1530 + root: posixOwnershipRoot,
1531 + rootPid: Number(child.pid),
1532 + }).pipe(Effect.forkIn(runtimeScope));
1533 + }
1534
1543 - const signalOwnedProcessGroup = (signal: NodeJS.Signals) =>
1544 - Effect.try({
1545 - try: () => {
1546 - signalProcessGroup(Number(child.pid), signal);
1547 - return true;
1548 - },
1549 - catch: (cause) =>
1550 - new AcpProcessGroupTerminationError({
1551 - cause,
1552 - detail: `Failed to signal ACP process group ${child.pid} with ${signal}`,
1553 - }),
1554 - }).pipe(
1555 - Effect.catch((error) => {
1556 - const cause = error.cause as NodeJS.ErrnoException | undefined;
1557 - return cause?.code === "ESRCH" ? Effect.succeed(false) : Effect.fail(error);
1535 + const signalOwnedProcessGroup = (signal: NodeJS.Signals) =>
1536 + Effect.try({
1537 + try: () => {
1538 + signalProcessGroup(Number(child.pid), signal);
1539 + return true;
1540 + },
1541 + catch: (cause) =>
1542 + new AcpProcessGroupTerminationError({
1543 + cause,
1544 + detail: `Failed to signal ACP process group ${child.pid} with ${signal}`,
1545 }),
1559 - );
1560 - const terminateWindowsProcessTree =
1561 - options.windowsProcessTreeTerminator ??
1562 - ((pid: number) =>
1563 - terminateWindowsProcessTreeWithTaskkill(pid).pipe(
1564 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1565 - ));
1566 - const terminatePosixProcessTree = (grace: Duration.Input, platformOverride?: NodeJS.Platform) =>
1567 - Effect.gen(function* () {
1568 - const platform = platformOverride ?? options.processGroupPlatform;
1569 - if (platform === undefined || platform === "win32") {
1570 - return yield* new AcpProcessGroupTerminationError({
1571 - detail: "POSIX ACP descendant ownership requires a supported host platform",
1572 - });
1573 - }
1574 - const controller = yield* Effect.try({
1575 - try: () => posixController ?? makePosixProcessTreeController(platform),
1576 - catch: (cause) =>
1577 - isAcpProcessGroupTerminationError(cause)
1578 - ? cause
1579 - : new AcpProcessGroupTerminationError({
1580 - cause,
1581 - detail: `Failed to initialize ACP descendant ownership on ${platform}`,
1582 - }),
1583 - });
1584 - yield* terminatePosixOwnedProcessTree({
1585 - controller,
1586 - grace,
1587 - ledger: posixOwnershipLedger,
1588 - root: posixOwnershipRoot,
1589 - rootPid: Number(child.pid),
1590 - });
1591 - });
1592 - const terminateOwnedProcessGroupImpl = Effect.gen(function* () {
1593 - if (options.ownDetachedProcessGroup !== true) return;
1594 - if (options.processGroupPlatform === undefined) {
1546 + }).pipe(
1547 + Effect.catch((error) => {
1548 + const cause = error.cause as NodeJS.ErrnoException | undefined;
1549 + return cause?.code === "ESRCH" ? Effect.succeed(false) : Effect.fail(error);
1550 + }),
1551 + );
1552 + const terminateWindowsProcessTree =
1553 + options.windowsProcessTreeTerminator ??
1554 + ((pid: number) =>
1555 + terminateWindowsProcessTreeWithTaskkill(pid).pipe(
1556 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1557 + ));
1558 + const terminatePosixProcessTree = Effect.fn("AcpSessionRuntime.terminatePosixProcessTree")(
1559 + function* (grace: Duration.Input, platformOverride?: NodeJS.Platform) {
1560 + const platform = platformOverride ?? options.processGroupPlatform;
1561 + if (platform === undefined || platform === "win32") {
1562 return yield* new AcpProcessGroupTerminationError({
1596 - detail: "Detached ACP process-group ownership requires a host platform",
1563 + detail: "POSIX ACP descendant ownership requires a supported host platform",
1564 });
1565 }
1599 - if (options.processGroupPlatform === "win32") {
1600 - return yield* terminateWindowsProcessTree(Number(child.pid));
1601 - }
1602 - if (linuxCgroupLease !== undefined) {
1603 - if (posixController !== undefined) {
1604 - yield* Effect.sync(() =>
1605 - signalLinuxCgroupRootTerm({
1606 - controller: posixController,
1607 - lease: linuxCgroupLease,
1608 - root: posixOwnershipRoot,
1609 - }),
1610 - );
1611 - }
1612 - const grace = options.processGroupTerminationGrace ?? "1 second";
1613 - if (grace !== 0) yield* Effect.sleep(grace);
1614 - return yield* terminateLinuxCgroupLease(linuxCgroupLease);
1615 - }
1616 - if (options.ownDescendantProcessGroups === true) {
1617 - return yield* terminatePosixProcessTree(options.processGroupTerminationGrace ?? "1 second");
1566 + const controller = yield* Effect.try({
1567 + try: () => posixController ?? makePosixProcessTreeController(platform),
1568 + catch: (cause) =>
1569 + isAcpProcessGroupTerminationError(cause)
1570 + ? cause
1571 + : new AcpProcessGroupTerminationError({
1572 + cause,
1573 + detail: `Failed to initialize ACP descendant ownership on ${platform}`,
1574 + }),
1575 + });
1576 + yield* terminatePosixOwnedProcessTree({
1577 + controller,
1578 + grace,
1579 + ledger: posixOwnershipLedger,
1580 + root: posixOwnershipRoot,
1581 + rootPid: Number(child.pid),
1582 + });
1583 + },
1584 + );
1585 + const terminateOwnedProcessGroupImpl = Effect.gen(function* () {
1586 + if (options.ownDetachedProcessGroup !== true) return;
1587 + if (options.processGroupPlatform === undefined) {
1588 + return yield* new AcpProcessGroupTerminationError({
1589 + detail: "Detached ACP process-group ownership requires a host platform",
1590 + });
1591 + }
1592 + if (options.processGroupPlatform === "win32") {
1593 + return yield* terminateWindowsProcessTree(Number(child.pid));
1594 + }
1595 + if (linuxCgroupLease !== undefined) {
1596 + if (posixController !== undefined) {
1597 + yield* Effect.sync(() =>
1598 + signalLinuxCgroupRootTerm({
1599 + controller: posixController,
1600 + lease: linuxCgroupLease,
1601 + root: posixOwnershipRoot,
1602 + }),
1603 + );
1604 }
1619 - const groupExisted = yield* signalOwnedProcessGroup("SIGTERM");
1620 - if (!groupExisted) return;
1605 const grace = options.processGroupTerminationGrace ?? "1 second";
1622 - if (grace !== 0) {
1623 - yield* Effect.sleep(grace);
1624 - }
1625 - yield* signalOwnedProcessGroup("SIGKILL");
1626 - }).pipe(withWallClock);
1627 - const terminateProcessGroup = yield* Effect.cached(
1628 - Effect.uninterruptible(terminateOwnedProcessGroupImpl),
1606 + if (grace !== 0) yield* Effect.sleep(grace);
1607 + return yield* terminateLinuxCgroupLease(linuxCgroupLease);
1608 + }
1609 + if (options.ownDescendantProcessGroups === true) {
1610 + return yield* terminatePosixProcessTree(options.processGroupTerminationGrace ?? "1 second");
1611 + }
1612 + const groupExisted = yield* signalOwnedProcessGroup("SIGTERM");
1613 + if (!groupExisted) return;
1614 + const grace = options.processGroupTerminationGrace ?? "1 second";
1615 + if (grace !== 0) {
1616 + yield* Effect.sleep(grace);
1617 + }
1618 + yield* signalOwnedProcessGroup("SIGKILL");
1619 + }).pipe(withWallClock);
1620 + const terminateProcessGroup = yield* Effect.cached(
1621 + Effect.uninterruptible(terminateOwnedProcessGroupImpl),
1622 + );
1623 + if (options.ownDetachedProcessGroup === true) {
1624 + const hostPlatform = yield* HostProcess.Platform;
1625 + const forceTerminateOwnedProcessGroup =
1626 + hostPlatform === "win32"
1627 + ? terminateWindowsProcessTreeWithTaskkill(Number(child.pid)).pipe(
1628 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1629 + )
1630 + : linuxCgroupLease !== undefined
1631 + ? terminateLinuxCgroupLease(linuxCgroupLease)
1632 + : options.ownDescendantProcessGroups === true
1633 + ? terminatePosixProcessTree(0, hostPlatform)
1634 + : signalOwnedProcessGroup("SIGKILL").pipe(Effect.asVoid);
1635 + yield* Scope.addFinalizer(
1636 + runtimeScope,
1637 + Effect.uninterruptible(forceTerminateOwnedProcessGroup).pipe(
1638 + Effect.ignoreCause({ log: true }),
1639 + ),
1640 );
1630 - if (options.ownDetachedProcessGroup === true) {
1631 - const hostPlatform = yield* HostProcess.Platform;
1632 - const forceTerminateOwnedProcessGroup =
1633 - hostPlatform === "win32"
1634 - ? terminateWindowsProcessTreeWithTaskkill(Number(child.pid)).pipe(
1635 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1636 - )
1637 - : linuxCgroupLease !== undefined
1638 - ? terminateLinuxCgroupLease(linuxCgroupLease)
1639 - : options.ownDescendantProcessGroups === true
1640 - ? terminatePosixProcessTree(0, hostPlatform)
1641 - : signalOwnedProcessGroup("SIGKILL").pipe(Effect.asVoid);
1642 - yield* Scope.addFinalizer(
1643 - runtimeScope,
1644 - Effect.uninterruptible(forceTerminateOwnedProcessGroup).pipe(
1645 - Effect.ignoreCause({ log: true }),
1641 + }
1642 + yield* child.stderr.pipe(
1643 + Stream.decodeText(),
1644 + Stream.runForEach((chunk) =>
1645 + Ref.update(stderrTailRef, (current) => appendAcpStderrTail(current, chunk)).pipe(
1646 + Effect.andThen(
1647 + options.onStderr ? options.onStderr(chunk.slice(-maxStderrChunkLength)) : Effect.void,
1648 ),
1647 - );
1648 - }
1649 - yield* child.stderr.pipe(
1650 - Stream.decodeText(),
1651 - Stream.runForEach((chunk) =>
1652 - Ref.update(stderrTailRef, (current) => appendAcpStderrTail(current, chunk)).pipe(
1653 - Effect.andThen(
1654 - options.onStderr ? options.onStderr(chunk.slice(-maxStderrChunkLength)) : Effect.void,
1655 - ),
1656 - Effect.catch((error) =>
1657 - Effect.gen(function* () {
1658 - yield* Deferred.fail(stderrFailure, error);
1659 - yield* recordTermination(error);
1660 - yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);
1661 - }),
1662 - ),
1649 + Effect.catch((error) =>
1650 + Effect.gen(function* () {
1651 + yield* Deferred.fail(stderrFailure, error);
1652 + yield* recordTermination(error);
1653 + yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);
1654 + }),
1655 ),
1656 ),
1665 - Effect.ensuring(Deferred.succeed(stderrDrained, undefined)),
1666 - Effect.ignore,
1667 - Effect.forkIn(runtimeScope),
1668 - );
1657 + ),
1658 + Effect.ensuring(Deferred.succeed(stderrDrained, undefined)),
1659 + Effect.ignore,
1660 + Effect.forkIn(runtimeScope),
1661 + );
1662
1670 - const acpContext = yield* Layer.build(
1671 - EffectAcpClient.layerChildProcess(child, {
1672 - ...(options.transformStdout ? { transformStdout: options.transformStdout } : {}),
1673 - ...(options.transformSessionUpdate
1674 - ? { transformSessionUpdate: options.transformSessionUpdate }
1675 - : {}),
1676 - ...(options.protocolLogging?.logIncoming !== undefined
1677 - ? { logIncoming: options.protocolLogging.logIncoming }
1678 - : {}),
1679 - ...(options.protocolLogging?.logOutgoing !== undefined
1680 - ? { logOutgoing: options.protocolLogging.logOutgoing }
1681 - : {}),
1682 - ...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
1683 - ...(options.onIncomingRequest ? { onIncomingRequest: options.onIncomingRequest } : {}),
1684 - onTermination: (error) =>
1685 - recordTermination(error).pipe(
1686 - Effect.andThen(options.onTermination?.(error) ?? Effect.void),
1687 - Effect.ensuring(
1688 - Scope.close(runtimeScope, Exit.fail(error)).pipe(Effect.forkDetach, Effect.asVoid),
1689 - ),
1663 + const acpContext = yield* Layer.build(
1664 + EffectAcpClient.layerChildProcess(child, {
1665 + ...(options.transformStdout ? { transformStdout: options.transformStdout } : {}),
1666 + ...(options.transformSessionUpdate
1667 + ? { transformSessionUpdate: options.transformSessionUpdate }
1668 + : {}),
1669 + ...(options.protocolLogging?.logIncoming !== undefined
1670 + ? { logIncoming: options.protocolLogging.logIncoming }
1671 + : {}),
1672 + ...(options.protocolLogging?.logOutgoing !== undefined
1673 + ? { logOutgoing: options.protocolLogging.logOutgoing }
1674 + : {}),
1675 + ...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
1676 + ...(options.onIncomingRequest ? { onIncomingRequest: options.onIncomingRequest } : {}),
1677 + onTermination: (error) =>
1678 + recordTermination(error).pipe(
1679 + Effect.andThen(options.onTermination?.(error) ?? Effect.void),
1680 + Effect.ensuring(
1681 + Scope.close(runtimeScope, Exit.fail(error)).pipe(Effect.forkDetach, Effect.asVoid),
1682 ),
1691 - ...(options.onOutgoingResponseFailure
1692 - ? { onOutgoingResponseFailure: options.onOutgoingResponseFailure }
1693 - : {}),
1694 - ...(options.onOutgoingResponse ? { onOutgoingResponse: options.onOutgoingResponse } : {}),
1695 - }),
1696 - ).pipe(Effect.provideService(Scope.Scope, runtimeScope));
1697 -
1698 - const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
1699 -
1700 - const processSessionUpdate = (notification: EffectAcpSchema.SessionNotification) =>
1701 - handleSessionUpdate({
1702 - queue: eventQueue,
1703 - modeStateRef,
1704 - configOptionsRef,
1705 - toolCallsRef,
1706 - shownToolCallIds,
1707 - assistantSegmentRef,
1708 - assistantItemRuntimeId,
1709 - params: notification,
1710 - });
1711 -
1712 - yield* acp.handleSessionUpdate((notification) =>
1713 - notificationSemaphore.withPermit(
1714 - Effect.gen(function* () {
1715 - if (Option.isSome(yield* Ref.get(terminationErrorRef))) {
1716 - return;
1717 - }
1718 - const gate = yield* Ref.get(sessionLoadGateRef);
1719 - // A different session can still have an in-flight prompt while this
1720 - // load replays history, so quarantine only the loading session.
1721 - const loadingThisSession =
1722 - Option.isSome(gate) &&
1723 - gate.value.active &&
1724 - notification.sessionId === gate.value.sessionId;
1725 - if (
1726 - loadingThisSession &&
1727 - sessionUpdateCountsAsLoadReplayActivity(notification, gate.value.sessionId)
1728 - ) {
1729 - const lastActivityAtMillis = yield* Clock.currentTimeMillis;
1730 - yield* Ref.set(
1731 - sessionLoadGateRef,
1732 - Option.some({
1733 - ...gate.value,
1734 - lastActivityAtMillis,
1735 - }),
1736 - );
1737 - }
1738 - if (sessionUpdateIsReplay(notification)) {
1739 - return;
1740 - }
1741 - const startState = yield* Ref.get(startStateRef);
1742 - if (startState._tag === "Starting") {
1743 - if (isStartupMetadataUpdate(notification)) {
1744 - yield* Ref.update(startupMetadataRef, (current) =>
1745 - [
1746 - ...current.filter(
1747 - (previous) =>
1748 - previous.sessionId !== notification.sessionId ||
1749 - previous.update.sessionUpdate !== notification.update.sessionUpdate,
1750 - ),
1751 - notification,
1752 - ].slice(-maxStartupMetadataUpdates),
1753 - );
1754 - }
1755 - return;
1756 - }
1757 - if (loadingThisSession) {
1758 - if (notification.update.sessionUpdate === "config_option_update") {
1759 - const candidateConfigOptions = notification.update.configOptions;
1760 - yield* Ref.update(sessionLoadGateRef, (current) =>
1761 - Option.isSome(current)
1762 - ? Option.some({ ...current.value, candidateConfigOptions })
1763 - : current,
1764 - );
1765 - }
1766 - return;
1767 - }
1768 - // One runtime projects one root ACP session. Child-session updates need
1769 - // explicit lineage routing and must never be flattened into this stream.
1770 - if (
1771 - startState._tag !== "Started" ||
1772 - notification.sessionId !== startState.result.sessionId
1773 - ) {
1774 - return;
1775 - }
1776 - if (
1777 - !(yield* Ref.get(assistantUpdatesOpenRef)) &&
1778 - (notification.update.sessionUpdate === "agent_message_chunk" ||
1779 - notification.update.sessionUpdate === "agent_thought_chunk")
1780 - ) {
1781 - return;
1782 - }
1783 - yield* processSessionUpdate(notification);
1784 - }),
1785 - ),
1786 - );
1787 - yield* Scope.addFinalizer(
1788 - runtimeScope,
1789 - Ref.set(stoppingRef, true).pipe(Effect.andThen(Deferred.succeed(runtimeClosed, undefined))),
1790 - );
1791 - const initializeClientCapabilities = {
1792 - fs: {
1793 - readTextFile: false,
1794 - writeTextFile: false,
1795 - ...options.clientCapabilities?.fs,
1796 - },
1797 - terminal: options.clientCapabilities?.terminal ?? false,
1798 - ...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),
1799 - ...(options.clientCapabilities?.elicitation
1800 - ? { elicitation: options.clientCapabilities.elicitation }
1683 + ),
1684 + ...(options.onOutgoingResponseFailure
1685 + ? { onOutgoingResponseFailure: options.onOutgoingResponseFailure }
1686 : {}),
1802 - ...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),
1803 - } satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
1804 -
1805 - const getStartedState = Effect.gen(function* () {
1806 - yield* ensureConnected;
1807 - const state = yield* Ref.get(startStateRef);
1808 - if (state._tag === "Started") {
1809 - return state.result;
1810 - }
1811 - return yield* new EffectAcpErrors.AcpTransportError({
1812 - detail: "ACP session runtime has not been started",
1813 - cause: "ACP session runtime has not been started",
1814 - });
1687 + ...(options.onOutgoingResponse ? { onOutgoingResponse: options.onOutgoingResponse } : {}),
1688 + }),
1689 + ).pipe(Effect.provideService(Scope.Scope, runtimeScope));
1690 +
1691 + const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
1692 +
1693 + const processSessionUpdate = (notification: EffectAcpSchema.SessionNotification) =>
1694 + handleSessionUpdate({
1695 + queue: eventQueue,
1696 + modeStateRef,
1697 + configOptionsRef,
1698 + toolCallsRef,
1699 + shownToolCallIds,
1700 + assistantSegmentRef,
1701 + assistantItemRuntimeId,
1702 + params: notification,
1703 });
1704
1817 - const validateConfigOptionValue = (
1818 - configId: string,
1819 - value: string | boolean,
1820 - ): Effect.Effect<void, EffectAcpErrors.AcpError> =>
1705 + yield* acp.handleSessionUpdate((notification) =>
1706 + notificationSemaphore.withPermit(
1707 Effect.gen(function* () {
1822 - const configOptions = yield* Ref.get(configOptionsRef);
1823 - const configOption = findSessionConfigOption(configOptions, configId);
1824 - if (!configOption) {
1708 + if (Option.isSome(yield* Ref.get(terminationErrorRef))) {
1709 + return;
1710 + }
1711 + const gate = yield* Ref.get(sessionLoadGateRef);
1712 + // A different session can still have an in-flight prompt while this
1713 + // load replays history, so quarantine only the loading session.
1714 + const loadingThisSession =
1715 + Option.isSome(gate) &&
1716 + gate.value.active &&
1717 + notification.sessionId === gate.value.sessionId;
1718 + if (
1719 + loadingThisSession &&
1720 + sessionUpdateCountsAsLoadReplayActivity(notification, gate.value.sessionId)
1721 + ) {
1722 + const lastActivityAtMillis = yield* Clock.currentTimeMillis;
1723 + yield* Ref.set(
1724 + sessionLoadGateRef,
1725 + Option.some({
1726 + ...gate.value,
1727 + lastActivityAtMillis,
1728 + }),
1729 + );
1730 + }
1731 + if (sessionUpdateIsReplay(notification)) {
1732 return;
1733 }
1827 - if (configOption.type === "boolean") {
1828 - if (typeof value === "boolean") {
1829 - return;
1734 + const startState = yield* Ref.get(startStateRef);
1735 + if (startState._tag === "Starting") {
1736 + if (isStartupMetadataUpdate(notification)) {
1737 + yield* Ref.update(startupMetadataRef, (current) =>
1738 + [
1739 + ...current.filter(
1740 + (previous) =>
1741 + previous.sessionId !== notification.sessionId ||
1742 + previous.update.sessionUpdate !== notification.update.sessionUpdate,
1743 + ),
1744 + notification,
1745 + ].slice(-maxStartupMetadataUpdates),
1746 + );
1747 }
1831 - return yield* new EffectAcpErrors.AcpRequestError({
1832 - code: -32602,
1833 - errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected boolean`,
1834 - data: {
1835 - configId: configOption.id,
1836 - expectedType: "boolean",
1837 - receivedValue: value,
1838 - },
1839 - });
1748 + return;
1749 }
1841 - if (typeof value !== "string") {
1842 - return yield* new EffectAcpErrors.AcpRequestError({
1843 - code: -32602,
1844 - errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected string`,
1845 - data: {
1846 - configId: configOption.id,
1847 - expectedType: "string",
1848 - receivedValue: value,
1849 - },
1850 - });
1750 + if (loadingThisSession) {
1751 + if (notification.update.sessionUpdate === "config_option_update") {
1752 + const candidateConfigOptions = notification.update.configOptions;
1753 + yield* Ref.update(sessionLoadGateRef, (current) =>
1754 + Option.isSome(current)
1755 + ? Option.some({ ...current.value, candidateConfigOptions })
1756 + : current,
1757 + );
1758 + }
1759 + return;
1760 }
1852 - const allowedValues = collectSessionConfigOptionValues(configOption);
1853 - if (allowedValues.includes(value)) {
1761 + // One runtime projects one root ACP session. Child-session updates need
1762 + // explicit lineage routing and must never be flattened into this stream.
1763 + if (
1764 + startState._tag !== "Started" ||
1765 + notification.sessionId !== startState.result.sessionId
1766 + ) {
1767 return;
1768 }
1769 if (
1857 - configOption === findModelConfigOption(configOptions) &&
1858 - options.customModels?.includes(value)
1770 + !(yield* Ref.get(assistantUpdatesOpenRef)) &&
1771 + (notification.update.sessionUpdate === "agent_message_chunk" ||
1772 + notification.update.sessionUpdate === "agent_thought_chunk")
1773 ) {
1774 return;
1775 }
1776 + yield* processSessionUpdate(notification);
1777 + }),
1778 + ),
1779 + );
1780 + yield* Scope.addFinalizer(
1781 + runtimeScope,
1782 + Ref.set(stoppingRef, true).pipe(Effect.andThen(Deferred.succeed(runtimeClosed, undefined))),
1783 + );
1784 + const initializeClientCapabilities = {
1785 + fs: {
1786 + readTextFile: false,
1787 + writeTextFile: false,
1788 + ...options.clientCapabilities?.fs,
1789 + },
1790 + terminal: options.clientCapabilities?.terminal ?? false,
1791 + ...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),
1792 + ...(options.clientCapabilities?.elicitation
1793 + ? { elicitation: options.clientCapabilities.elicitation }
1794 + : {}),
1795 + ...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),
1796 + } satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
1797 +
1798 + const getStartedState = Effect.gen(function* () {
1799 + yield* ensureConnected;
1800 + const state = yield* Ref.get(startStateRef);
1801 + if (state._tag === "Started") {
1802 + return state.result;
1803 + }
1804 + return yield* new EffectAcpErrors.AcpTransportError({
1805 + detail: "ACP session runtime has not been started",
1806 + cause: "ACP session runtime has not been started",
1807 + });
1808 + });
1809 +
1810 + const validateConfigOptionValue = Effect.fn("AcpSessionRuntime.validateConfigOptionValue")(
1811 + function* (
1812 + configId: string,
1813 + value: string | boolean,
1814 + ): Effect.fn.Return<void, EffectAcpErrors.AcpError> {
1815 + const configOptions = yield* Ref.get(configOptionsRef);
1816 + const configOption = findSessionConfigOption(configOptions, configId);
1817 + if (!configOption) {
1818 + return;
1819 + }
1820 + if (configOption.type === "boolean") {
1821 + if (typeof value === "boolean") {
1822 + return;
1823 + }
1824 + return yield* new EffectAcpErrors.AcpRequestError({
1825 + code: -32602,
1826 + errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected boolean`,
1827 + data: {
1828 + configId: configOption.id,
1829 + expectedType: "boolean",
1830 + receivedValue: value,
1831 + },
1832 + });
1833 + }
1834 + if (typeof value !== "string") {
1835 return yield* new EffectAcpErrors.AcpRequestError({
1836 code: -32602,
1864 - errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
1837 + errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected string`,
1838 data: {
1839 configId: configOption.id,
1867 - allowedValues,
1840 + expectedType: "string",
1841 receivedValue: value,
1842 },
1843 });
1844 + }
1845 + const allowedValues = collectSessionConfigOptionValues(configOption);
1846 + if (allowedValues.includes(value)) {
1847 + return;
1848 + }
1849 + if (
1850 + configOption === findModelConfigOption(configOptions) &&
1851 + options.customModels?.includes(value)
1852 + ) {
1853 + return;
1854 + }
1855 + return yield* new EffectAcpErrors.AcpRequestError({
1856 + code: -32602,
1857 + errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
1858 + data: {
1859 + configId: configOption.id,
1860 + allowedValues,
1861 + receivedValue: value,
1862 + },
1863 });
1864 + },
1865 + );
1866
1873 - const updateConfigOptions = Effect.fn("AcpSessionRuntime.updateConfigOptions")(function* (
1874 - response:
1875 - | EffectAcpSchema.SetSessionConfigOptionResponse
1876 - | EffectAcpSchema.ForkSessionResponse
1877 - | EffectAcpSchema.LoadSessionResponse
1878 - | EffectAcpSchema.NewSessionResponse
1879 - | EffectAcpSchema.ResumeSessionResponse,
1880 - ) {
1881 - const configOptions = sessionConfigOptionsFromSetup(response);
1882 - yield* Ref.set(configOptionsRef, configOptions);
1883 - yield* Queue.offer(eventQueue, {
1884 - _tag: "ConfigOptionsUpdated",
1885 - configOptions,
1886 - rawPayload: response,
1887 - });
1867 + const updateConfigOptions = Effect.fn("AcpSessionRuntime.updateConfigOptions")(function* (
1868 + response:
1869 + | EffectAcpSchema.SetSessionConfigOptionResponse
1870 + | EffectAcpSchema.ForkSessionResponse
1871 + | EffectAcpSchema.LoadSessionResponse
1872 + | EffectAcpSchema.NewSessionResponse
1873 + | EffectAcpSchema.ResumeSessionResponse,
1874 + ) {
1875 + const configOptions = sessionConfigOptionsFromSetup(response);
1876 + yield* Ref.set(configOptionsRef, configOptions);
1877 + yield* Queue.offer(eventQueue, {
1878 + _tag: "ConfigOptionsUpdated",
1879 + configOptions,
1880 + rawPayload: response,
1881 });
1882 + });
1883
1890 - const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>
1891 - Ref.update(modeStateRef, (current) =>
1892 - current ? { ...current, currentModeId: modeId } : current,
1893 - );
1884 + const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>
1885 + Ref.update(modeStateRef, (current) =>
1886 + current ? { ...current, currentModeId: modeId } : current,
1887 + );
1888
1895 - const adoptSession = (
1896 - sessionId: string,
1897 - sessionSetupResult:
1898 - | EffectAcpSchema.ForkSessionResponse
1899 - | EffectAcpSchema.LoadSessionResponse
1900 - | EffectAcpSchema.NewSessionResponse
1901 - | EffectAcpSchema.ResumeSessionResponse,
1902 - ): Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError> =>
1903 - Effect.gen(function* () {
1904 - const current = yield* getStartedState;
1905 - const meta = sessionSetupResult._meta;
1906 - const syntheticReplayIdle =
1907 - meta !== null &&
1908 - typeof meta === "object" &&
1909 - !Array.isArray(meta) &&
1910 - (meta as { readonly t3SessionLoadReady?: unknown }).t3SessionLoadReady === "replay_idle";
1911 - const extractedModelConfigId = extractModelConfigId(sessionSetupResult);
1912 - const nextModelConfigId =
1913 - extractedModelConfigId ?? (syntheticReplayIdle ? current.modelConfigId : undefined);
1914 - const nextModeState = parseSessionModeState(sessionSetupResult);
1915 - if (nextModeState !== undefined) {
1916 - yield* Ref.set(modeStateRef, nextModeState);
1917 - } else if (!syntheticReplayIdle) {
1918 - yield* Ref.set(modeStateRef, undefined);
1919 - }
1920 - // Synthetic replay-idle load responses only carry initialize model/mode
1921 - // meta; preserve live configOptions so setConfigOption still validates.
1922 - if (
1923 - sessionSetupResult.configOptions !== undefined &&
1924 - sessionSetupResult.configOptions !== null
1925 - ) {
1926 - yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
1927 - } else if (!syntheticReplayIdle) {
1928 - yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
1929 - }
1930 - const nextState = {
1931 - sessionId,
1932 - initializeResult: current.initializeResult,
1933 - sessionSetupResult,
1934 - modelConfigId: nextModelConfigId,
1935 - } satisfies AcpStartedState;
1936 - yield* Ref.set(toolCallsRef, new Map());
1937 - yield* Ref.set(assistantSegmentRef, { nextSegmentIndex: 0 });
1938 - yield* Ref.set(startStateRef, { _tag: "Started", result: nextState });
1939 - return nextState;
1940 - });
1889 + const adoptSession = Effect.fn("AcpSessionRuntime.adoptSession")(function* (
1890 + sessionId: string,
1891 + sessionSetupResult:
1892 + | EffectAcpSchema.ForkSessionResponse
1893 + | EffectAcpSchema.LoadSessionResponse
1894 + | EffectAcpSchema.NewSessionResponse
1895 + | EffectAcpSchema.ResumeSessionResponse,
1896 + ): Effect.fn.Return<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError> {
1897 + const current = yield* getStartedState;
1898 + const meta = sessionSetupResult._meta;
1899 + const syntheticReplayIdle =
1900 + meta !== null &&
1901 + typeof meta === "object" &&
1902 + !Array.isArray(meta) &&
1903 + (meta as { readonly t3SessionLoadReady?: unknown }).t3SessionLoadReady === "replay_idle";
1904 + const extractedModelConfigId = extractModelConfigId(sessionSetupResult);
1905 + const nextModelConfigId =
1906 + extractedModelConfigId ?? (syntheticReplayIdle ? current.modelConfigId : undefined);
1907 + const nextModeState = parseSessionModeState(sessionSetupResult);
1908 + if (nextModeState !== undefined) {
1909 + yield* Ref.set(modeStateRef, nextModeState);
1910 + } else if (!syntheticReplayIdle) {
1911 + yield* Ref.set(modeStateRef, undefined);
1912 + }
1913 + // Synthetic replay-idle load responses only carry initialize model/mode
1914 + // meta; preserve live configOptions so setConfigOption still validates.
1915 + if (
1916 + sessionSetupResult.configOptions !== undefined &&
1917 + sessionSetupResult.configOptions !== null
1918 + ) {
1919 + yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
1920 + } else if (!syntheticReplayIdle) {
1921 + yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
1922 + }
1923 + const nextState = {
1924 + sessionId,
1925 + initializeResult: current.initializeResult,
1926 + sessionSetupResult,
1927 + modelConfigId: nextModelConfigId,
1928 + } satisfies AcpStartedState;
1929 + yield* Ref.set(toolCallsRef, new Map());
1930 + yield* Ref.set(assistantSegmentRef, { nextSegmentIndex: 0 });
1931 + yield* Ref.set(startStateRef, { _tag: "Started", result: nextState });
1932 + return nextState;
1933 + });
1934
1942 - const runLoadSessionWithReplayIdle = (
1943 - loadPayload: EffectAcpSchema.LoadSessionRequest,
1944 - initializeResult: EffectAcpSchema.InitializeResponse,
1945 - ): Effect.Effect<EffectAcpSchema.LoadSessionResponse, EffectAcpErrors.AcpError> =>
1946 - sessionLoadSemaphore.withPermits(1)(
1947 - Effect.gen(function* () {
1948 - const sessionLoadTimeout = Duration.fromInputUnsafe(
1949 - options.sessionLoadTimeout ?? defaultSessionLoadTimeout,
1950 - );
1951 - const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(
1952 - options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,
1953 - );
1935 + const runLoadSessionWithReplayIdle = (
1936 + loadPayload: EffectAcpSchema.LoadSessionRequest,
1937 + initializeResult: EffectAcpSchema.InitializeResponse,
1938 + ): Effect.Effect<EffectAcpSchema.LoadSessionResponse, EffectAcpErrors.AcpError> =>
1939 + sessionLoadSemaphore.withPermits(1)(
1940 + Effect.gen(function* () {
1941 + const sessionLoadTimeout = Duration.fromInputUnsafe(
1942 + options.sessionLoadTimeout ?? defaultSessionLoadTimeout,
1943 + );
1944 + const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(
1945 + options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,
1946 + );
1947
1955 - yield* Ref.set(
1956 - sessionLoadGateRef,
1957 - Option.some({
1958 - active: true,
1959 - sessionId: loadPayload.sessionId,
1960 - lastActivityAtMillis: undefined,
1961 - idleGap: sessionLoadReplayIdleGap,
1962 - initializeResult,
1963 - }),
1964 - );
1948 + yield* Ref.set(
1949 + sessionLoadGateRef,
1950 + Option.some({
1951 + active: true,
1952 + sessionId: loadPayload.sessionId,
1953 + lastActivityAtMillis: undefined,
1954 + idleGap: sessionLoadReplayIdleGap,
1955 + initializeResult,
1956 + }),
1957 + );
1958
1966 - return yield* Effect.gen(function* () {
1967 - yield* logRequest({
1968 - method: "session/load",
1969 - payload: loadPayload,
1970 - status: "started",
1971 - });
1959 + return yield* Effect.gen(function* () {
1960 + yield* logRequest({
1961 + method: "session/load",
1962 + payload: loadPayload,
1963 + status: "started",
1964 + });
1965
1973 - const idleFiber = yield* waitForSessionLoadReplayIdle({
1974 - gateRef: sessionLoadGateRef,
1975 - }).pipe(Effect.forkIn(runtimeScope));
1976 - const loaded = yield* Effect.raceFirst(
1977 - acp.agent.loadSession(loadPayload),
1978 - Fiber.join(idleFiber),
1979 - ).pipe(
1980 - Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),
1981 - Effect.timeoutOption(sessionLoadTimeout),
1982 - Effect.flatMap((result) =>
1983 - Option.match(result, {
1984 - onNone: () =>
1985 - Effect.fail(
1986 - new EffectAcpErrors.AcpTransportError({
1987 - operation: "call-rpc",
1988 - method: "session/load",
1989 - detail:
1990 - "session/load timed out waiting for RPC response or replay idle gap",
1991 - cause: undefined,
1992 - }),
1993 - ),
1994 - onSome: Effect.succeed,
1995 - }),
1996 - ),
1997 - Effect.tap((result) =>
1998 - logRequest({
1999 - method: "session/load",
2000 - payload: loadPayload,
2001 - status: "succeeded",
2002 - result,
2003 - }),
2004 - ),
2005 - Effect.onError((cause) =>
2006 - logRequest({
2007 - method: "session/load",
2008 - payload: loadPayload,
2009 - status: "failed",
2010 - cause,
2011 - }),
2012 - ),
2013 - );
1966 + const idleFiber = yield* waitForSessionLoadReplayIdle({
1967 + gateRef: sessionLoadGateRef,
1968 + }).pipe(Effect.forkIn(runtimeScope));
1969 + const loaded = yield* Effect.raceFirst(
1970 + acp.agent.loadSession(loadPayload),
1971 + Fiber.join(idleFiber),
1972 + ).pipe(
1973 + Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),
1974 + Effect.timeoutOption(sessionLoadTimeout),
1975 + Effect.flatMap((result) =>
1976 + Option.match(result, {
1977 + onNone: () =>
1978 + Effect.fail(
1979 + new EffectAcpErrors.AcpTransportError({
1980 + operation: "call-rpc",
1981 + method: "session/load",
1982 + detail: "session/load timed out waiting for RPC response or replay idle gap",
1983 + cause: undefined,
1984 + }),
1985 + ),
1986 + onSome: Effect.succeed,
1987 + }),
1988 + ),
1989 + Effect.tap((result) =>
1990 + logRequest({
1991 + method: "session/load",
1992 + payload: loadPayload,
1993 + status: "succeeded",
1994 + result,
1995 + }),
1996 + ),
1997 + Effect.onError((cause) =>
1998 + logRequest({
1999 + method: "session/load",
2000 + payload: loadPayload,
2001 + status: "failed",
2002 + cause,
2003 + }),
2004 + ),
2005 + );
2006
2015 - const gate = yield* Ref.get(sessionLoadGateRef);
2016 - const candidateConfigOptions = Option.isSome(gate)
2017 - ? gate.value.candidateConfigOptions
2018 - : undefined;
2019 - return loaded.configOptions == null && candidateConfigOptions !== undefined
2020 - ? { ...loaded, configOptions: candidateConfigOptions }
2021 - : loaded;
2022 - }).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
2023 - }),
2024 - );
2007 + const gate = yield* Ref.get(sessionLoadGateRef);
2008 + const candidateConfigOptions = Option.isSome(gate)
2009 + ? gate.value.candidateConfigOptions
2010 + : undefined;
2011 + return loaded.configOptions == null && candidateConfigOptions !== undefined
2012 + ? { ...loaded, configOptions: candidateConfigOptions }
2013 + : loaded;
2014 + }).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
2015 + }),
2016 + );
2017
2026 - const setConfigOption = (
2027 - configId: string,
2028 - value: string | boolean,
2029 - ): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
2030 - validateConfigOptionValue(configId, value).pipe(
2031 - Effect.flatMap(() => getStartedState),
2032 - Effect.flatMap((started) =>
2033 - Ref.get(configOptionsRef).pipe(
2034 - Effect.flatMap((configOptions) => {
2035 - const existing = findSessionConfigOption(configOptions, configId);
2036 - if (existing && configOptionCurrentValueMatches(existing, value)) {
2037 - return Effect.succeed({
2038 - configOptions,
2039 - } satisfies EffectAcpSchema.SetSessionConfigOptionResponse);
2040 - }
2041 - const requestPayload =
2042 - typeof value === "boolean"
2043 - ? ({
2044 - sessionId: started.sessionId,
2045 - configId,
2046 - type: "boolean",
2047 - value,
2048 - } satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
2049 - : ({
2050 - sessionId: started.sessionId,
2051 - configId,
2052 - value: String(value),
2053 - } satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
2054 - return runLoggedRequest(
2055 - "session/set_config_option",
2056 - requestPayload,
2057 - acp.agent.setSessionConfigOption(requestPayload),
2058 - ).pipe(Effect.tap((response) => updateConfigOptions(response)));
2059 - }),
2060 - ),
2018 + const setConfigOption = (
2019 + configId: string,
2020 + value: string | boolean,
2021 + ): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
2022 + validateConfigOptionValue(configId, value).pipe(
2023 + Effect.flatMap(() => getStartedState),
2024 + Effect.flatMap((started) =>
2025 + Ref.get(configOptionsRef).pipe(
2026 + Effect.flatMap((configOptions) => {
2027 + const existing = findSessionConfigOption(configOptions, configId);
2028 + if (existing && configOptionCurrentValueMatches(existing, value)) {
2029 + return Effect.succeed({
2030 + configOptions,
2031 + } satisfies EffectAcpSchema.SetSessionConfigOptionResponse);
2032 + }
2033 + const requestPayload =
2034 + typeof value === "boolean"
2035 + ? ({
2036 + sessionId: started.sessionId,
2037 + configId,
2038 + type: "boolean",
2039 + value,
2040 + } satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
2041 + : ({
2042 + sessionId: started.sessionId,
2043 + configId,
2044 + value: String(value),
2045 + } satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
2046 + return runLoggedRequest(
2047 + "session/set_config_option",
2048 + requestPayload,
2049 + acp.agent.setSessionConfigOption(requestPayload),
2050 + ).pipe(Effect.tap((response) => updateConfigOptions(response)));
2051 + }),
2052 ),
2062 - );
2053 + ),
2054 + );
2055
2064 - const initializeOnce = Effect.gen(function* () {
2065 - const initializePayload = {
2066 - protocolVersion: 2,
2067 - clientCapabilities: initializeClientCapabilities,
2068 - clientInfo: options.clientInfo,
2069 - ...(options.initializeMeta === undefined ? {} : { _meta: options.initializeMeta }),
2070 - } satisfies EffectAcpSchema.InitializeRequest;
2071 -
2072 - const initializeResult = yield* runLoggedRequest(
2073 - "initialize",
2074 - initializePayload,
2075 - acp.agent.initialize(initializePayload),
2076 - );
2077 - yield* options.onInitialized?.(initializeResult) ?? Effect.void;
2078 - return initializeResult;
2079 - });
2056 + const initializeOnce = Effect.gen(function* () {
2057 + const initializePayload = {
2058 + protocolVersion: 2,
2059 + clientCapabilities: initializeClientCapabilities,
2060 + clientInfo: options.clientInfo,
2061 + ...(options.initializeMeta === undefined ? {} : { _meta: options.initializeMeta }),
2062 + } satisfies EffectAcpSchema.InitializeRequest;
2063 +
2064 + const initializeResult = yield* runLoggedRequest(
2065 + "initialize",
2066 + initializePayload,
2067 + acp.agent.initialize(initializePayload),
2068 + );
2069 + yield* options.onInitialized?.(initializeResult) ?? Effect.void;
2070 + return initializeResult;
2071 + });
2072
2081 - const initialize = Effect.gen(function* () {
2082 - yield* ensureConnected;
2083 - const deferred = yield* Deferred.make<
2084 - EffectAcpSchema.InitializeResponse,
2085 - EffectAcpErrors.AcpError
2086 - >();
2087 - const effect = yield* Ref.modify(initializeStateRef, (state) => {
2088 - switch (state._tag) {
2089 - case "Started":
2090 - return [Effect.succeed(state.result), state] as const;
2091 - case "Starting":
2092 - return [Deferred.await(state.deferred), state] as const;
2093 - case "NotStarted":
2094 - return [
2095 - initializeOnce.pipe(
2096 - Effect.tap((result) =>
2097 - Ref.set(initializeStateRef, { _tag: "Started", result }).pipe(
2098 - Effect.andThen(Deferred.succeed(deferred, result)),
2099 - ),
2073 + const initialize = Effect.gen(function* () {
2074 + yield* ensureConnected;
2075 + const deferred = yield* Deferred.make<
2076 + EffectAcpSchema.InitializeResponse,
2077 + EffectAcpErrors.AcpError
2078 + >();
2079 + const effect = yield* Ref.modify(initializeStateRef, (state) => {
2080 + switch (state._tag) {
2081 + case "Started":
2082 + return [Effect.succeed(state.result), state] as const;
2083 + case "Starting":
2084 + return [Deferred.await(state.deferred), state] as const;
2085 + case "NotStarted":
2086 + return [
2087 + initializeOnce.pipe(
2088 + Effect.tap((result) =>
2089 + Ref.set(initializeStateRef, { _tag: "Started", result }).pipe(
2090 + Effect.andThen(Deferred.succeed(deferred, result)),
2091 ),
2101 - Effect.onError((cause) =>
2102 - Deferred.failCause(deferred, cause).pipe(
2103 - Effect.andThen(Ref.set(initializeStateRef, { _tag: "NotStarted" })),
2104 - ),
2092 + ),
2093 + Effect.onError((cause) =>
2094 + Deferred.failCause(deferred, cause).pipe(
2095 + Effect.andThen(Ref.set(initializeStateRef, { _tag: "NotStarted" })),
2096 ),
2097 ),
2107 - { _tag: "Starting", deferred } satisfies AcpInitializeState,
2108 - ] as const;
2109 - }
2110 - });
2111 - return yield* effect;
2098 + ),
2099 + { _tag: "Starting", deferred } satisfies AcpInitializeState,
2100 + ] as const;
2101 + }
2102 });
2103 + return yield* effect;
2104 + });
2105
2114 - const sessionMcpServers = (
2115 - initializeResult: EffectAcpSchema.InitializeResponse,
2116 - activationOptions?: AcpSessionActivationOptions,
2117 - ): ReadonlyArray<EffectAcpSchema.McpServer> => {
2118 - const acpServers = activationOptions?.acpMcpServers ?? options.acpMcpServers ?? [];
2119 - if (
2120 - initializeResult.agentCapabilities?.mcpCapabilities?.acp === true &&
2121 - acpServers.length > 0
2122 - ) {
2123 - return acpServers;
2124 - }
2125 - return activationOptions?.mcpServers ?? options.mcpServers ?? [];
2126 - };
2106 + const sessionMcpServers = (
2107 + initializeResult: EffectAcpSchema.InitializeResponse,
2108 + activationOptions?: AcpSessionActivationOptions,
2109 + ): ReadonlyArray<EffectAcpSchema.McpServer> => {
2110 + const acpServers = activationOptions?.acpMcpServers ?? options.acpMcpServers ?? [];
2111 + if (
2112 + initializeResult.agentCapabilities?.mcpCapabilities?.acp === true &&
2113 + acpServers.length > 0
2114 + ) {
2115 + return acpServers;
2116 + }
2117 + return activationOptions?.mcpServers ?? options.mcpServers ?? [];
2118 + };
2119
2128 - const startOnce = Effect.gen(function* () {
2129 - const initializeResult = yield* initialize;
2120 + const startOnce = Effect.gen(function* () {
2121 + const initializeResult = yield* initialize;
2122
2131 - const authenticateAfterRequired = (
2123 + const authenticateAfterRequired = Effect.fn("AcpSessionRuntime.authenticateAfterRequired")(
2124 + function* (
2125 authRequiredError: EffectAcpErrors.AcpError,
2133 - ): Effect.Effect<void, EffectAcpErrors.AcpError> =>
2134 - Effect.gen(function* () {
2135 - const configuredAuthMethodId = options.authMethodId?.trim();
2136 - const authMethod = selectAcpAgentAuthMethod(
2137 - initializeResult.authMethods,
2138 - configuredAuthMethodId,
2139 - );
2140 - if (
2141 - configuredAuthMethodId &&
2142 - initializeResult.authMethods !== undefined &&
2143 - authMethod === undefined
2144 - ) {
2145 - return yield* new EffectAcpErrors.AcpTransportError({
2146 - detail: `ACP agent did not advertise configured authentication method "${configuredAuthMethodId}"`,
2147 - cause: { configuredAuthMethodId, authMethods: initializeResult.authMethods },
2148 - });
2149 - }
2150 - if (
2151 - authMethod !== undefined &&
2152 - authMethod.type !== undefined &&
2153 - authMethod.type !== "agent"
2154 - ) {
2155 - return yield* new EffectAcpErrors.AcpTransportError({
2156 - detail: `ACP authentication method "${authMethod.id}" requires ${authMethod.type} authentication, which cannot run inside a headless provider session`,
2157 - cause: authMethod,
2158 - });
2159 - }
2160 -
2161 - const authMethodId = authMethod?.id ?? configuredAuthMethodId;
2162 - if (!authMethodId) {
2163 - return yield* authRequiredError;
2164 - }
2165 -
2166 - const authenticatePayload = {
2167 - methodId: authMethodId,
2168 - } satisfies EffectAcpSchema.AuthenticateRequest;
2169 - yield* runLoggedRequest(
2170 - "authenticate",
2171 - authenticatePayload,
2172 - acp.agent.authenticate(authenticatePayload),
2173 - );
2174 - });
2175 -
2176 - const setupSession = Effect.gen(function* () {
2177 - let sessionId: string;
2178 - let sessionSetupResult:
2179 - | EffectAcpSchema.LoadSessionResponse
2180 - | EffectAcpSchema.NewSessionResponse
2181 - | EffectAcpSchema.ResumeSessionResponse;
2182 - const additionalDirectories = options.additionalDirectories?.length
2183 - ? { additionalDirectories: options.additionalDirectories }
2184 - : {};
2185 - if (options.resumeSessionId) {
2186 - sessionId = options.resumeSessionId;
2187 - if (
2188 - initializeResult.agentCapabilities?.loadSession === true &&
2189 - options.resumeMethod !== "resume"
2190 - ) {
2191 - const loadPayload = {
2192 - sessionId,
2193 - cwd: options.cwd,
2194 - ...additionalDirectories,
2195 - mcpServers: sessionMcpServers(initializeResult),
2196 - } satisfies EffectAcpSchema.LoadSessionRequest;
2197 - sessionSetupResult = yield* runLoadSessionWithReplayIdle(loadPayload, initializeResult);
2198 - } else if (initializeResult.agentCapabilities?.sessionCapabilities?.resume != null) {
2199 - const resumePayload = {
2200 - sessionId,
2201 - cwd: options.cwd,
2202 - ...additionalDirectories,
2203 - mcpServers: sessionMcpServers(initializeResult),
2204 - } satisfies EffectAcpSchema.ResumeSessionRequest;
2205 - sessionSetupResult = yield* runLoggedRequest(
2206 - "session/resume",
2207 - resumePayload,
2208 - acp.agent.resumeSession(resumePayload),
2209 - );
2210 - } else {
2211 - return yield* new EffectAcpErrors.AcpRequestError({
2212 - code: -32601,
2213 - errorMessage: "ACP agent does not advertise session/load or session/resume support",
2214 - });
2215 - }
2216 - } else {
2217 - const createPayload = {
2218 - cwd: options.cwd,
2219 - mcpServers: sessionMcpServers(initializeResult),
2220 - ...additionalDirectories,
2221 - } satisfies EffectAcpSchema.NewSessionRequest;
2222 - const created = yield* runLoggedRequest(
2223 - "session/new",
2224 - createPayload,
2225 - acp.agent.createSession(createPayload),
2226 - );
2227 - sessionId = created.sessionId;
2228 - sessionSetupResult = created;
2126 + ): Effect.fn.Return<void, EffectAcpErrors.AcpError> {
2127 + const configuredAuthMethodId = options.authMethodId?.trim();
2128 + const authMethod = selectAcpAgentAuthMethod(
2129 + initializeResult.authMethods,
2130 + configuredAuthMethodId,
2131 + );
2132 + if (
2133 + configuredAuthMethodId &&
2134 + initializeResult.authMethods !== undefined &&
2135 + authMethod === undefined
2136 + ) {
2137 + return yield* new EffectAcpErrors.AcpTransportError({
2138 + detail: `ACP agent did not advertise configured authentication method "${configuredAuthMethodId}"`,
2139 + cause: { configuredAuthMethodId, authMethods: initializeResult.authMethods },
2140 + });
2141 + }
2142 + if (
2143 + authMethod !== undefined &&
2144 + authMethod.type !== undefined &&
2145 + authMethod.type !== "agent"
2146 + ) {
2147 + return yield* new EffectAcpErrors.AcpTransportError({
2148 + detail: `ACP authentication method "${authMethod.id}" requires ${authMethod.type} authentication, which cannot run inside a headless provider session`,
2149 + cause: authMethod,
2150 + });
2151 }
2152
2231 - return { sessionId, sessionSetupResult };
2232 - });
2153 + const authMethodId = authMethod?.id ?? configuredAuthMethodId;
2154 + if (!authMethodId) {
2155 + return yield* authRequiredError;
2156 + }
2157
2234 - if (options.authenticateEagerly === true) {
2235 - // The configured method is authoritative here: Antigravity accepts
2236 - // methods (API key, Vertex) it does not list in `initialize`.
2158 const authenticatePayload = {
2238 - methodId: options.authMethodId ?? "",
2159 + methodId: authMethodId,
2160 } satisfies EffectAcpSchema.AuthenticateRequest;
2161 yield* runLoggedRequest(
2162 "authenticate",
2163 authenticatePayload,
2164 acp.agent.authenticate(authenticatePayload),
2165 );
2166 + },
2167 + );
2168 +
2169 + const setupSession = Effect.gen(function* () {
2170 + let sessionId: string;
2171 + let sessionSetupResult:
2172 + | EffectAcpSchema.LoadSessionResponse
2173 + | EffectAcpSchema.NewSessionResponse
2174 + | EffectAcpSchema.ResumeSessionResponse;
2175 + const additionalDirectories = options.additionalDirectories?.length
2176 + ? { additionalDirectories: options.additionalDirectories }
2177 + : {};
2178 + if (options.resumeSessionId) {
2179 + sessionId = options.resumeSessionId;
2180 + if (
2181 + initializeResult.agentCapabilities?.loadSession === true &&
2182 + options.resumeMethod !== "resume"
2183 + ) {
2184 + const loadPayload = {
2185 + sessionId,
2186 + cwd: options.cwd,
2187 + ...additionalDirectories,
2188 + mcpServers: sessionMcpServers(initializeResult),
2189 + } satisfies EffectAcpSchema.LoadSessionRequest;
2190 + sessionSetupResult = yield* runLoadSessionWithReplayIdle(loadPayload, initializeResult);
2191 + } else if (initializeResult.agentCapabilities?.sessionCapabilities?.resume != null) {
2192 + const resumePayload = {
2193 + sessionId,
2194 + cwd: options.cwd,
2195 + ...additionalDirectories,
2196 + mcpServers: sessionMcpServers(initializeResult),
2197 + } satisfies EffectAcpSchema.ResumeSessionRequest;
2198 + sessionSetupResult = yield* runLoggedRequest(
2199 + "session/resume",
2200 + resumePayload,
2201 + acp.agent.resumeSession(resumePayload),
2202 + );
2203 + } else {
2204 + return yield* new EffectAcpErrors.AcpRequestError({
2205 + code: -32601,
2206 + errorMessage: "ACP agent does not advertise session/load or session/resume support",
2207 + });
2208 + }
2209 + } else {
2210 + const createPayload = {
2211 + cwd: options.cwd,
2212 + mcpServers: sessionMcpServers(initializeResult),
2213 + ...additionalDirectories,
2214 + } satisfies EffectAcpSchema.NewSessionRequest;
2215 + const created = yield* runLoggedRequest(
2216 + "session/new",
2217 + createPayload,
2218 + acp.agent.createSession(createPayload),
2219 + );
2220 + sessionId = created.sessionId;
2221 + sessionSetupResult = created;
2222 }
2246 - const { sessionId, sessionSetupResult } = yield* setupSession.pipe(
2247 - Effect.catch((error) =>
2248 - !isAcpAuthenticationRequired(error) || options.authenticateOnAuthRequired === false
2249 - ? Effect.fail(error)
2250 - : authenticateAfterRequired(error).pipe(Effect.andThen(setupSession)),
2251 - ),
2223 +
2224 + return { sessionId, sessionSetupResult };
2225 + });
2226 +
2227 + if (options.authenticateEagerly === true) {
2228 + // The configured method is authoritative here: Antigravity accepts
2229 + // methods (API key, Vertex) it does not list in `initialize`.
2230 + const authenticatePayload = {
2231 + methodId: options.authMethodId ?? "",
2232 + } satisfies EffectAcpSchema.AuthenticateRequest;
2233 + yield* runLoggedRequest(
2234 + "authenticate",
2235 + authenticatePayload,
2236 + acp.agent.authenticate(authenticatePayload),
2237 );
2238 + }
2239 + const { sessionId, sessionSetupResult } = yield* setupSession.pipe(
2240 + Effect.catch((error) =>
2241 + !isAcpAuthenticationRequired(error) || options.authenticateOnAuthRequired === false
2242 + ? Effect.fail(error)
2243 + : authenticateAfterRequired(error).pipe(Effect.andThen(setupSession)),
2244 + ),
2245 + );
2246
2254 - yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
2255 - yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
2247 + yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
2248 + yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
2249
2257 - const nextState = {
2258 - sessionId,
2259 - initializeResult,
2260 - sessionSetupResult,
2261 - modelConfigId: extractModelConfigId(sessionSetupResult),
2262 - } satisfies AcpStartedState;
2263 - return nextState;
2264 - });
2250 + const nextState = {
2251 + sessionId,
2252 + initializeResult,
2253 + sessionSetupResult,
2254 + modelConfigId: extractModelConfigId(sessionSetupResult),
2255 + } satisfies AcpStartedState;
2256 + return nextState;
2257 + });
2258
2266 - const start = Effect.gen(function* () {
2267 - yield* ensureConnected;
2268 - const deferred = yield* Deferred.make<
2269 - AcpSessionRuntimeStartResult,
2270 - EffectAcpErrors.AcpError
2271 - >();
2272 - const effect = yield* Ref.modify(startStateRef, (state) => {
2273 - switch (state._tag) {
2274 - case "Started":
2275 - return [Effect.succeed(state.result), state] as const;
2276 - case "Starting":
2277 - return [Deferred.await(state.deferred), state] as const;
2278 - case "NotStarted":
2279 - return [
2280 - startOnce.pipe(
2281 - Effect.tap((result) =>
2282 - notificationSemaphore.withPermit(
2283 - Effect.gen(function* () {
2284 - const error = yield* Ref.get(terminationErrorRef);
2285 - if (Option.isSome(error)) {
2286 - return yield* error.value;
2287 - }
2288 - yield* Ref.set(startStateRef, { _tag: "Started", result });
2289 - const metadata = yield* Ref.getAndSet(startupMetadataRef, []);
2290 - for (const notification of metadata) {
2291 - if (notification.sessionId === result.sessionId) {
2292 - yield* processSessionUpdate(notification);
2293 - }
2259 + const start = Effect.gen(function* () {
2260 + yield* ensureConnected;
2261 + const deferred = yield* Deferred.make<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>();
2262 + const effect = yield* Ref.modify(startStateRef, (state) => {
2263 + switch (state._tag) {
2264 + case "Started":
2265 + return [Effect.succeed(state.result), state] as const;
2266 + case "Starting":
2267 + return [Deferred.await(state.deferred), state] as const;
2268 + case "NotStarted":
2269 + return [
2270 + startOnce.pipe(
2271 + Effect.tap((result) =>
2272 + notificationSemaphore.withPermit(
2273 + Effect.gen(function* () {
2274 + const error = yield* Ref.get(terminationErrorRef);
2275 + if (Option.isSome(error)) {
2276 + return yield* error.value;
2277 + }
2278 + yield* Ref.set(startStateRef, { _tag: "Started", result });
2279 + const metadata = yield* Ref.getAndSet(startupMetadataRef, []);
2280 + for (const notification of metadata) {
2281 + if (notification.sessionId === result.sessionId) {
2282 + yield* processSessionUpdate(notification);
2283 }
2295 - yield* Deferred.succeed(deferred, result);
2296 - }),
2297 - ),
2284 + }
2285 + yield* Deferred.succeed(deferred, result);
2286 + }),
2287 ),
2299 - Effect.onError((cause) =>
2300 - Deferred.failCause(deferred, cause).pipe(
2301 - Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),
2302 - Effect.andThen(Ref.set(startupMetadataRef, [])),
2303 - ),
2288 + ),
2289 + Effect.onError((cause) =>
2290 + Deferred.failCause(deferred, cause).pipe(
2291 + Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),
2292 + Effect.andThen(Ref.set(startupMetadataRef, [])),
2293 ),
2294 ),
2306 - { _tag: "Starting", deferred } satisfies AcpStartState,
2307 - ] as const;
2308 - }
2309 - });
2310 - return yield* effect;
2311 - });
2312 -
2313 - const drainEvents = Effect.gen(function* () {
2314 - if (yield* Ref.get(stoppingRef)) {
2315 - return;
2295 + ),
2296 + { _tag: "Starting", deferred } satisfies AcpStartState,
2297 + ] as const;
2298 }
2317 - const acknowledge = yield* Deferred.make<void>();
2318 - yield* notificationSemaphore.withPermit(
2319 - Effect.gen(function* () {
2320 - if (Option.isNone(yield* Ref.get(activePromptRef))) {
2321 - yield* Ref.set(assistantUpdatesOpenRef, false);
2322 - yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
2323 - }
2324 - yield* Queue.offer(eventQueue, { _tag: "EventStreamBarrier", acknowledge });
2325 - }),
2326 - );
2327 - yield* Effect.raceFirst(Deferred.await(acknowledge), Deferred.await(runtimeClosed));
2328 - });
2329 -
2330 - const retireRuntime = Effect.fn("AcpSessionRuntime.retireRuntime")(function* (
2331 - error: EffectAcpErrors.AcpError,
2332 - ) {
2333 - yield* recordTermination(error);
2334 - yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);
2299 });
2300 + return yield* effect;
2301 + });
2302
2337 - const cancel = Effect.gen(function* () {
2338 - const started = yield* getStartedState;
2339 - const activePrompt = yield* Ref.get(activePromptRef);
2340 - const cancelPayload = {
2341 - sessionId: started.sessionId,
2342 - ...(options.cancelMeta === undefined ? {} : { _meta: options.cancelMeta }),
2343 - } satisfies EffectAcpSchema.CancelNotification;
2344 - if (options.cancelBehavior !== "wait-for-prompt") {
2345 - if (options.interruptPromptOnCancel === false) {
2346 - return yield* acp.agent.cancel(cancelPayload);
2347 - }
2348 - if (Option.isSome(activePrompt)) {
2349 - yield* Fiber.interrupt(activePrompt.value.fiber).pipe(Effect.ignore);
2303 + const drainEvents = Effect.gen(function* () {
2304 + if (yield* Ref.get(stoppingRef)) {
2305 + return;
2306 + }
2307 + const acknowledge = yield* Deferred.make<void>();
2308 + yield* notificationSemaphore.withPermit(
2309 + Effect.gen(function* () {
2310 + if (Option.isNone(yield* Ref.get(activePromptRef))) {
2311 + yield* Ref.set(assistantUpdatesOpenRef, false);
2312 + yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
2313 }
2351 - // Write cancel before a replacement prompt can reach the agent.
2352 - yield* acp.agent.cancel(cancelPayload).pipe(Effect.ignore);
2353 - return;
2354 - }
2314 + yield* Queue.offer(eventQueue, { _tag: "EventStreamBarrier", acknowledge });
2315 + }),
2316 + );
2317 + yield* Effect.raceFirst(Deferred.await(acknowledge), Deferred.await(runtimeClosed));
2318 + });
2319
2356 - yield* acp.agent.cancel(cancelPayload);
2357 - if (Option.isNone(activePrompt)) {
2358 - return;
2320 + const retireRuntime = Effect.fn("AcpSessionRuntime.retireRuntime")(function* (
2321 + error: EffectAcpErrors.AcpError,
2322 + ) {
2323 + yield* recordTermination(error);
2324 + yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);
2325 + });
2326 +
2327 + const cancel = Effect.gen(function* () {
2328 + const started = yield* getStartedState;
2329 + const activePrompt = yield* Ref.get(activePromptRef);
2330 + const cancelPayload = {
2331 + sessionId: started.sessionId,
2332 + ...(options.cancelMeta === undefined ? {} : { _meta: options.cancelMeta }),
2333 + } satisfies EffectAcpSchema.CancelNotification;
2334 + if (options.cancelBehavior !== "wait-for-prompt") {
2335 + if (options.interruptPromptOnCancel === false) {
2336 + return yield* acp.agent.cancel(cancelPayload);
2337 }
2360 - const completed = yield* Effect.gen(function* () {
2361 - const result = yield* Fiber.await(activePrompt.value.fiber);
2362 - yield* Deferred.await(activePrompt.value.completed);
2363 - if (Option.isNone(yield* Ref.get(terminationErrorRef))) {
2364 - yield* drainEvents;
2365 - }
2366 - return result;
2367 - }).pipe(Effect.timeoutOption(options.cancelTimeout ?? defaultCancelTimeout));
2368 - if (Option.isNone(completed)) {
2369 - const error = new EffectAcpErrors.AcpTransportError({
2370 - operation: "call-rpc",
2371 - method: "session/cancel",
2372 - detail: "The ACP agent did not finish cancellation. Its process was stopped.",
2373 - cause: undefined,
2374 - });
2375 - yield* retireRuntime(error);
2376 - return yield* error;
2338 + if (Option.isSome(activePrompt)) {
2339 + yield* Fiber.interrupt(activePrompt.value.fiber).pipe(Effect.ignore);
2340 }
2378 - if (Exit.isFailure(completed.value)) {
2379 - return yield* Effect.failCause(completed.value.cause);
2341 + // Write cancel before a replacement prompt can reach the agent.
2342 + yield* acp.agent.cancel(cancelPayload).pipe(Effect.ignore);
2343 + return;
2344 + }
2345 +
2346 + yield* acp.agent.cancel(cancelPayload);
2347 + if (Option.isNone(activePrompt)) {
2348 + return;
2349 + }
2350 + const completed = yield* Effect.gen(function* () {
2351 + const result = yield* Fiber.await(activePrompt.value.fiber);
2352 + yield* Deferred.await(activePrompt.value.completed);
2353 + if (Option.isNone(yield* Ref.get(terminationErrorRef))) {
2354 + yield* drainEvents;
2355 }
2381 - });
2356 + return result;
2357 + }).pipe(Effect.timeoutOption(options.cancelTimeout ?? defaultCancelTimeout));
2358 + if (Option.isNone(completed)) {
2359 + const error = new EffectAcpErrors.AcpTransportError({
2360 + operation: "call-rpc",
2361 + method: "session/cancel",
2362 + detail: "The ACP agent did not finish cancellation. Its process was stopped.",
2363 + cause: undefined,
2364 + });
2365 + yield* retireRuntime(error);
2366 + return yield* error;
2367 + }
2368 + if (Exit.isFailure(completed.value)) {
2369 + return yield* Effect.failCause(completed.value.cause);
2370 + }
2371 + });
2372
2383 - return {
2384 - processContainment:
2385 - linuxCgroupLease !== undefined
2386 - ? "cgroup-v2"
2387 - : options.ownDescendantProcessGroups === true
2388 - ? "process-ledger-reduced-guarantee"
2389 - : options.ownDetachedProcessGroup === true
2390 - ? "process-group"
2391 - : "none",
2392 - handleRequestPermission: acp.handleRequestPermission,
2393 - handleElicitation: acp.handleElicitation,
2394 - handleMcpConnect: acp.handleMcpConnect,
2395 - handleMcpMessage: acp.handleMcpMessage,
2396 - handleMcpDisconnect: acp.handleMcpDisconnect,
2397 - handleMcpNotification: acp.handleMcpNotification,
2398 - handleReadTextFile: acp.handleReadTextFile,
2399 - handleWriteTextFile: acp.handleWriteTextFile,
2400 - handleCreateTerminal: acp.handleCreateTerminal,
2401 - handleTerminalOutput: acp.handleTerminalOutput,
2402 - handleTerminalWaitForExit: acp.handleTerminalWaitForExit,
2403 - handleTerminalKill: acp.handleTerminalKill,
2404 - handleTerminalRelease: acp.handleTerminalRelease,
2405 - handleSessionUpdate: acp.handleSessionUpdate,
2406 - handleElicitationComplete: acp.handleElicitationComplete,
2407 - handleUnknownExtRequest: acp.handleUnknownExtRequest,
2408 - handleUnknownExtNotification: acp.handleUnknownExtNotification,
2409 - handleExtRequest: acp.handleExtRequest,
2410 - handleExtNotification: acp.handleExtNotification,
2411 - initialize: () => initialize,
2412 - authenticate: (methodId) =>
2413 - initialize.pipe(
2414 - Effect.andThen(
2415 - runLoggedRequest("authenticate", { methodId }, acp.agent.authenticate({ methodId })),
2416 - ),
2417 - Effect.asVoid,
2418 - ),
2419 - start: () => start,
2420 - getEvents: () => Stream.fromQueue(eventQueue),
2421 - drainEvents,
2422 - getModeState: Ref.get(modeStateRef),
2423 - getConfigOptions: Ref.get(configOptionsRef),
2424 - loadSession: (sessionId, activationOptions) =>
2425 - start.pipe(
2426 - Effect.flatMap((started) => {
2427 - const requestPayload = {
2428 - sessionId,
2429 - cwd: options.cwd,
2430 - mcpServers: sessionMcpServers(started.initializeResult, activationOptions),
2431 - } satisfies EffectAcpSchema.LoadSessionRequest;
2432 - return runLoadSessionWithReplayIdle(requestPayload, started.initializeResult);
2433 - }),
2434 - Effect.flatMap((response) => adoptSession(sessionId, response)),
2373 + return {
2374 + processContainment:
2375 + linuxCgroupLease !== undefined
2376 + ? "cgroup-v2"
2377 + : options.ownDescendantProcessGroups === true
2378 + ? "process-ledger-reduced-guarantee"
2379 + : options.ownDetachedProcessGroup === true
2380 + ? "process-group"
2381 + : "none",
2382 + handleRequestPermission: acp.handleRequestPermission,
2383 + handleElicitation: acp.handleElicitation,
2384 + handleMcpConnect: acp.handleMcpConnect,
2385 + handleMcpMessage: acp.handleMcpMessage,
2386 + handleMcpDisconnect: acp.handleMcpDisconnect,
2387 + handleMcpNotification: acp.handleMcpNotification,
2388 + handleReadTextFile: acp.handleReadTextFile,
2389 + handleWriteTextFile: acp.handleWriteTextFile,
2390 + handleCreateTerminal: acp.handleCreateTerminal,
2391 + handleTerminalOutput: acp.handleTerminalOutput,
2392 + handleTerminalWaitForExit: acp.handleTerminalWaitForExit,
2393 + handleTerminalKill: acp.handleTerminalKill,
2394 + handleTerminalRelease: acp.handleTerminalRelease,
2395 + handleSessionUpdate: acp.handleSessionUpdate,
2396 + handleElicitationComplete: acp.handleElicitationComplete,
2397 + handleUnknownExtRequest: acp.handleUnknownExtRequest,
2398 + handleUnknownExtNotification: acp.handleUnknownExtNotification,
2399 + handleExtRequest: acp.handleExtRequest,
2400 + handleExtNotification: acp.handleExtNotification,
2401 + initialize: () => initialize,
2402 + authenticate: (methodId) =>
2403 + initialize.pipe(
2404 + Effect.andThen(
2405 + runLoggedRequest("authenticate", { methodId }, acp.agent.authenticate({ methodId })),
2406 ),
2436 - resumeSession: (sessionId, activationOptions) =>
2437 - start.pipe(
2438 - Effect.flatMap((started) => {
2439 - const requestPayload = {
2440 - sessionId,
2441 - cwd: options.cwd,
2442 - mcpServers: sessionMcpServers(started.initializeResult, activationOptions),
2443 - } satisfies EffectAcpSchema.ResumeSessionRequest;
2444 - return runLoggedRequest(
2445 - "session/resume",
2446 - requestPayload,
2447 - acp.agent.resumeSession(requestPayload),
2448 - );
2449 - }),
2450 - Effect.flatMap((response) => adoptSession(sessionId, response)),
2407 + Effect.asVoid,
2408 + ),
2409 + start: () => start,
2410 + getEvents: () => Stream.fromQueue(eventQueue),
2411 + drainEvents,
2412 + getModeState: Ref.get(modeStateRef),
2413 + getConfigOptions: Ref.get(configOptionsRef),
2414 + loadSession: (sessionId, activationOptions) =>
2415 + start.pipe(
2416 + Effect.flatMap((started) => {
2417 + const requestPayload = {
2418 + sessionId,
2419 + cwd: options.cwd,
2420 + mcpServers: sessionMcpServers(started.initializeResult, activationOptions),
2421 + } satisfies EffectAcpSchema.LoadSessionRequest;
2422 + return runLoadSessionWithReplayIdle(requestPayload, started.initializeResult);
2423 + }),
2424 + Effect.flatMap((response) => adoptSession(sessionId, response)),
2425 + ),
2426 + resumeSession: (sessionId, activationOptions) =>
2427 + start.pipe(
2428 + Effect.flatMap((started) => {
2429 + const requestPayload = {
2430 + sessionId,
2431 + cwd: options.cwd,
2432 + mcpServers: sessionMcpServers(started.initializeResult, activationOptions),
2433 + } satisfies EffectAcpSchema.ResumeSessionRequest;
2434 + return runLoggedRequest(
2435 + "session/resume",
2436 + requestPayload,
2437 + acp.agent.resumeSession(requestPayload),
2438 + );
2439 + }),
2440 + Effect.flatMap((response) => adoptSession(sessionId, response)),
2441 + ),
2442 + forkSession: (sessionId, activationOptions) =>
2443 + start.pipe(
2444 + Effect.flatMap((started) => {
2445 + const requestPayload = {
2446 + sessionId,
2447 + cwd: options.cwd,
2448 + mcpServers: sessionMcpServers(started.initializeResult, activationOptions),
2449 + } satisfies EffectAcpSchema.ForkSessionRequest;
2450 + return runLoggedRequest(
2451 + "session/fork",
2452 + requestPayload,
2453 + acp.agent.forkSession(requestPayload),
2454 + );
2455 + }),
2456 + Effect.flatMap((response) => adoptSession(response.sessionId, response)),
2457 + ),
2458 + listSessions: (cursor) => {
2459 + const requestPayload = {
2460 + cwd: options.cwd,
2461 + ...(cursor === undefined ? {} : { cursor }),
2462 + } satisfies EffectAcpSchema.ListSessionsRequest;
2463 + return initialize.pipe(
2464 + Effect.filterOrFail(
2465 + (initialized) => initialized.agentCapabilities?.sessionCapabilities?.list != null,
2466 + () =>
2467 + new EffectAcpErrors.AcpRequestError({
2468 + code: -32601,
2469 + errorMessage: "ACP agent does not advertise session/list support",
2470 + }),
2471 ),
2452 - forkSession: (sessionId, activationOptions) =>
2453 - start.pipe(
2454 - Effect.flatMap((started) => {
2455 - const requestPayload = {
2456 - sessionId,
2457 - cwd: options.cwd,
2458 - mcpServers: sessionMcpServers(started.initializeResult, activationOptions),
2459 - } satisfies EffectAcpSchema.ForkSessionRequest;
2460 - return runLoggedRequest(
2461 - "session/fork",
2462 - requestPayload,
2463 - acp.agent.forkSession(requestPayload),
2464 - );
2465 - }),
2466 - Effect.flatMap((response) => adoptSession(response.sessionId, response)),
2472 + Effect.andThen(
2473 + runLoggedRequest("session/list", requestPayload, acp.agent.listSessions(requestPayload)),
2474 ),
2468 - listSessions: (cursor) => {
2469 - const requestPayload = {
2470 - cwd: options.cwd,
2471 - ...(cursor === undefined ? {} : { cursor }),
2472 - } satisfies EffectAcpSchema.ListSessionsRequest;
2473 - return initialize.pipe(
2474 - Effect.filterOrFail(
2475 - (initialized) => initialized.agentCapabilities?.sessionCapabilities?.list != null,
2476 - () =>
2477 - new EffectAcpErrors.AcpRequestError({
2478 - code: -32601,
2479 - errorMessage: "ACP agent does not advertise session/list support",
2480 - }),
2481 - ),
2482 - Effect.andThen(
2483 - runLoggedRequest(
2484 - "session/list",
2485 - requestPayload,
2486 - acp.agent.listSessions(requestPayload),
2487 - ),
2488 - ),
2489 - );
2490 - },
2491 - closeSession: (sessionId) =>
2492 - start.pipe(
2493 - Effect.flatMap((started) => {
2494 - const requestPayload = {
2495 - sessionId: sessionId ?? started.sessionId,
2496 - } satisfies EffectAcpSchema.CloseSessionRequest;
2497 - return runLoggedRequest(
2498 - "session/close",
2499 - requestPayload,
2500 - acp.agent.closeSession(requestPayload),
2501 - );
2502 - }),
2475 + );
2476 + },
2477 + closeSession: (sessionId) =>
2478 + start.pipe(
2479 + Effect.flatMap((started) => {
2480 + const requestPayload = {
2481 + sessionId: sessionId ?? started.sessionId,
2482 + } satisfies EffectAcpSchema.CloseSessionRequest;
2483 + return runLoggedRequest(
2484 + "session/close",
2485 + requestPayload,
2486 + acp.agent.closeSession(requestPayload),
2487 + );
2488 + }),
2489 + ),
2490 + deleteSession: (sessionId) =>
2491 + initialize.pipe(
2492 + Effect.filterOrFail(
2493 + (initialized) => initialized.agentCapabilities?.sessionCapabilities?.delete != null,
2494 + () =>
2495 + new EffectAcpErrors.AcpRequestError({
2496 + code: -32601,
2497 + errorMessage: "ACP agent does not advertise session/delete support",
2498 + }),
2499 ),
2504 - deleteSession: (sessionId) =>
2505 - initialize.pipe(
2506 - Effect.filterOrFail(
2507 - (initialized) => initialized.agentCapabilities?.sessionCapabilities?.delete != null,
2508 - () =>
2509 - new EffectAcpErrors.AcpRequestError({
2510 - code: -32601,
2511 - errorMessage: "ACP agent does not advertise session/delete support",
2512 - }),
2513 - ),
2514 - Effect.andThen(
2515 - runLoggedRequest(
2516 - "session/delete",
2517 - { sessionId },
2518 - acp.agent.deleteSession({ sessionId }),
2519 - ),
2520 - ),
2500 + Effect.andThen(
2501 + runLoggedRequest("session/delete", { sessionId }, acp.agent.deleteSession({ sessionId })),
2502 ),
2522 - listProviders: initialize.pipe(
2503 + ),
2504 + listProviders: initialize.pipe(
2505 + Effect.filterOrFail(
2506 + (initialized) => initialized.agentCapabilities?.providers != null,
2507 + () =>
2508 + new EffectAcpErrors.AcpRequestError({
2509 + code: -32601,
2510 + errorMessage: "ACP agent does not advertise provider configuration support",
2511 + }),
2512 + ),
2513 + Effect.andThen(runLoggedRequest("providers/list", {}, acp.agent.listProviders({}))),
2514 + ),
2515 + setProvider: (provider) =>
2516 + initialize.pipe(
2517 Effect.filterOrFail(
2518 (initialized) => initialized.agentCapabilities?.providers != null,
2519 () =>
@@ -2528,185 +2522,168 @@ export const make = (
2522 errorMessage: "ACP agent does not advertise provider configuration support",
2523 }),
2524 ),
2531 - Effect.andThen(runLoggedRequest("providers/list", {}, acp.agent.listProviders({}))),
2532 - ),
2533 - setProvider: (provider) =>
2534 - initialize.pipe(
2535 - Effect.filterOrFail(
2536 - (initialized) => initialized.agentCapabilities?.providers != null,
2537 - () =>
2538 - new EffectAcpErrors.AcpRequestError({
2539 - code: -32601,
2540 - errorMessage: "ACP agent does not advertise provider configuration support",
2541 - }),
2542 - ),
2543 - Effect.andThen(
2544 - runLoggedRequest(
2545 - "providers/set",
2546 - {
2547 - ...provider,
2548 - ...(provider.headers === undefined
2549 - ? {}
2550 - : {
2551 - headers: Object.fromEntries(
2552 - Object.keys(provider.headers).map((name) => [name, "[redacted]"]),
2553 - ),
2554 - }),
2555 - },
2556 - acp.agent.setProvider(provider),
2557 - ),
2525 + Effect.andThen(
2526 + runLoggedRequest(
2527 + "providers/set",
2528 + {
2529 + ...provider,
2530 + ...(provider.headers === undefined
2531 + ? {}
2532 + : {
2533 + headers: Object.fromEntries(
2534 + Object.keys(provider.headers).map((name) => [name, "[redacted]"]),
2535 + ),
2536 + }),
2537 + },
2538 + acp.agent.setProvider(provider),
2539 ),
2540 ),
2560 - disableProvider: (providerId) => {
2561 - const request = { providerId } satisfies EffectAcpSchema.DisableProviderRequest;
2562 - return initialize.pipe(
2563 - Effect.filterOrFail(
2564 - (initialized) => initialized.agentCapabilities?.providers != null,
2565 - () =>
2566 - new EffectAcpErrors.AcpRequestError({
2567 - code: -32601,
2568 - errorMessage: "ACP agent does not advertise provider configuration support",
2569 - }),
2570 - ),
2571 - Effect.andThen(
2572 - runLoggedRequest("providers/disable", request, acp.agent.disableProvider(request)),
2573 - ),
2574 - );
2575 - },
2576 - logout: initialize.pipe(
2541 + ),
2542 + disableProvider: (providerId) => {
2543 + const request = { providerId } satisfies EffectAcpSchema.DisableProviderRequest;
2544 + return initialize.pipe(
2545 Effect.filterOrFail(
2578 - (initialized) => initialized.agentCapabilities?.auth?.logout != null,
2546 + (initialized) => initialized.agentCapabilities?.providers != null,
2547 () =>
2548 new EffectAcpErrors.AcpRequestError({
2549 code: -32601,
2582 - errorMessage: "ACP agent does not advertise logout support",
2550 + errorMessage: "ACP agent does not advertise provider configuration support",
2551 }),
2552 ),
2585 - Effect.andThen(runLoggedRequest("logout", {}, acp.agent.logout({}))),
2553 + Effect.andThen(
2554 + runLoggedRequest("providers/disable", request, acp.agent.disableProvider(request)),
2555 + ),
2556 + );
2557 + },
2558 + logout: initialize.pipe(
2559 + Effect.filterOrFail(
2560 + (initialized) => initialized.agentCapabilities?.auth?.logout != null,
2561 + () =>
2562 + new EffectAcpErrors.AcpRequestError({
2563 + code: -32601,
2564 + errorMessage: "ACP agent does not advertise logout support",
2565 + }),
2566 ),
2587 - prompt: (payload, promptOptions?) =>
2588 - promptSerializationSemaphore.withPermit(
2589 - Effect.acquireUseRelease(
2590 - promptDispatchSemaphore.withPermit(
2591 - Effect.gen(function* () {
2592 - const started = yield* getStartedState;
2593 - yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
2594 - yield* Ref.set(assistantUpdatesOpenRef, true);
2595 - const requestPayload = {
2596 - sessionId: started.sessionId,
2597 - ...payload,
2598 - } satisfies EffectAcpSchema.PromptRequest;
2599 - const completed = yield* Deferred.make<void>();
2600 - const fiber = yield* runLoggedRequest(
2601 - "session/prompt",
2602 - requestPayload,
2603 - acp.agent.prompt(requestPayload),
2604 - ).pipe(Effect.forkIn(runtimeScope));
2605 - const active = { fiber, completed } satisfies AcpActivePrompt;
2606 - yield* Ref.set(activePromptRef, Option.some(active));
2607 - if (promptOptions?.dispatched) {
2608 - yield* Deferred.succeed(promptOptions.dispatched, undefined);
2609 - }
2610 - return active;
2611 - }).pipe(notificationSemaphore.withPermit),
2612 - ),
2613 - (activePrompt) =>
2614 - Fiber.join(activePrompt.fiber).pipe(
2615 - Effect.catchCause((cause) =>
2616 - options.cancelBehavior !== "wait-for-prompt" && Cause.hasInterruptsOnly(cause)
2617 - ? Effect.succeed({
2618 - stopReason: "cancelled",
2619 - } satisfies EffectAcpSchema.PromptResponse)
2620 - : Effect.failCause(cause),
2621 - ),
2622 - Effect.tap(() =>
2623 - closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }),
2624 - ),
2625 - ),
2626 - (activePrompt, result) =>
2627 - Effect.gen(function* () {
2628 - if (
2629 - options.cancelBehavior === "wait-for-prompt" &&
2630 - Exit.isFailure(result) &&
2631 - Cause.hasInterrupts(result.cause)
2632 - ) {
2633 - yield* retireRuntime(
2634 - new EffectAcpErrors.AcpTransportError({
2635 - method: "session/prompt",
2636 - detail: "The ACP prompt stopped before the agent confirmed completion.",
2637 - cause: undefined,
2638 - }),
2639 - );
2640 - }
2641 - yield* Fiber.interrupt(activePrompt.fiber).pipe(Effect.ignore);
2642 - yield* Ref.set(activePromptRef, Option.none());
2643 - yield* Deferred.succeed(activePrompt.completed, undefined);
2644 - }),
2567 + Effect.andThen(runLoggedRequest("logout", {}, acp.agent.logout({}))),
2568 + ),
2569 + prompt: (payload, promptOptions?) =>
2570 + promptSerializationSemaphore.withPermit(
2571 + Effect.acquireUseRelease(
2572 + promptDispatchSemaphore.withPermit(
2573 + Effect.gen(function* () {
2574 + const started = yield* getStartedState;
2575 + yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
2576 + yield* Ref.set(assistantUpdatesOpenRef, true);
2577 + const requestPayload = {
2578 + sessionId: started.sessionId,
2579 + ...payload,
2580 + } satisfies EffectAcpSchema.PromptRequest;
2581 + const completed = yield* Deferred.make<void>();
2582 + const fiber = yield* runLoggedRequest(
2583 + "session/prompt",
2584 + requestPayload,
2585 + acp.agent.prompt(requestPayload),
2586 + ).pipe(Effect.forkIn(runtimeScope));
2587 + const active = { fiber, completed } satisfies AcpActivePrompt;
2588 + yield* Ref.set(activePromptRef, Option.some(active));
2589 + if (promptOptions?.dispatched) {
2590 + yield* Deferred.succeed(promptOptions.dispatched, undefined);
2591 + }
2592 + return active;
2593 + }).pipe(notificationSemaphore.withPermit),
2594 ),
2595 + (activePrompt) =>
2596 + Fiber.join(activePrompt.fiber).pipe(
2597 + Effect.catchCause((cause) =>
2598 + options.cancelBehavior !== "wait-for-prompt" && Cause.hasInterruptsOnly(cause)
2599 + ? Effect.succeed({
2600 + stopReason: "cancelled",
2601 + } satisfies EffectAcpSchema.PromptResponse)
2602 + : Effect.failCause(cause),
2603 + ),
2604 + Effect.tap(() =>
2605 + closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }),
2606 + ),
2607 + ),
2608 + (activePrompt, result) =>
2609 + Effect.gen(function* () {
2610 + if (
2611 + options.cancelBehavior === "wait-for-prompt" &&
2612 + Exit.isFailure(result) &&
2613 + Cause.hasInterrupts(result.cause)
2614 + ) {
2615 + yield* retireRuntime(
2616 + new EffectAcpErrors.AcpTransportError({
2617 + method: "session/prompt",
2618 + detail: "The ACP prompt stopped before the agent confirmed completion.",
2619 + cause: undefined,
2620 + }),
2621 + );
2622 + }
2623 + yield* Fiber.interrupt(activePrompt.fiber).pipe(Effect.ignore);
2624 + yield* Ref.set(activePromptRef, Option.none());
2625 + yield* Deferred.succeed(activePrompt.completed, undefined);
2626 + }),
2627 ),
2647 - cancel:
2648 - options.cancelBehavior === "wait-for-prompt"
2649 - ? promptDispatchSemaphore.withPermit(cancel)
2650 - : cancel,
2651 - ...(options.ownDetachedProcessGroup === true ? { terminateProcessGroup } : {}),
2652 - // A session's mode is its `category: "mode"` config option. ACP v1 agents
2653 - // that only advertise `modes` (gemini-cli) take `session/set_mode`
2654 - // instead, which ACP v2 removed.
2655 - setMode: (modeId) =>
2656 - Effect.gen(function* () {
2657 - const modeState = yield* Ref.get(modeStateRef);
2658 - if (modeState?.currentModeId === modeId) {
2659 - return {} satisfies EffectAcpSchema.SetSessionModeResponse;
2660 - }
2661 - const modeConfigOption = (yield* Ref.get(configOptionsRef))?.find(
2662 - (option) => option.category === "mode" && option.type === "select",
2663 - );
2664 - if (modeConfigOption === undefined && modeState !== undefined) {
2665 - const started = yield* getStartedState;
2666 - const payload = { sessionId: started.sessionId, modeId };
2667 - yield* runLoggedRequest("session/set_mode", payload, acp.agent.setSessionMode(payload));
2668 - yield* updateCurrentModeId(modeId);
2669 - return {} satisfies EffectAcpSchema.SetSessionModeResponse;
2670 - }
2671 - const response = yield* setConfigOption(modeConfigOption?.id ?? "mode", modeId);
2672 - const reported = parseSessionModeState({ configOptions: response.configOptions });
2673 - if (reported === undefined) {
2674 - yield* updateCurrentModeId(modeId);
2675 - } else {
2676 - yield* updateCurrentModeId(reported.currentModeId);
2677 - }
2678 - return {} satisfies EffectAcpSchema.SetSessionModeResponse;
2628 + ),
2629 + cancel:
2630 + options.cancelBehavior === "wait-for-prompt"
2631 + ? promptDispatchSemaphore.withPermit(cancel)
2632 + : cancel,
2633 + ...(options.ownDetachedProcessGroup === true ? { terminateProcessGroup } : {}),
2634 + // A session's mode is its `category: "mode"` config option. ACP v1 agents
2635 + // that only advertise `modes` (gemini-cli) take `session/set_mode`
2636 + // instead, which ACP v2 removed.
2637 + setMode: Effect.fn("AcpSessionRuntime.setMode")(function* (modeId) {
2638 + const modeState = yield* Ref.get(modeStateRef);
2639 + if (modeState?.currentModeId === modeId) {
2640 + return {} satisfies EffectAcpSchema.SetSessionModeResponse;
2641 + }
2642 + const modeConfigOption = (yield* Ref.get(configOptionsRef))?.find(
2643 + (option) => option.category === "mode" && option.type === "select",
2644 + );
2645 + if (modeConfigOption === undefined && modeState !== undefined) {
2646 + const started = yield* getStartedState;
2647 + const payload = { sessionId: started.sessionId, modeId };
2648 + yield* runLoggedRequest("session/set_mode", payload, acp.agent.setSessionMode(payload));
2649 + yield* updateCurrentModeId(modeId);
2650 + return {} satisfies EffectAcpSchema.SetSessionModeResponse;
2651 + }
2652 + const response = yield* setConfigOption(modeConfigOption?.id ?? "mode", modeId);
2653 + const reported = parseSessionModeState({ configOptions: response.configOptions });
2654 + if (reported === undefined) {
2655 + yield* updateCurrentModeId(modeId);
2656 + } else {
2657 + yield* updateCurrentModeId(reported.currentModeId);
2658 + }
2659 + return {} satisfies EffectAcpSchema.SetSessionModeResponse;
2660 + }),
2661 + setSessionModel: (modelId, meta) =>
2662 + getStartedState.pipe(
2663 + Effect.flatMap((started) => {
2664 + const payload = {
2665 + sessionId: started.sessionId,
2666 + modelId,
2667 + ...(meta === undefined ? {} : { _meta: meta }),
2668 + };
2669 + return runLoggedRequest("session/set_model", payload, acp.agent.setSessionModel(payload));
2670 }),
2680 - setSessionModel: (modelId, meta) =>
2681 - getStartedState.pipe(
2682 - Effect.flatMap((started) => {
2683 - const payload = {
2684 - sessionId: started.sessionId,
2685 - modelId,
2686 - ...(meta === undefined ? {} : { _meta: meta }),
2687 - };
2688 - return runLoggedRequest(
2689 - "session/set_model",
2690 - payload,
2691 - acp.agent.setSessionModel(payload),
2692 - );
2693 - }),
2694 - ),
2695 - setConfigOption,
2696 - setModel: (model) =>
2697 - getStartedState.pipe(
2698 - Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
2699 - Effect.asVoid,
2700 - ),
2671 + ),
2672 + setConfigOption,
2673 + setModel: (model) =>
2674 + getStartedState.pipe(
2675 + Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
2676 + Effect.asVoid,
2677 + ),
2678
2702 - request: (method, payload) =>
2703 - ensureConnected.pipe(
2704 - Effect.andThen(runLoggedRequest(method, payload, acp.raw.request(method, payload))),
2705 - ),
2706 - notify: (method, payload) =>
2707 - ensureConnected.pipe(Effect.andThen(acp.raw.notify(method, payload))),
2708 - } satisfies AcpSessionRuntime["Service"];
2709 - });
2679 + request: (method, payload) =>
2680 + ensureConnected.pipe(
2681 + Effect.andThen(runLoggedRequest(method, payload, acp.raw.request(method, payload))),
2682 + ),
2683 + notify: (method, payload) =>
2684 + ensureConnected.pipe(Effect.andThen(acp.raw.notify(method, payload))),
2685 + } satisfies AcpSessionRuntime["Service"];
2686 +});
2687
2688 export const layer = (
2689 options: AcpSessionRuntimeOptions,
@@ -2751,26 +2728,27 @@ function isStartupMetadataUpdate(notification: EffectAcpSchema.SessionNotificati
2728 }
2729 }
2730
2754 -const handleSessionUpdate = ({
2755 - queue,
2756 - modeStateRef,
2757 - configOptionsRef,
2758 - toolCallsRef,
2759 - shownToolCallIds,
2760 - assistantSegmentRef,
2761 - assistantItemRuntimeId,
2762 - params,
2763 -}: {
2764 - readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
2765 - readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
2766 - readonly configOptionsRef: Ref.Ref<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
2767 - readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallTrackedState>>;
2768 - readonly shownToolCallIds: Set<string>;
2769 - readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
2770 - readonly assistantItemRuntimeId: string;
2771 - readonly params: EffectAcpSchema.SessionNotification;
2772 -}): Effect.Effect<void> =>
2773 - Effect.gen(function* () {
2731 +const handleSessionUpdate =
2732 + /* Provider events include streaming deltas; avoid a span for each update. */
2733 + Effect.fnUntraced(function* ({
2734 + queue,
2735 + modeStateRef,
2736 + configOptionsRef,
2737 + toolCallsRef,
2738 + shownToolCallIds,
2739 + assistantSegmentRef,
2740 + assistantItemRuntimeId,
2741 + params,
2742 + }: {
2743 + readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
2744 + readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
2745 + readonly configOptionsRef: Ref.Ref<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
2746 + readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallTrackedState>>;
2747 + readonly shownToolCallIds: Set<string>;
2748 + readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
2749 + readonly assistantItemRuntimeId: string;
2750 + readonly params: EffectAcpSchema.SessionNotification;
2751 + }): Effect.fn.Return<void> {
2752 if (params.update.sessionUpdate === "config_option_update") {
2753 const configOptions = params.update.configOptions;
2754 yield* Ref.set(configOptionsRef, configOptions);
packages/provider-acp/src/server/adapter.ts
+71 -64
@@ -1568,12 +1568,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
1568 return Option.some(yield* effect);
1569 }),
1570 );
1571 - const registerNativeResponseAcknowledgement = (
1572 - generation: number,
1573 - transportRequestId: string,
1574 - acknowledgement: Deferred.Deferred<void, EffectAcpErrors.AcpError>,
1575 - ) =>
1576 - Effect.gen(function* () {
1571 + const registerNativeResponseAcknowledgement =
1572 + /* Provider events include streaming deltas; avoid a span for each update. */
1573 + Effect.fnUntraced(function* (
1574 + generation: number,
1575 + transportRequestId: string,
1576 + acknowledgement: Deferred.Deferred<void, EffectAcpErrors.AcpError>,
1577 + ) {
1578 yield* Ref.update(nativeResponseAcknowledgements, (current) => {
1579 const updated = new Map(current);
1580 updated.set(transportRequestId, { acknowledgement, generation });
@@ -1813,8 +1814,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
1814 const endedBackgroundTaskIds = yield* Ref.make<ReadonlySet<string>>(new Set());
1815 const endedBackgroundTaskIdLimit = 128;
1816
1816 - const setBackgroundTaskRunning = (taskId: string, running: boolean) =>
1817 - Effect.gen(function* () {
1817 + const setBackgroundTaskRunning =
1818 + /* Provider events include streaming deltas; avoid a span for each update. */
1819 + Effect.fnUntraced(function* (taskId: string, running: boolean) {
1820 if (running && (yield* Ref.get(endedBackgroundTaskIds)).has(taskId)) {
1821 return;
1822 }
@@ -1849,10 +1851,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
1851 ? setBackgroundTaskRunning(mutation.taskId, true)
1852 : markBackgroundTaskEnded(mutation.taskId);
1853
1852 - const trackRunningBackgroundTools = (
1853 - notification: EffectAcpSchema.SessionNotification,
1854 - ): Effect.Effect<void> =>
1855 - Effect.gen(function* () {
1854 + const trackRunningBackgroundTools =
1855 + /* Provider events include streaming deltas; avoid a span for each update. */
1856 + Effect.fnUntraced(function* (
1857 + notification: EffectAcpSchema.SessionNotification,
1858 + ): Effect.fn.Return<void> {
1859 if (flavor.extractBackgroundTaskId === undefined) return;
1860 for (const event of parseSessionUpdateEvent(notification).events) {
1861 if (event._tag !== "ToolCallUpdated") continue;
@@ -2836,8 +2839,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
2839 return false;
2840 };
2841
2839 - const rearmDeferredFinalize = (context: ActiveAcpTurn) =>
2840 - Effect.gen(function* () {
2842 + const rearmDeferredFinalize =
2843 + /* Provider events include streaming deltas; avoid a span for each update. */
2844 + Effect.fnUntraced(function* (context: ActiveAcpTurn) {
2845 if (!flavor.deferFinalizeForBackgroundWork) return;
2846 if (!context.promptSettled || context.finalized) return;
2847 if (hasDeferredBackgroundWork(context)) return;
@@ -2851,8 +2855,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
2855 projectedStatus?: ProjectedToolStatus,
2856 ) => Effect.Effect<void> = () => Effect.void;
2857
2854 - const markAwaitingBackgroundHydration = (context: ActiveAcpTurn, taskId: string) =>
2855 - Effect.gen(function* () {
2858 + const markAwaitingBackgroundHydration =
2859 + /* Provider events include streaming deltas; avoid a span for each update. */
2860 + Effect.fnUntraced(function* (context: ActiveAcpTurn, taskId: string) {
2861 if (context.awaitingBackgroundHydration.has(taskId)) return;
2862 context.awaitingBackgroundHydration.add(taskId);
2863 yield* Effect.gen(function* () {
@@ -2871,8 +2876,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
2876 }).pipe(Effect.forkIn(sessionScope), Effect.asVoid);
2877 });
2878
2874 - const markPendingInjectedReport = (context: ActiveAcpTurn, taskId: string) =>
2875 - Effect.gen(function* () {
2879 + const markPendingInjectedReport =
2880 + /* Provider events include streaming deltas; avoid a span for each update. */
2881 + Effect.fnUntraced(function* (context: ActiveAcpTurn, taskId: string) {
2882 if (!context.promptSettled) return;
2883 if (context.pendingInjectedReport.has(taskId)) return;
2884 context.pendingInjectedReport.add(taskId);
@@ -3421,13 +3427,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
3427 });
3428 });
3429
3424 - const appendLoadedHistory = (
3425 - notification: EffectAcpSchema.SessionNotification,
3426 - role: "user" | "assistant" | "thought",
3427 - text: string,
3428 - replace = false,
3429 - ) =>
3430 - Effect.gen(function* () {
3430 + const appendLoadedHistory =
3431 + /* Provider events include streaming deltas; avoid a span for each update. */
3432 + Effect.fnUntraced(function* (
3433 + notification: EffectAcpSchema.SessionNotification,
3434 + role: "user" | "assistant" | "thought",
3435 + text: string,
3436 + replace = false,
3437 + ) {
3438 if (text.length === 0 && !replace) return;
3439 const now = yield* DateTime.now;
3440 yield* Ref.update(snapshot, (current) => {
@@ -5088,47 +5095,47 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
5095 }
5096 });
5097
5091 - const projectAcpRuntimeSessionUpdateEffect = (
5092 - rawNotification: EffectAcpSchema.SessionNotification,
5093 - ) =>
5094 - Effect.gen(function* () {
5095 - if (clientTerminals !== undefined) {
5096 - const embedded = embeddedTerminalIdsFromSessionUpdate(rawNotification);
5097 - if (embedded !== undefined) {
5098 - rememberEmbeddedTerminals({
5099 - ...embedded,
5100 - sessionId: rawNotification.sessionId,
5101 - });
5098 + const projectAcpRuntimeSessionUpdateEffect =
5099 + /* Provider events include streaming deltas; avoid a span for each update. */
5100 + Effect.fnUntraced(
5101 + function* (rawNotification: EffectAcpSchema.SessionNotification) {
5102 + if (clientTerminals !== undefined) {
5103 + const embedded = embeddedTerminalIdsFromSessionUpdate(rawNotification);
5104 + if (embedded !== undefined) {
5105 + rememberEmbeddedTerminals({
5106 + ...embedded,
5107 + sessionId: rawNotification.sessionId,
5108 + });
5109 + }
5110 }
5103 - }
5104 - const notification =
5105 - clientTerminals === undefined
5106 - ? rawNotification
5107 - : resolveEmbeddedTerminalContent(
5108 - rawNotification,
5109 - clientTerminals.readOutputSnapshot,
5110 - );
5111 - if (notification.update.sessionUpdate === "available_commands_update") {
5112 - yield* (
5113 - flavor.onAvailableCommandsUpdate?.(notification.update.availableCommands) ??
5114 - Effect.void
5115 - );
5116 - }
5117 - if (
5118 - notification.update.sessionUpdate === "config_option_update" ||
5119 - notification.update.sessionUpdate === "current_mode_update"
5120 - ) {
5121 - yield* (
5122 - flavor.onSessionConfigurationUpdate?.(
5123 - yield* runtime.getConfigOptions,
5124 - yield* runtime.getModeState,
5125 - ) ?? Effect.void
5111 + const notification =
5112 + clientTerminals === undefined
5113 + ? rawNotification
5114 + : resolveEmbeddedTerminalContent(
5115 + rawNotification,
5116 + clientTerminals.readOutputSnapshot,
5117 + );
5118 + if (notification.update.sessionUpdate === "available_commands_update") {
5119 + yield* (
5120 + flavor.onAvailableCommandsUpdate?.(notification.update.availableCommands) ??
5121 + Effect.void
5122 + );
5123 + }
5124 + if (
5125 + notification.update.sessionUpdate === "config_option_update" ||
5126 + notification.update.sessionUpdate === "current_mode_update"
5127 + ) {
5128 + yield* (
5129 + flavor.onSessionConfigurationUpdate?.(
5130 + yield* runtime.getConfigOptions,
5131 + yield* runtime.getModeState,
5132 + ) ?? Effect.void
5133 + );
5134 + }
5135 + yield* handleSessionUpdate(
5136 + flavor.normalizeSessionUpdate?.(notification) ?? notification,
5137 );
5127 - }
5128 - yield* handleSessionUpdate(
5129 - flavor.normalizeSessionUpdate?.(notification) ?? notification,
5130 - );
5131 - }).pipe(
5138 + },
5139 Effect.mapError(
5140 (cause) =>
5141 new EffectAcpErrors.AcpTransportError({
packages/provider-acp/src/server/mcpOverAcpBridge.ts
+79 -83
@@ -139,94 +139,90 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun
139 }).pipe(Effect.mapError(bridgeError)),
140 );
141
142 - const disconnect = (
142 + const disconnect = Effect.fn("mcpOverAcpBridge.disconnect")(function* (
143 request: AcpSchema.DisconnectMcpRequest,
144 - ): Effect.Effect<AcpSchema.DisconnectMcpResponse, AcpMcpOverAcpError> =>
145 - Effect.gen(function* () {
146 - const connection = yield* connectionFor(request.connectionId);
147 - connections.delete(request.connectionId);
148 - const sessionId = connection.sessionId;
149 - if (sessionId !== null) {
150 - const response = yield* Effect.tryPromise({
151 - try: (signal) =>
152 - fetchImplementation(options.endpoint, {
153 - method: "DELETE",
154 - signal,
155 - headers: {
156 - authorization: options.authorization,
157 - "mcp-session-id": sessionId,
158 - ...(connection.protocolVersion === null
159 - ? {}
160 - : { "mcp-protocol-version": connection.protocolVersion }),
161 - },
162 - }),
163 - catch: bridgeError,
164 - });
165 - if (!response.ok && response.status !== 404) {
166 - return yield* Effect.fail(
167 - new AcpMcpOverAcpError(
168 - `T3 Code MCP endpoint rejected disconnect with HTTP ${response.status}.`,
169 - ),
170 - );
171 - }
172 - yield* Effect.promise(
173 - () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(),
144 + ): Effect.fn.Return<AcpSchema.DisconnectMcpResponse, AcpMcpOverAcpError> {
145 + const connection = yield* connectionFor(request.connectionId);
146 + connections.delete(request.connectionId);
147 + const sessionId = connection.sessionId;
148 + if (sessionId !== null) {
149 + const response = yield* Effect.tryPromise({
150 + try: (signal) =>
151 + fetchImplementation(options.endpoint, {
152 + method: "DELETE",
153 + signal,
154 + headers: {
155 + authorization: options.authorization,
156 + "mcp-session-id": sessionId,
157 + ...(connection.protocolVersion === null
158 + ? {}
159 + : { "mcp-protocol-version": connection.protocolVersion }),
160 + },
161 + }),
162 + catch: bridgeError,
163 + });
164 + if (!response.ok && response.status !== 404) {
165 + return yield* Effect.fail(
166 + new AcpMcpOverAcpError(
167 + `T3 Code MCP endpoint rejected disconnect with HTTP ${response.status}.`,
168 + ),
169 );
170 }
176 - return {};
177 - });
171 + yield* Effect.promise(
172 + () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(),
173 + );
174 + }
175 + return {};
176 + });
177
178 return {
180 - connect: (request) =>
181 - Effect.gen(function* () {
182 - if (request.serverId !== "t3-code") {
183 - return yield* Effect.fail(
184 - new AcpMcpOverAcpError(`Unknown ACP MCP server "${request.serverId}".`),
185 - );
186 - }
187 - if (connections.size >= MAX_CONNECTIONS) {
188 - return yield* Effect.fail(new AcpMcpOverAcpError("Too many MCP-over-ACP connections."));
189 - }
190 - const connectionId = yield* options.allocateConnectionId;
191 - connections.set(connectionId, {
192 - mutex: yield* Semaphore.make(1),
193 - sessionId: null,
194 - protocolVersion: null,
195 - nextRequestId: 0,
196 - });
197 - return { connectionId };
198 - }),
199 - message: (request) =>
200 - Effect.gen(function* () {
201 - const connection = yield* connectionFor(request.connectionId);
202 - const id = ++connection.nextRequestId;
203 - const payloads = yield* send(connection, {
204 - jsonrpc: "2.0",
205 - id,
206 - method: request.method,
207 - ...(request.params == null ? {} : { params: request.params }),
208 - });
209 - const response = payloads.find((payload) => asEnvelope(payload)?.id === id);
210 - const envelope = asEnvelope(response);
211 - if (envelope === null) {
212 - return yield* Effect.fail(
213 - new AcpMcpOverAcpError("MCP server did not return a matching response."),
214 - );
215 - }
216 - if (envelope.error !== undefined) {
217 - return yield* Effect.fail(new AcpMcpOverAcpError(errorMessage(envelope.error)));
218 - }
219 - return (envelope.result ?? null) as AcpSchema.MessageMcpResponse;
220 - }),
221 - notification: (request) =>
222 - Effect.gen(function* () {
223 - const connection = yield* connectionFor(request.connectionId);
224 - yield* send(connection, {
225 - jsonrpc: "2.0",
226 - method: request.method,
227 - ...(request.params == null ? {} : { params: request.params }),
228 - });
229 - }),
179 + connect: Effect.fn("mcpOverAcpBridge.connect")(function* (request) {
180 + if (request.serverId !== "t3-code") {
181 + return yield* Effect.fail(
182 + new AcpMcpOverAcpError(`Unknown ACP MCP server "${request.serverId}".`),
183 + );
184 + }
185 + if (connections.size >= MAX_CONNECTIONS) {
186 + return yield* Effect.fail(new AcpMcpOverAcpError("Too many MCP-over-ACP connections."));
187 + }
188 + const connectionId = yield* options.allocateConnectionId;
189 + connections.set(connectionId, {
190 + mutex: yield* Semaphore.make(1),
191 + sessionId: null,
192 + protocolVersion: null,
193 + nextRequestId: 0,
194 + });
195 + return { connectionId };
196 + }),
197 + message: Effect.fn("mcpOverAcpBridge.message")(function* (request) {
198 + const connection = yield* connectionFor(request.connectionId);
199 + const id = ++connection.nextRequestId;
200 + const payloads = yield* send(connection, {
201 + jsonrpc: "2.0",
202 + id,
203 + method: request.method,
204 + ...(request.params == null ? {} : { params: request.params }),
205 + });
206 + const response = payloads.find((payload) => asEnvelope(payload)?.id === id);
207 + const envelope = asEnvelope(response);
208 + if (envelope === null) {
209 + return yield* Effect.fail(
210 + new AcpMcpOverAcpError("MCP server did not return a matching response."),
211 + );
212 + }
213 + if (envelope.error !== undefined) {
214 + return yield* Effect.fail(new AcpMcpOverAcpError(errorMessage(envelope.error)));
215 + }
216 + return (envelope.result ?? null) as AcpSchema.MessageMcpResponse;
217 + }),
218 + notification: Effect.fn("mcpOverAcpBridge.notification")(function* (request) {
219 + const connection = yield* connectionFor(request.connectionId);
220 + yield* send(connection, {
221 + jsonrpc: "2.0",
222 + method: request.method,
223 + ...(request.params == null ? {} : { params: request.params }),
224 + });
225 + }),
226 disconnect,
227 dispose: Effect.suspend(() =>
228 Effect.forEach(
packages/provider-acp/src/server/nativeLogging.ts
+14 -17
@@ -126,11 +126,8 @@ export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory"
126 readonly threadId: ThreadId;
127 readonly verboseProtocolLogging?: boolean;
128 }): Pick<AcpSessionRuntime.AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> => {
129 - const writeNativeAcpLog = (logInput: {
130 - readonly kind: "request" | "protocol";
131 - readonly payload: unknown;
132 - }) =>
133 - Effect.gen(function* () {
129 + const writeNativeAcpLog = Effect.fn("AcpNativeLogging.writeNativeAcpLog")(
130 + function* (logInput: { readonly kind: "request" | "protocol"; readonly payload: unknown }) {
131 if (!input.nativeEventLogger) return;
132 const observedAt = DateTime.formatIso(yield* DateTime.now);
133 yield* input.nativeEventLogger.write(
@@ -147,18 +144,18 @@ export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory"
144 },
145 input.threadId,
146 );
150 - }).pipe(
151 - Effect.catchCause((cause) =>
152 - Cause.hasInterrupts(cause)
153 - ? Effect.interrupt
154 - : Effect.logWarning("Failed to write native ACP event log.", {
155 - errorTag: causeErrorTag(cause),
156 - reasonCount: cause.reasons.length,
157 - provider: input.provider,
158 - threadId: input.threadId,
159 - }),
160 - ),
161 - );
147 + },
148 + Effect.catchCause((cause) =>
149 + Cause.hasInterrupts(cause)
150 + ? Effect.interrupt
151 + : Effect.logWarning("Failed to write native ACP event log.", {
152 + errorTag: causeErrorTag(cause),
153 + reasonCount: cause.reasons.length,
154 + provider: input.provider,
155 + threadId: input.threadId,
156 + }),
157 + ),
158 + );
159
160 return {
161 requestLogger: (event: AcpSessionRuntime.AcpSessionRequestLogEvent) =>
packages/provider-acp/src/server/runtimeModel.ts
+15 -18
@@ -1287,27 +1287,24 @@ export interface SessionLoadGate {
1287 readonly candidateConfigOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
1288 }
1289
1290 -export const waitForSessionLoadReplayIdle = (input: {
1290 +export const waitForSessionLoadReplayIdle = Effect.fn(
1291 + "AcpRuntimeModel.waitForSessionLoadReplayIdle",
1292 +)(function* (input: {
1293 readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;
1292 -}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>
1293 - Effect.gen(function* () {
1294 - const pollInterval = Duration.millis(25);
1295 - while (true) {
1296 - const gate = yield* Ref.get(input.gateRef);
1297 - if (
1298 - Option.isSome(gate) &&
1299 - gate.value.active &&
1300 - gate.value.lastActivityAtMillis !== undefined
1301 - ) {
1302 - const idleGapMillis = Duration.toMillis(gate.value.idleGap);
1303 - const nowMillis = yield* Clock.currentTimeMillis;
1304 - if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
1305 - return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
1306 - }
1294 +}): Effect.fn.Return<EffectAcpSchema.LoadSessionResponse, never> {
1295 + const pollInterval = Duration.millis(25);
1296 + while (true) {
1297 + const gate = yield* Ref.get(input.gateRef);
1298 + if (Option.isSome(gate) && gate.value.active && gate.value.lastActivityAtMillis !== undefined) {
1299 + const idleGapMillis = Duration.toMillis(gate.value.idleGap);
1300 + const nowMillis = yield* Clock.currentTimeMillis;
1301 + if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
1302 + return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
1303 }
1308 - yield* Effect.sleep(pollInterval);
1304 }
1310 - });
1305 + yield* Effect.sleep(pollInterval);
1306 + }
1307 +});
1308
1309 export function sessionModelStateFromInitialize(
1310 initializeResult: EffectAcpSchema.InitializeResponse,
packages/provider-cursor/src/server/accountUsage.ts
+8 -8
@@ -176,8 +176,8 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi
176 let completed = false;
177 const pageSize = 1000;
178 let total: number | undefined;
179 - const readPage = (page: number) =>
180 - Effect.gen(function* () {
179 + const readPage = Effect.fn("CursorAccountUsage.readPage")(
180 + function* (page: number) {
181 // A count can include overlapping page boundaries. Allow room to
182 // reconcile them without imposing a fixed account-size limit.
183 if (page > (total === undefined ? 1000 : Math.ceil(total / pageSize) * 2 + 1)) {
@@ -243,12 +243,12 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi
243 }
244 if (typeof count === "number") total = count;
245 return events as unknown[];
246 - }).pipe(
247 - Effect.timeoutOrElse({
248 - duration: Duration.seconds(10),
249 - orElse: () => invalid("Account usage request timed out"),
250 - }),
251 - );
246 + },
247 + Effect.timeoutOrElse({
248 + duration: Duration.seconds(10),
249 + orElse: () => invalid("Account usage request timed out"),
250 + }),
251 + );
252 // Cursor caps a page at 1,000 events and takes about a second to answer one, so the pages
253 // the first one's count implies are requested up to six ahead and consumed in page order.
254 const ahead: Fiber.Fiber<
packages/provider-cursor/src/server/auth.ts
+47 -41
@@ -154,8 +154,8 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu
154 }),
155 );
156
157 - const runLogin = (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) =>
158 - Effect.gen(function* () {
157 + const runLogin = Effect.fn("CursorAuth.runLogin")(
158 + function* (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) {
159 yield* stopSessions.pipe(Effect.ensuring(stopSessionsWithCredentials));
160 // The SDK first writes into memory. Cancellation must not save a late login result.
161 const pendingStore = new InMemoryCredentialStore();
@@ -243,50 +243,56 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu
243 });
244 }).pipe(Effect.uninterruptible),
245 );
246 - }).pipe(
247 - Effect.scoped,
248 - Effect.timeoutOrElse({
249 - duration: AUTH_TIMEOUT_MS,
250 - orElse: () =>
251 - Effect.fail(
252 - new ProviderSetupError({
253 - instanceId: options.instanceId,
254 - operation: "start",
255 - detail: "Cursor sign-in expired. Start sign-in again.",
246 + },
247 + (effect, flow, stopSessions) =>
248 + effect.pipe(
249 + Effect.scoped,
250 + Effect.timeoutOrElse({
251 + duration: AUTH_TIMEOUT_MS,
252 + orElse: () =>
253 + Effect.fail(
254 + new ProviderSetupError({
255 + instanceId: options.instanceId,
256 + operation: "start",
257 + detail: "Cursor sign-in expired. Start sign-in again.",
258 + }),
259 + ),
260 + }),
261 + Effect.exit,
262 + Effect.flatMap((result) =>
263 + lock.withPermits(1)(
264 + Effect.gen(function* () {
265 + if (active !== flow) return;
266 + active = undefined;
267 + operation = "idle";
268 + yield* publish(flow, {
269 + phase: Exit.isSuccess(result) ? "succeeded" : "failed",
270 + authorizationUrl: null,
271 + expiresAt: null,
272 + message: Exit.isSuccess(result)
273 + ? "Signed in with Cursor."
274 + : "Cursor sign-in failed or expired. Start sign-in again.",
275 + });
276 }),
277 ),
258 - }),
259 - Effect.exit,
260 - Effect.flatMap((result) =>
261 - lock.withPermits(1)(
262 - Effect.gen(function* () {
263 - if (active !== flow) return;
264 - active = undefined;
265 - operation = "idle";
266 - yield* publish(flow, {
267 - phase: Exit.isSuccess(result) ? "succeeded" : "failed",
268 - authorizationUrl: null,
269 - expiresAt: null,
270 - message: Exit.isSuccess(result)
271 - ? "Signed in with Cursor."
272 - : "Cursor sign-in failed or expired. Start sign-in again.",
273 - });
274 - }),
278 ),
279 ),
277 - );
280 + );
281
279 - const requireFlow = (owner: string, id: string, name: string) =>
280 - Effect.gen(function* () {
281 - if (!active || active.owner !== owner || active.id !== id) {
282 - return yield* new ProviderSetupError({
283 - instanceId: options.instanceId,
284 - operation: name,
285 - detail: "This sign-in is no longer active in this client.",
286 - });
287 - }
288 - return active;
289 - });
282 + const requireFlow = Effect.fn("CursorAuth.requireFlow")(function* (
283 + owner: string,
284 + id: string,
285 + name: string,
286 + ) {
287 + if (!active || active.owner !== owner || active.id !== id) {
288 + return yield* new ProviderSetupError({
289 + instanceId: options.instanceId,
290 + operation: name,
291 + detail: "This sign-in is no longer active in this client.",
292 + });
293 + }
294 + return active;
295 + });
296
297 const controller: ProviderAuthController = {
298 credentialBinding: options.credentialBinding ?? {
packages/provider-cursor/src/server/driver.ts
+212 -206
@@ -86,224 +86,230 @@ export const CursorDriver: ProviderDriver<
86 ),
87 ),
88 },
89 - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
90 - Effect.gen(function* () {
91 - const host = yield* ProviderHost.ProviderHost;
92 - const fileSystem = yield* FileSystem.FileSystem;
93 - const path = yield* Path.Path;
94 - const httpClient = yield* HttpClient.HttpClient;
95 - const keychain = yield* CursorKeychain.CursorKeychain;
96 - const sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner;
97 - const processEnv = yield* mergeProviderInstanceEnvironment(environment);
98 - const continuationIdentity = defaultProviderContinuationIdentity({
99 - driverKind: DRIVER_KIND,
100 - instanceId,
101 - });
102 - const stampIdentity = withInstanceIdentity({
103 - instanceId,
104 - driverKind: DRIVER_KIND,
105 - displayName: displayName ?? "Cursor",
106 - accentColor,
107 - continuationGroupKey: continuationIdentity.continuationKey,
108 - });
109 - const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
110 - const credentials = yield* CursorCredentialStore.makeCursorCredentialStore(
111 - instanceId,
112 - path.join(
113 - host.paths.stateDir,
114 - "provider-auth",
115 - encodeURIComponent(instanceId),
116 - "cursor.json",
117 - ),
118 - ).pipe(
119 - Effect.mapError(
120 - (cause) =>
121 - new ProviderDriverError({
122 - driver: DRIVER_KIND,
123 - instanceId,
124 - detail: "Could not open the Cursor credential store.",
125 - cause,
126 - }),
127 - ),
128 - );
129 - const auth = yield* makeCursorAuth({
130 - instanceId,
131 - displayName: displayName ?? "Cursor",
132 - enabled,
133 - ...(processEnv.CURSOR_API_KEY ? { apiKey: processEnv.CURSOR_API_KEY } : {}),
134 - store: credentials.store,
135 - credentialBinding: credentials.binding,
136 - onChanged: (signedIn): Effect.Effect<void, ProviderSetupError> =>
137 - snapshot.refresh.pipe(
138 - Effect.flatMap((provider) =>
139 - !signedIn || provider.auth.status === "authenticated"
140 - ? Effect.void
141 - : Effect.fail(
142 - new ProviderSetupError({
143 - instanceId,
144 - operation: "start",
145 - detail: provider.message ?? "Could not verify the Cursor sign-in. Try again.",
146 - }),
147 - ),
148 - ),
89 + create: Effect.fn("CursorDriver.create")(function* ({
90 + instanceId,
91 + displayName,
92 + accentColor,
93 + environment,
94 + enabled,
95 + config,
96 + }) {
97 + const host = yield* ProviderHost.ProviderHost;
98 + const fileSystem = yield* FileSystem.FileSystem;
99 + const path = yield* Path.Path;
100 + const httpClient = yield* HttpClient.HttpClient;
101 + const keychain = yield* CursorKeychain.CursorKeychain;
102 + const sdkRunner = yield* CursorAgentSdk.CursorAgentSdkRunner;
103 + const processEnv = yield* mergeProviderInstanceEnvironment(environment);
104 + const continuationIdentity = defaultProviderContinuationIdentity({
105 + driverKind: DRIVER_KIND,
106 + instanceId,
107 + });
108 + const stampIdentity = withInstanceIdentity({
109 + instanceId,
110 + driverKind: DRIVER_KIND,
111 + displayName: displayName ?? "Cursor",
112 + accentColor,
113 + continuationGroupKey: continuationIdentity.continuationKey,
114 + });
115 + const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
116 + const credentials = yield* CursorCredentialStore.makeCursorCredentialStore(
117 + instanceId,
118 + path.join(
119 + host.paths.stateDir,
120 + "provider-auth",
121 + encodeURIComponent(instanceId),
122 + "cursor.json",
123 + ),
124 + ).pipe(
125 + Effect.mapError(
126 + (cause) =>
127 + new ProviderDriverError({
128 + driver: DRIVER_KIND,
129 + instanceId,
130 + detail: "Could not open the Cursor credential store.",
131 + cause,
132 + }),
133 + ),
134 + );
135 + const auth = yield* makeCursorAuth({
136 + instanceId,
137 + displayName: displayName ?? "Cursor",
138 + enabled,
139 + ...(processEnv.CURSOR_API_KEY ? { apiKey: processEnv.CURSOR_API_KEY } : {}),
140 + store: credentials.store,
141 + credentialBinding: credentials.binding,
142 + onChanged: (signedIn): Effect.Effect<void, ProviderSetupError> =>
143 + snapshot.refresh.pipe(
144 + Effect.flatMap((provider) =>
145 + !signedIn || provider.auth.status === "authenticated"
146 + ? Effect.void
147 + : Effect.fail(
148 + new ProviderSetupError({
149 + instanceId,
150 + operation: "start",
151 + detail: provider.message ?? "Could not verify the Cursor sign-in. Try again.",
152 + }),
153 + ),
154 ),
155 + ),
156 + });
157 + const stampSnapshot: typeof stampIdentity = (draft) =>
158 + stampIdentity({
159 + ...draft,
160 + setup: { canAuthenticate: !auth.usesApiKey, canInstall: false },
161 + auth: {
162 + ...draft.auth,
163 + canLogout: !auth.usesApiKey,
164 + },
165 });
151 - const stampSnapshot: typeof stampIdentity = (draft) =>
152 - stampIdentity({
153 - ...draft,
154 - setup: { canAuthenticate: !auth.usesApiKey, canInstall: false },
155 - auth: {
156 - ...draft.auth,
157 - canLogout: !auth.usesApiKey,
158 - },
159 - });
166
161 - let catalogModels: ReadonlyArray<ServerProviderModel> = [];
162 - const orchestrationAdapter = yield* makeCursorAdapterV2({
163 - instanceId,
164 - settings: effectiveConfig,
165 - environment: processEnv,
166 - getModels: () => catalogModels,
167 - }).pipe(
168 - Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
169 - ...sdkRunner,
170 - open: (input) =>
171 - auth.requireApiKey.pipe(
172 - Effect.flatMap((apiKey) =>
173 - Effect.acquireRelease(
174 - sdkRunner
175 - .open({ ...input, options: { ...input.options, apiKey } })
176 - .pipe(
177 - Effect.flatMap((session) =>
178 - Effect.cached(session.close).pipe(
179 - Effect.map((close) => ({ ...session, close })),
180 - ),
167 + let catalogModels: ReadonlyArray<ServerProviderModel> = [];
168 + const orchestrationAdapter = yield* makeCursorAdapterV2({
169 + instanceId,
170 + settings: effectiveConfig,
171 + environment: processEnv,
172 + getModels: () => catalogModels,
173 + }).pipe(
174 + Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
175 + ...sdkRunner,
176 + open: (input) =>
177 + auth.requireApiKey.pipe(
178 + Effect.flatMap((apiKey) =>
179 + Effect.acquireRelease(
180 + sdkRunner
181 + .open({ ...input, options: { ...input.options, apiKey } })
182 + .pipe(
183 + Effect.flatMap((session) =>
184 + Effect.cached(session.close).pipe(
185 + Effect.map((close) => ({ ...session, close })),
186 ),
187 ),
183 - (session) => session.close.pipe(Effect.ignore),
184 - ),
185 - ),
186 - auth.withAccess,
187 - Effect.mapError((cause) =>
188 - isSdkRunnerError(cause)
189 - ? cause
190 - : new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "open", cause }),
188 + ),
189 + (session) => session.close.pipe(Effect.ignore),
190 ),
191 ),
193 - }),
194 - Effect.mapError(
195 - (cause) =>
196 - new ProviderDriverError({
197 - driver: DRIVER_KIND,
198 - instanceId,
199 - detail: "Failed to build Cursor orchestration adapter.",
200 - cause,
201 - }),
202 - ),
203 - );
204 - const textGeneration = yield* makeCursorTextGeneration(
205 - effectiveConfig,
206 - processEnv,
207 - auth.requireApiKey,
208 - auth.withAccess,
209 - );
210 -
211 - const checkProvider = auth.readApiKey.pipe(
212 - Effect.orElseSucceed(() => undefined),
213 - Effect.flatMap((apiKey) =>
214 - checkCursorProviderStatus(
215 - effectiveConfig,
216 - {
217 - ...processEnv,
218 - CURSOR_API_KEY: apiKey,
219 - },
220 - auth.usesApiKey ? "api-key" : "browser",
221 - ).pipe(
222 - Effect.flatMap((snapshot) =>
223 - effectiveConfig.enabled &&
224 - snapshot.installed &&
225 - snapshot.auth.status === "authenticated"
226 - ? host.settings.get.pipe(
227 - Effect.flatMap((settings) =>
228 - readCursorUsageLimits(
229 - effectiveConfig,
230 - { ...processEnv, CURSOR_API_KEY: apiKey },
231 - settings.cursorKeychainUsageEnabled,
232 - ),
233 - ),
234 - Effect.map((usageLimits) => ({ ...snapshot, usageLimits })),
235 - )
236 - : Effect.succeed(snapshot),
192 + auth.withAccess,
193 + Effect.mapError((cause) =>
194 + isSdkRunnerError(cause)
195 + ? cause
196 + : new CursorAgentSdk.CursorAgentSdkRunnerError({ method: "open", cause }),
197 ),
198 ),
239 - ),
240 - Effect.provideService(HttpClient.HttpClient, httpClient),
241 - Effect.provideService(FileSystem.FileSystem, fileSystem),
242 - Effect.provideService(Path.Path, path),
243 - Effect.provideService(CursorKeychain.CursorKeychain, keychain),
244 - Effect.map(stampSnapshot),
245 - Effect.tap((provider) =>
246 - Effect.sync(() => {
247 - // A failed check lists only custom models, so keep the last loaded catalog.
248 - if (provider.models.some((model) => !model.isCustom)) {
249 - catalogModels = provider.models;
250 - }
199 + }),
200 + Effect.mapError(
201 + (cause) =>
202 + new ProviderDriverError({
203 + driver: DRIVER_KIND,
204 + instanceId,
205 + detail: "Failed to build Cursor orchestration adapter.",
206 + cause,
207 }),
252 - ),
253 - Effect.provide(CursorSdkCatalog.layer),
254 - );
208 + ),
209 + );
210 + const textGeneration = yield* makeCursorTextGeneration(
211 + effectiveConfig,
212 + processEnv,
213 + auth.requireApiKey,
214 + auth.withAccess,
215 + );
216
256 - const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
257 - const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({
258 - resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),
259 - getSettings: snapshotSettings.getSettings,
260 - streamSettings: snapshotSettings.streamSettings,
261 - haveSettingsChanged: haveProviderSnapshotSettingsChanged,
262 - initialSnapshot: (settings) =>
263 - buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampSnapshot)),
264 - checkProvider,
265 - }).pipe(
266 - Effect.mapError(
267 - (cause) =>
268 - new ProviderDriverError({
269 - driver: DRIVER_KIND,
270 - instanceId,
271 - detail: "Failed to build Cursor snapshot.",
272 - cause,
273 - }),
217 + const checkProvider = auth.readApiKey.pipe(
218 + Effect.orElseSucceed(() => undefined),
219 + Effect.flatMap((apiKey) =>
220 + checkCursorProviderStatus(
221 + effectiveConfig,
222 + {
223 + ...processEnv,
224 + CURSOR_API_KEY: apiKey,
225 + },
226 + auth.usesApiKey ? "api-key" : "browser",
227 + ).pipe(
228 + Effect.flatMap((snapshot) =>
229 + effectiveConfig.enabled &&
230 + snapshot.installed &&
231 + snapshot.auth.status === "authenticated"
232 + ? host.settings.get.pipe(
233 + Effect.flatMap((settings) =>
234 + readCursorUsageLimits(
235 + effectiveConfig,
236 + { ...processEnv, CURSOR_API_KEY: apiKey },
237 + settings.cursorKeychainUsageEnabled,
238 + ),
239 + ),
240 + Effect.map((usageLimits) => ({ ...snapshot, usageLimits })),
241 + )
242 + : Effect.succeed(snapshot),
243 + ),
244 ),
275 - );
245 + ),
246 + Effect.provideService(HttpClient.HttpClient, httpClient),
247 + Effect.provideService(FileSystem.FileSystem, fileSystem),
248 + Effect.provideService(Path.Path, path),
249 + Effect.provideService(CursorKeychain.CursorKeychain, keychain),
250 + Effect.map(stampSnapshot),
251 + Effect.tap((provider) =>
252 + Effect.sync(() => {
253 + // A failed check lists only custom models, so keep the last loaded catalog.
254 + if (provider.models.some((model) => !model.isCustom)) {
255 + catalogModels = provider.models;
256 + }
257 + }),
258 + ),
259 + Effect.provide(CursorSdkCatalog.layer),
260 + );
261
277 - return {
278 - instanceId,
279 - driverKind: DRIVER_KIND,
280 - continuationIdentity,
281 - displayName,
282 - accentColor,
283 - enabled,
284 - auth: auth.controller,
285 - snapshot,
286 - snapshotForCwd: (cwd) =>
287 - !effectiveConfig.enabled
288 - ? snapshot.getSnapshot
289 - : Effect.all([
290 - snapshot.getSnapshot,
291 - probeCursorSkills(cwd, processEnv).pipe(
292 - Effect.provideService(FileSystem.FileSystem, fileSystem),
293 - Effect.provideService(Path.Path, path),
294 - Effect.mapError(
295 - (cause) =>
296 - new ProviderDriverError({
297 - driver: DRIVER_KIND,
298 - instanceId,
299 - detail: `Failed to discover Cursor skills for '${cwd}'`,
300 - cause,
301 - }),
302 - ),
262 + const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
263 + const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({
264 + resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),
265 + getSettings: snapshotSettings.getSettings,
266 + streamSettings: snapshotSettings.streamSettings,
267 + haveSettingsChanged: haveProviderSnapshotSettingsChanged,
268 + initialSnapshot: (settings) =>
269 + buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampSnapshot)),
270 + checkProvider,
271 + }).pipe(
272 + Effect.mapError(
273 + (cause) =>
274 + new ProviderDriverError({
275 + driver: DRIVER_KIND,
276 + instanceId,
277 + detail: "Failed to build Cursor snapshot.",
278 + cause,
279 + }),
280 + ),
281 + );
282 +
283 + return {
284 + instanceId,
285 + driverKind: DRIVER_KIND,
286 + continuationIdentity,
287 + displayName,
288 + accentColor,
289 + enabled,
290 + auth: auth.controller,
291 + snapshot,
292 + snapshotForCwd: (cwd) =>
293 + !effectiveConfig.enabled
294 + ? snapshot.getSnapshot
295 + : Effect.all([
296 + snapshot.getSnapshot,
297 + probeCursorSkills(cwd, processEnv).pipe(
298 + Effect.provideService(FileSystem.FileSystem, fileSystem),
299 + Effect.provideService(Path.Path, path),
300 + Effect.mapError(
301 + (cause) =>
302 + new ProviderDriverError({
303 + driver: DRIVER_KIND,
304 + instanceId,
305 + detail: `Failed to discover Cursor skills for '${cwd}'`,
306 + cause,
307 + }),
308 ),
304 - ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills }))),
305 - orchestrationAdapter,
306 - textGeneration,
307 - } satisfies ProviderInstance;
308 - }),
309 + ),
310 + ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills }))),
311 + orchestrationAdapter,
312 + textGeneration,
313 + } satisfies ProviderInstance;
314 + }),
315 };
packages/provider-cursor/src/server/status.ts
+24 -26
@@ -34,44 +34,42 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
34
35 const CURSOR_SDK_CATALOG_TIMEOUT_MS = 15_000;
36
37 -export function buildInitialCursorProviderSnapshot(
38 - cursorSettings: CursorSettings,
39 -): Effect.Effect<ServerProviderDraft> {
40 - return Effect.gen(function* () {
41 - const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
42 - const models = getCursorFallbackModels(cursorSettings);
43 -
44 - if (!cursorSettings.enabled) {
45 - return buildServerProvider({
46 - presentation: CURSOR_PRESENTATION,
47 - enabled: false,
48 - checkedAt,
49 - models,
50 - probe: {
51 - installed: false,
52 - version: null,
53 - status: "warning",
54 - auth: { status: "unknown" },
55 - message: "Cursor is disabled in T3 Code settings.",
56 - },
57 - });
58 - }
37 +export const buildInitialCursorProviderSnapshot = Effect.fn(
38 + "CursorProviderStatus.buildInitialCursorProviderSnapshot",
39 +)(function* (cursorSettings: CursorSettings): Effect.fn.Return<ServerProviderDraft> {
40 + const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
41 + const models = getCursorFallbackModels(cursorSettings);
42
43 + if (!cursorSettings.enabled) {
44 return buildServerProvider({
45 presentation: CURSOR_PRESENTATION,
62 - enabled: true,
46 + enabled: false,
47 checkedAt,
48 models,
49 probe: {
66 - installed: true,
50 + installed: false,
51 version: null,
52 status: "warning",
53 auth: { status: "unknown" },
70 - message: "Checking Cursor SDK availability...",
54 + message: "Cursor is disabled in T3 Code settings.",
55 },
56 });
57 + }
58 +
59 + return buildServerProvider({
60 + presentation: CURSOR_PRESENTATION,
61 + enabled: true,
62 + checkedAt,
63 + models,
64 + probe: {
65 + installed: true,
66 + version: null,
67 + status: "warning",
68 + auth: { status: "unknown" },
69 + message: "Checking Cursor SDK availability...",
70 + },
71 });
74 -}
72 +});
73
74 function getCursorFallbackModels(
75 cursorSettings: Pick<CursorSettings, "customModels">,
packages/provider-cursor/src/server/textGeneration.ts
+45 -38
@@ -57,31 +57,35 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
57 const { Agent, SqliteLocalAgentStore } = yield* CursorSdk.CursorSdk;
58 const resolvedEnvironment = environment ?? process.env;
59
60 - const resolveCursorApiKey = (operation: TextGenerationOperations.Operation) =>
61 - Effect.gen(function* () {
62 - if (!cursorSettings.enabled) {
63 - return yield* new TextGenerationError({
64 - operation,
65 - detail: "Cursor is disabled in T3 Code settings.",
66 - });
67 - }
60 + const resolveCursorApiKey = Effect.fn("CursorTextGeneration.resolveCursorApiKey")(function* (
61 + operation: TextGenerationOperations.Operation,
62 + ) {
63 + if (!cursorSettings.enabled) {
64 + return yield* new TextGenerationError({
65 + operation,
66 + detail: "Cursor is disabled in T3 Code settings.",
67 + });
68 + }
69
69 - const apiKey = resolveApiKey
70 - ? yield* resolveApiKey
71 - : resolvedEnvironment.CURSOR_API_KEY?.trim();
72 - if (!apiKey) {
73 - return yield* new TextGenerationError({
74 - operation,
75 - detail: "Sign in with Cursor or add CURSOR_API_KEY in provider settings.",
76 - });
77 - }
70 + const apiKey = resolveApiKey
71 + ? yield* resolveApiKey
72 + : resolvedEnvironment.CURSOR_API_KEY?.trim();
73 + if (!apiKey) {
74 + return yield* new TextGenerationError({
75 + operation,
76 + detail: "Sign in with Cursor or add CURSOR_API_KEY in provider settings.",
77 + });
78 + }
79 +
80 + return apiKey;
81 + });
82
79 - return apiKey;
80 - });
83 + const runCursorJson: TextGenerationOperations.Runner = Effect.fn(
84 + "CursorTextGeneration.runCursorJson",
85 + )(
86 + function* (input) {
87 + const { operation, prompt, modelSelection } = input;
88
82 - const runCursorJson: TextGenerationOperations.Runner = (input) => {
83 - const { operation, prompt, modelSelection } = input;
84 - return Effect.gen(function* () {
89 const apiKey = yield* resolveCursorApiKey(operation);
90 // The SDK loads sandbox.json independently of settingSources and lets it
91 // expand the writable paths. Its public API cannot override that policy.
@@ -187,22 +191,25 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
191 }
192
193 return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);
190 - }).pipe(
191 - // Scope this call inside `withAccess`, so sign-out closes the agent before its store.
192 - Effect.scoped,
193 - (effect) => (withAccess ? withAccess(effect) : effect),
194 - Effect.scoped,
195 - Effect.mapError((cause) =>
196 - isTextGenerationError(cause)
197 - ? cause
198 - : new TextGenerationError({
199 - operation,
200 - detail: "Cursor SDK text generation failed.",
201 - cause,
202 - }),
203 - ),
204 - );
205 - };
194 + },
195 + (effect, input) => {
196 + const { operation } = input;
197 + return effect.pipe(
198 + Effect.scoped,
199 + (effect) => (withAccess ? withAccess(effect) : effect),
200 + Effect.scoped,
201 + Effect.mapError((cause) =>
202 + isTextGenerationError(cause)
203 + ? cause
204 + : new TextGenerationError({
205 + operation,
206 + detail: "Cursor SDK text generation failed.",
207 + cause,
208 + }),
209 + ),
210 + );
211 + },
212 + );
213
214 return TextGenerationOperations.fromRunner(
215 "CursorTextGeneration",
packages/provider-grok/src/server/acpSupport.ts
+24 -27
@@ -145,37 +145,34 @@ export function grokApprovalOptions(
145 ];
146 }
147
148 -export const makeGrokAcpRuntime = (
148 +export const makeGrokAcpRuntime = Effect.fn("GrokAcpSupport.makeGrokAcpRuntime")(function* (
149 input: GrokAcpRuntimeInput,
150 -): Effect.Effect<
150 +): Effect.fn.Return<
151 AcpSessionRuntime.AcpSessionRuntime["Service"],
152 EffectAcpErrors.AcpError,
153 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
154 -> =>
155 - Effect.gen(function* () {
156 - const processGroupPlatform = yield* HostProcess.Platform.pipe(
157 - Effect.provide(NodeServices.layer),
158 - );
159 - const acpContext = yield* Layer.build(
160 - AcpSessionRuntime.layer({
161 - ...input,
162 - spawn: buildGrokAcpSpawnInput(
163 - input.grokSettings,
164 - input.cwd,
165 - input.environment,
166 - input.runtimeMode,
167 - ),
168 - authMethodId: resolveGrokAuthMethodId(input.environment),
169 - cancelMeta: { ...input.cancelMeta, ...GROK_ACP_CANCEL_META },
170 - initializeMeta: GROK_ACP_INITIALIZE_META,
171 - ...grokAcpRuntimeProcessOwnership(processGroupPlatform),
172 - }),
173 - );
174 - const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
175 - Effect.provide(acpContext),
176 - );
177 - return yield* makeXAiPromptCompletionRuntime(runtime);
178 - });
154 +> {
155 + const processGroupPlatform = yield* HostProcess.Platform.pipe(Effect.provide(NodeServices.layer));
156 + const acpContext = yield* Layer.build(
157 + AcpSessionRuntime.layer({
158 + ...input,
159 + spawn: buildGrokAcpSpawnInput(
160 + input.grokSettings,
161 + input.cwd,
162 + input.environment,
163 + input.runtimeMode,
164 + ),
165 + authMethodId: resolveGrokAuthMethodId(input.environment),
166 + cancelMeta: { ...input.cancelMeta, ...GROK_ACP_CANCEL_META },
167 + initializeMeta: GROK_ACP_INITIALIZE_META,
168 + ...grokAcpRuntimeProcessOwnership(processGroupPlatform),
169 + }),
170 + );
171 + const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
172 + Effect.provide(acpContext),
173 + );
174 + return yield* makeXAiPromptCompletionRuntime(runtime);
175 +});
176
177 /**
178 * It is the CLI's product name, not a model id the ACP accepts, so selecting it
packages/provider-grok/src/server/adapter.ts
+19 -16
@@ -264,22 +264,25 @@ export function makeGrokAcpAdapterFlavor(
264 ? window
265 : undefined;
266 },
267 - applyModelSelection: ({ runtime, startResult, modelSelection }) =>
268 - Effect.gen(function* () {
269 - const legacy = startResult.initializeResult.protocolVersion === 1;
270 - const options = legacy ? [] : yield* runtime.getConfigOptions;
271 - const configuredModel = findModelConfigOption(options)?.currentValue;
272 - return yield* applyGrokAcpModelSelection({
273 - runtime: legacy
274 - ? runtime
275 - : { setSessionModel: (model) => runtime.setModel(model).pipe(Effect.as({})) },
276 - currentModelId: legacy
277 - ? currentGrokModelIdFromSessionSetup(startResult.sessionSetupResult)
278 - : configuredModel,
279 - requestedModelId: resolveGrokAcpBaseModelId(modelSelection.model),
280 - mapError: (cause) => cause,
281 - });
282 - }),
267 + applyModelSelection: Effect.fn("GrokAdapter.applyModelSelection")(function* ({
268 + runtime,
269 + startResult,
270 + modelSelection,
271 + }) {
272 + const legacy = startResult.initializeResult.protocolVersion === 1;
273 + const options = legacy ? [] : yield* runtime.getConfigOptions;
274 + const configuredModel = findModelConfigOption(options)?.currentValue;
275 + return yield* applyGrokAcpModelSelection({
276 + runtime: legacy
277 + ? runtime
278 + : { setSessionModel: (model) => runtime.setModel(model).pipe(Effect.as({})) },
279 + currentModelId: legacy
280 + ? currentGrokModelIdFromSessionSetup(startResult.sessionSetupResult)
281 + : configuredModel,
282 + requestedModelId: resolveGrokAcpBaseModelId(modelSelection.model),
283 + mapError: (cause) => cause,
284 + });
285 + }),
286 makeRuntime:
287 options.makeRuntime ??
288 (({ runtimePolicy, ...input }) =>
packages/provider-grok/src/server/driver.ts
+136 -130
@@ -111,142 +111,148 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv, Path.Path>
111 configSchema: GrokSettings,
112 defaultConfig: (): GrokSettings => decodeGrokSettings({}),
113 usage: grokUsageReader,
114 - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
115 - Effect.gen(function* () {
116 - const crypto = yield* Crypto.Crypto;
117 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
118 - const httpClient = yield* HttpClient.HttpClient;
119 - const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
120 - const fileSystem = yield* FileSystem.FileSystem;
121 - const path = yield* Path.Path;
122 - const host = yield* ProviderHost.ProviderHost;
123 - const { cwd } = host.paths;
124 - const processEnv = yield* mergeProviderInstanceEnvironment(environment);
125 - const continuationIdentity = defaultProviderContinuationIdentity({
126 - driverKind: DRIVER_KIND,
127 - instanceId,
128 - });
129 - const stampIdentity = withInstanceIdentity({
130 - instanceId,
131 - driverKind: DRIVER_KIND,
132 - displayName,
133 - accentColor,
134 - continuationGroupKey: continuationIdentity.continuationKey,
135 - });
136 - const effectiveConfig = { ...config, enabled } satisfies GrokSettings;
137 - const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
138 - resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
139 - binaryPath: effectiveConfig.binaryPath,
140 - env: processEnv,
141 - }).pipe(
142 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
143 - Effect.provideService(FileSystem.FileSystem, fileSystem),
144 - Effect.provideService(Path.Path, path),
145 - ),
146 - );
147 - const orchestrationAdapter = yield* GrokAdapterV2Driver.create({
148 - instanceId,
149 - displayName,
150 - accentColor,
151 - environment,
152 - enabled,
153 - config,
114 + create: Effect.fn("GrokDriver.create")(function* ({
115 + instanceId,
116 + displayName,
117 + accentColor,
118 + environment,
119 + enabled,
120 + config,
121 + }) {
122 + const crypto = yield* Crypto.Crypto;
123 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
124 + const httpClient = yield* HttpClient.HttpClient;
125 + const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
126 + const fileSystem = yield* FileSystem.FileSystem;
127 + const path = yield* Path.Path;
128 + const host = yield* ProviderHost.ProviderHost;
129 + const { cwd } = host.paths;
130 + const processEnv = yield* mergeProviderInstanceEnvironment(environment);
131 + const continuationIdentity = defaultProviderContinuationIdentity({
132 + driverKind: DRIVER_KIND,
133 + instanceId,
134 + });
135 + const stampIdentity = withInstanceIdentity({
136 + instanceId,
137 + driverKind: DRIVER_KIND,
138 + displayName,
139 + accentColor,
140 + continuationGroupKey: continuationIdentity.continuationKey,
141 + });
142 + const effectiveConfig = { ...config, enabled } satisfies GrokSettings;
143 + const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
144 + resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
145 + binaryPath: effectiveConfig.binaryPath,
146 + env: processEnv,
147 }).pipe(
155 - Effect.mapError(
156 - (cause) =>
157 - new ProviderDriverError({
158 - driver: DRIVER_KIND,
159 - instanceId,
160 - detail: "Failed to build Grok orchestration adapter.",
161 - cause,
162 - }),
163 - ),
164 - );
165 - const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);
166 -
167 - const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv, cwd).pipe(
168 - Effect.flatMap((snapshot) =>
169 - effectiveConfig.enabled && snapshot.installed && snapshot.auth.status === "authenticated"
170 - ? readGrokAccount(processEnv).pipe(
171 - Effect.map(({ email, usageLimits }) => ({
172 - ...snapshot,
173 - auth: email ? { ...snapshot.auth, email } : snapshot.auth,
174 - usageLimits,
175 - })),
176 - )
177 - : Effect.succeed(snapshot),
178 - ),
179 - Effect.map(stampIdentity),
180 - Effect.provideService(HttpClient.HttpClient, httpClient),
148 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
149 Effect.provideService(FileSystem.FileSystem, fileSystem),
150 Effect.provideService(Path.Path, path),
183 - Effect.provideService(Crypto.Crypto, crypto),
184 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
185 - );
151 + ),
152 + );
153 + const orchestrationAdapter = yield* GrokAdapterV2Driver.create({
154 + instanceId,
155 + displayName,
156 + accentColor,
157 + environment,
158 + enabled,
159 + config,
160 + }).pipe(
161 + Effect.mapError(
162 + (cause) =>
163 + new ProviderDriverError({
164 + driver: DRIVER_KIND,
165 + instanceId,
166 + detail: "Failed to build Grok orchestration adapter.",
167 + cause,
168 + }),
169 + ),
170 + );
171 + const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);
172
187 - const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
188 - const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({
189 - resolveMaintenance,
190 - getSettings: snapshotSettings.getSettings,
191 - streamSettings: snapshotSettings.streamSettings,
192 - haveSettingsChanged: haveProviderSnapshotSettingsChanged,
193 - initialSnapshot: (settings) =>
194 - buildInitialGrokProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
195 - checkProvider,
196 - enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
197 - resolveMaintenance().pipe(
198 - Effect.flatMap((maintenanceCapabilities) =>
199 - enrichGrokSnapshot({
200 - snapshot: currentSnapshot,
201 - maintenanceCapabilities,
202 - enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
203 - publishSnapshot,
204 - }),
205 - ),
206 - Effect.provideService(HttpClient.HttpClient, httpClient),
207 - Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
208 - ),
209 - }).pipe(
210 - Effect.mapError(
211 - (cause) =>
212 - new ProviderDriverError({
213 - driver: DRIVER_KIND,
214 - instanceId,
215 - detail: "Failed to build Grok snapshot.",
216 - cause,
173 + const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv, cwd).pipe(
174 + Effect.flatMap((snapshot) =>
175 + effectiveConfig.enabled && snapshot.installed && snapshot.auth.status === "authenticated"
176 + ? readGrokAccount(processEnv).pipe(
177 + Effect.map(({ email, usageLimits }) => ({
178 + ...snapshot,
179 + auth: email ? { ...snapshot.auth, email } : snapshot.auth,
180 + usageLimits,
181 + })),
182 + )
183 + : Effect.succeed(snapshot),
184 + ),
185 + Effect.map(stampIdentity),
186 + Effect.provideService(HttpClient.HttpClient, httpClient),
187 + Effect.provideService(FileSystem.FileSystem, fileSystem),
188 + Effect.provideService(Path.Path, path),
189 + Effect.provideService(Crypto.Crypto, crypto),
190 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
191 + );
192 +
193 + const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
194 + const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({
195 + resolveMaintenance,
196 + getSettings: snapshotSettings.getSettings,
197 + streamSettings: snapshotSettings.streamSettings,
198 + haveSettingsChanged: haveProviderSnapshotSettingsChanged,
199 + initialSnapshot: (settings) =>
200 + buildInitialGrokProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
201 + checkProvider,
202 + enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
203 + resolveMaintenance().pipe(
204 + Effect.flatMap((maintenanceCapabilities) =>
205 + enrichGrokSnapshot({
206 + snapshot: currentSnapshot,
207 + maintenanceCapabilities,
208 + enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
209 + publishSnapshot,
210 }),
211 + ),
212 + Effect.provideService(HttpClient.HttpClient, httpClient),
213 + Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
214 ),
219 - );
220 - const snapshotForCwd = (workspaceCwd: string) =>
221 - !effectiveConfig.enabled
222 - ? snapshot.getSnapshot
223 - : Effect.all([
224 - snapshot.getSnapshot,
225 - discoverGrokSkills(effectiveConfig, processEnv, workspaceCwd).pipe(
226 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
227 - Effect.mapError(
228 - (cause) =>
229 - new ProviderDriverError({
230 - driver: DRIVER_KIND,
231 - instanceId,
232 - detail: `Failed to discover Grok skills for '${workspaceCwd}'`,
233 - cause,
234 - }),
235 - ),
215 + }).pipe(
216 + Effect.mapError(
217 + (cause) =>
218 + new ProviderDriverError({
219 + driver: DRIVER_KIND,
220 + instanceId,
221 + detail: "Failed to build Grok snapshot.",
222 + cause,
223 + }),
224 + ),
225 + );
226 + const snapshotForCwd = (workspaceCwd: string) =>
227 + !effectiveConfig.enabled
228 + ? snapshot.getSnapshot
229 + : Effect.all([
230 + snapshot.getSnapshot,
231 + discoverGrokSkills(effectiveConfig, processEnv, workspaceCwd).pipe(
232 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
233 + Effect.mapError(
234 + (cause) =>
235 + new ProviderDriverError({
236 + driver: DRIVER_KIND,
237 + instanceId,
238 + detail: `Failed to discover Grok skills for '${workspaceCwd}'`,
239 + cause,
240 + }),
241 ),
237 - ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })));
242 + ),
243 + ]).pipe(Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })));
244
239 - return {
240 - instanceId,
241 - driverKind: DRIVER_KIND,
242 - continuationIdentity,
243 - displayName,
244 - accentColor,
245 - enabled,
246 - snapshot,
247 - snapshotForCwd,
248 - orchestrationAdapter,
249 - textGeneration,
250 - } satisfies ProviderInstance;
251 - }),
245 + return {
246 + instanceId,
247 + driverKind: DRIVER_KIND,
248 + continuationIdentity,
249 + displayName,
250 + accentColor,
251 + enabled,
252 + snapshot,
253 + snapshotForCwd,
254 + orchestrationAdapter,
255 + textGeneration,
256 + } satisfies ProviderInstance;
257 + }),
258 };
packages/provider-grok/src/server/status.ts
+51 -56
@@ -71,44 +71,42 @@ const GROK_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
71 },
72 ];
73
74 -export function buildInitialGrokProviderSnapshot(
75 - grokSettings: GrokSettings,
76 -): Effect.Effect<ServerProviderDraft> {
77 - return Effect.gen(function* () {
78 - const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
79 - const models = grokModelsFromSettings(grokSettings.customModels);
80 -
81 - if (!grokSettings.enabled) {
82 - return buildServerProvider({
83 - presentation: GROK_PRESENTATION,
84 - enabled: false,
85 - checkedAt,
86 - models,
87 - probe: {
88 - installed: false,
89 - version: null,
90 - status: "warning",
91 - auth: { status: "unknown" },
92 - message: "Grok is disabled in T3 Code settings.",
93 - },
94 - });
95 - }
74 +export const buildInitialGrokProviderSnapshot = Effect.fn(
75 + "GrokProviderStatus.buildInitialGrokProviderSnapshot",
76 +)(function* (grokSettings: GrokSettings): Effect.fn.Return<ServerProviderDraft> {
77 + const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
78 + const models = grokModelsFromSettings(grokSettings.customModels);
79
80 + if (!grokSettings.enabled) {
81 return buildServerProvider({
82 presentation: GROK_PRESENTATION,
99 - enabled: true,
83 + enabled: false,
84 checkedAt,
85 models,
86 probe: {
103 - installed: true,
87 + installed: false,
88 version: null,
89 status: "warning",
90 auth: { status: "unknown" },
107 - message: "Checking Grok CLI availability...",
91 + message: "Grok is disabled in T3 Code settings.",
92 },
93 });
94 + }
95 +
96 + return buildServerProvider({
97 + presentation: GROK_PRESENTATION,
98 + enabled: true,
99 + checkedAt,
100 + models,
101 + probe: {
102 + installed: true,
103 + version: null,
104 + status: "warning",
105 + auth: { status: "unknown" },
106 + message: "Checking Grok CLI availability...",
107 + },
108 });
111 -}
109 +});
110
111 function grokModelsFromSettings(
112 customModels: ReadonlyArray<CustomModelSetting> | undefined,
@@ -287,22 +285,21 @@ function displayNameFromGrokModelSlug(slug: string): string {
285 .join(" ");
286 }
287
290 -const runGrokCliCommand = (
288 +const runGrokCliCommand = Effect.fn("GrokProviderStatus.runGrokCliCommand")(function* (
289 grokSettings: GrokSettings,
290 args: ReadonlyArray<string>,
291 environment: NodeJS.ProcessEnv,
294 -) =>
295 - Effect.gen(function* () {
296 - const command = grokSettings.binaryPath || "grok";
297 - const spawnCommand = yield* resolveSpawnCommand(command, args, { env: environment });
298 - return yield* spawnAndCollect(
299 - command,
300 - ChildProcess.make(spawnCommand.command, spawnCommand.args, {
301 - env: environment,
302 - shell: spawnCommand.shell,
303 - }),
304 - );
305 - });
292 +) {
293 + const command = grokSettings.binaryPath || "grok";
294 + const spawnCommand = yield* resolveSpawnCommand(command, args, { env: environment });
295 + return yield* spawnAndCollect(
296 + command,
297 + ChildProcess.make(spawnCommand.command, spawnCommand.args, {
298 + env: environment,
299 + shell: spawnCommand.shell,
300 + }),
301 + );
302 +});
303
304 const decodeAvailableCommands = Schema.decodeUnknownOption(Schema.Array(Schema.Unknown));
305 const decodeAvailableCommand = Schema.decodeUnknownOption(
@@ -343,23 +340,21 @@ export function grokSlashCommandsFromInitialize(
340 * This never calls `authenticate` or `session/new`, so it cannot open a browser login or
341 * boot the workspace's MCP servers.
342 */
346 -const discoverGrokMetadataViaAcpInitialize = (
347 - grokSettings: GrokSettings,
348 - environment: NodeJS.ProcessEnv,
349 -) =>
350 - Effect.gen(function* () {
351 - const acp = yield* makeGrokAcpRuntime({
352 - grokSettings,
353 - environment,
354 - cwd: process.cwd(),
355 - clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
356 - });
357 - const initialized = yield* acp.initialize();
358 - return {
359 - models: buildGrokModelsFromSessionModelState(sessionModelStateFromInitialize(initialized)),
360 - slashCommands: grokSlashCommandsFromInitialize(initialized),
361 - };
362 - }).pipe(Effect.scoped);
343 +const discoverGrokMetadataViaAcpInitialize = Effect.fn(
344 + "GrokProviderStatus.discoverGrokMetadataViaAcpInitialize",
345 +)(function* (grokSettings: GrokSettings, environment: NodeJS.ProcessEnv) {
346 + const acp = yield* makeGrokAcpRuntime({
347 + grokSettings,
348 + environment,
349 + cwd: process.cwd(),
350 + clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
351 + });
352 + const initialized = yield* acp.initialize();
353 + return {
354 + models: buildGrokModelsFromSessionModelState(sessionModelStateFromInitialize(initialized)),
355 + slashCommands: grokSlashCommandsFromInitialize(initialized),
356 + };
357 +}, Effect.scoped);
358
359 export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
360 grokSettings: GrokSettings,
packages/provider-grok/src/server/textGeneration.ts
+21 -16
@@ -30,9 +30,10 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
30 const crypto = yield* Crypto.Crypto;
31 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
32
33 - const runGrokJson: TextGenerationOperations.Runner = (request) => {
34 - const { operation, cwd, prompt, modelSelection } = request;
35 - return Effect.gen(function* () {
33 + const runGrokJson: TextGenerationOperations.Runner = Effect.fn("GrokTextGeneration.runGrokJson")(
34 + function* (request) {
35 + const { operation, cwd, prompt, modelSelection } = request;
36 +
37 const outputRef = yield* Ref.make("");
38 const runtime = yield* makeGrokAcpRuntime({
39 grokSettings,
@@ -115,19 +116,23 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
116 }
117
118 return yield* TextGenerationOperations.decodeJsonReply(request, "Grok Agent", trimmed);
118 - }).pipe(
119 - Effect.mapError((cause) =>
120 - isTextGenerationError(cause)
121 - ? cause
122 - : new TextGenerationError({
123 - operation,
124 - detail: "Grok ACP text generation failed.",
125 - cause,
126 - }),
127 - ),
128 - Effect.scoped,
129 - );
130 - };
119 + },
120 + (effect, request) => {
121 + const { operation } = request;
122 + return effect.pipe(
123 + Effect.mapError((cause) =>
124 + isTextGenerationError(cause)
125 + ? cause
126 + : new TextGenerationError({
127 + operation,
128 + detail: "Grok ACP text generation failed.",
129 + cause,
130 + }),
131 + ),
132 + Effect.scoped,
133 + );
134 + },
135 + );
136
137 return TextGenerationOperations.fromRunner(
138 "GrokTextGeneration",
packages/provider-grok/src/server/xaiAcpExtension.ts
+49 -50
@@ -1536,58 +1536,57 @@ export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletion
1536 );
1537 })
1538 : runtime.handleExtNotification(method, payload, handler),
1539 - prompt: (payload, promptOptions?) =>
1540 - Effect.gen(function* () {
1541 - const started = yield* runtime.start();
1542 - const promptId = yield* allocatePromptFallbackId;
1543 - const fallback = yield* registerXAiPromptCompletionFallback(
1544 - pendingXAiPromptCompletionsRef,
1545 - started.sessionId,
1546 - promptId,
1547 - );
1548 - const cancelledResponse = promptResponseFromXAi({
1549 - sessionId: started.sessionId,
1550 - promptId: fallback.promptId,
1551 - stopReason: "cancelled",
1552 - agentResult: null,
1553 - });
1554 - const promptRpcFiber = yield* runtime
1555 - .prompt(
1556 - {
1557 - ...payload,
1558 - _meta: {
1559 - ...payload._meta,
1560 - promptId: fallback.promptId,
1561 - requestId: fallback.promptId,
1562 - },
1539 + prompt: Effect.fn("xaiAcpExtension.prompt")(function* (payload, promptOptions?) {
1540 + const started = yield* runtime.start();
1541 + const promptId = yield* allocatePromptFallbackId;
1542 + const fallback = yield* registerXAiPromptCompletionFallback(
1543 + pendingXAiPromptCompletionsRef,
1544 + started.sessionId,
1545 + promptId,
1546 + );
1547 + const cancelledResponse = promptResponseFromXAi({
1548 + sessionId: started.sessionId,
1549 + promptId: fallback.promptId,
1550 + stopReason: "cancelled",
1551 + agentResult: null,
1552 + });
1553 + const promptRpcFiber = yield* runtime
1554 + .prompt(
1555 + {
1556 + ...payload,
1557 + _meta: {
1558 + ...payload._meta,
1559 + promptId: fallback.promptId,
1560 + requestId: fallback.promptId,
1561 },
1564 - promptOptions,
1565 - )
1566 - .pipe(Effect.forkChild);
1567 - return yield* Effect.raceFirst(
1568 - Fiber.join(promptRpcFiber).pipe(
1569 - Effect.catchCause((cause) =>
1570 - Cause.hasInterruptsOnly(cause)
1571 - ? Effect.succeed(cancelledResponse)
1572 - : Effect.failCause(cause),
1573 - ),
1574 - ),
1575 - Deferred.await(fallback.deferred),
1576 - ).pipe(
1577 - Effect.tap((response) =>
1578 - rememberCompletedXAiPromptId(completedXAiPromptIdsRef, response, fallback.promptId),
1562 + },
1563 + promptOptions,
1564 + )
1565 + .pipe(Effect.forkChild);
1566 + return yield* Effect.raceFirst(
1567 + Fiber.join(promptRpcFiber).pipe(
1568 + Effect.catchCause((cause) =>
1569 + Cause.hasInterruptsOnly(cause)
1570 + ? Effect.succeed(cancelledResponse)
1571 + : Effect.failCause(cause),
1572 ),
1580 - Effect.ensuring(
1581 - Effect.gen(function* () {
1582 - yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);
1583 - yield* unregisterXAiPromptCompletionFallback(
1584 - pendingXAiPromptCompletionsRef,
1585 - fallback.deferred,
1586 - );
1587 - }),
1588 - ),
1589 - );
1590 - }),
1573 + ),
1574 + Deferred.await(fallback.deferred),
1575 + ).pipe(
1576 + Effect.tap((response) =>
1577 + rememberCompletedXAiPromptId(completedXAiPromptIdsRef, response, fallback.promptId),
1578 + ),
1579 + Effect.ensuring(
1580 + Effect.gen(function* () {
1581 + yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);
1582 + yield* unregisterXAiPromptCompletionFallback(
1583 + pendingXAiPromptCompletionsRef,
1584 + fallback.deferred,
1585 + );
1586 + }),
1587 + ),
1588 + );
1589 + }),
1590 cancel: Effect.gen(function* () {
1591 // Do not call start here: cancellation must be able to reach the
1592 // underlying runtime when startup is stalled.
packages/provider-muse/src/server/adapter.ts
+46 -37
@@ -2141,8 +2141,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
2141 ),
2142 ),
2143 compactThread: (args) => start(args, true).pipe(commands.withPermits(1)),
2144 - steerTurn: (args) =>
2145 - Effect.gen(function* () {
2144 + steerTurn: Effect.fn("MuseAdapter.steerTurn")(
2145 + function* (args) {
2146 const turn = active;
2147 if (
2148 !turn ||
@@ -2158,20 +2158,23 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
2158 }).pipe(Effect.flatMap((value) => decode(MuseTurnStartResult, value)));
2159 if (result.turnId !== turn.nativeId)
2160 return yield* protocolError("Muse steering targeted a different turn");
2161 - }).pipe(
2162 - commands.withPermits(1),
2163 - Effect.mapError(
2164 - (cause) =>
2165 - new ProviderAdapter.ProviderAdapterSteerRunError({
2166 - driver: MUSE_PROVIDER,
2167 - providerThreadId: args.providerThread.id,
2168 - providerTurnId: args.providerTurnId,
2169 - cause,
2170 - }),
2161 + },
2162 + (effect, args) =>
2163 + effect.pipe(
2164 + commands.withPermits(1),
2165 + Effect.mapError(
2166 + (cause) =>
2167 + new ProviderAdapter.ProviderAdapterSteerRunError({
2168 + driver: MUSE_PROVIDER,
2169 + providerThreadId: args.providerThread.id,
2170 + providerTurnId: args.providerTurnId,
2171 + cause,
2172 + }),
2173 + ),
2174 ),
2172 - ),
2173 - interruptTurn: (args) =>
2174 - Effect.gen(function* () {
2175 + ),
2176 + interruptTurn: Effect.fn("MuseAdapter.interruptTurn")(
2177 + function* (args) {
2178 const turn = active;
2179 if (
2180 !turn ||
@@ -2207,20 +2210,23 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
2210 Effect.mapError((cause) => protocolError("Muse did not confirm interruption", cause)),
2211 Effect.onError((cause) => eventPermit.withPermits(1)(failHost(cause))),
2212 );
2210 - }).pipe(
2211 - commands.withPermits(1),
2212 - Effect.mapError(
2213 - (cause) =>
2214 - new ProviderAdapter.ProviderAdapterInterruptError({
2215 - driver: MUSE_PROVIDER,
2216 - providerThreadId: args.providerThread.id,
2217 - providerTurnId: args.providerTurnId,
2218 - cause,
2219 - }),
2213 + },
2214 + (effect, args) =>
2215 + effect.pipe(
2216 + commands.withPermits(1),
2217 + Effect.mapError(
2218 + (cause) =>
2219 + new ProviderAdapter.ProviderAdapterInterruptError({
2220 + driver: MUSE_PROVIDER,
2221 + providerThreadId: args.providerThread.id,
2222 + providerTurnId: args.providerTurnId,
2223 + cause,
2224 + }),
2225 + ),
2226 ),
2221 - ),
2222 - respondToRuntimeRequest: (args) =>
2223 - Effect.gen(function* () {
2227 + ),
2228 + respondToRuntimeRequest: Effect.fn("MuseAdapter.respondToRuntimeRequest")(
2229 + function* (args) {
2230 const entry = pending.get(args.requestId);
2231 if (!entry) return yield* protocolError("This Muse request is no longer pending");
2232 if (entry.native.type === "approval") yield* decideApproval(entry, args.decision);
@@ -2261,16 +2267,19 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
2267 answers,
2268 }).pipe(Effect.tapError(() => Effect.sync(() => delete entry.response)));
2269 }
2264 - }).pipe(
2265 - Effect.mapError(
2266 - (cause) =>
2267 - new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
2268 - driver: MUSE_PROVIDER,
2269 - requestId: args.requestId,
2270 - cause,
2271 - }),
2270 + },
2271 + (effect, args) =>
2272 + effect.pipe(
2273 + Effect.mapError(
2274 + (cause) =>
2275 + new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
2276 + driver: MUSE_PROVIDER,
2277 + requestId: args.requestId,
2278 + cause,
2279 + }),
2280 + ),
2281 ),
2273 - ),
2282 + ),
2283 readThreadSnapshot: (args) =>
2284 (!validateThread(args.providerThread)
2285 ? protocolError("Snapshot requested for a different Muse thread")
packages/provider-muse/src/server/driver.ts
+131 -127
@@ -58,136 +58,140 @@ export const MuseDriver: ProviderDriver<MuseSettings, MuseDriverEnv> = {
58 metadata: { displayName: "Muse Code", supportsMultipleInstances: true },
59 configSchema: MuseSettings,
60 defaultConfig: () => decodeMuseSettings({}),
61 - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
62 - Effect.gen(function* () {
63 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
64 - const fileSystem = yield* FileSystem.FileSystem;
65 - const path = yield* Path.Path;
66 - const httpClient = yield* HttpClient.HttpClient;
67 - const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
68 - const host = yield* ProviderHost.ProviderHost;
69 - const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
70 - const { cwd } = host.paths;
71 - const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
72 - const hostEnvironment = yield* HostProcess.Environment;
73 - // Drop an inherited META_API_KEY so Muse uses its login; an instance value still wins.
74 - const processEnvironment = yield* mergeProviderInstanceEnvironment(
75 - environment,
76 - makeMuseEnvironment(hostEnvironment),
77 - );
78 - const effectiveConfig = {
79 - ...config,
80 - enabled,
81 - binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
82 - } satisfies MuseSettings;
83 - const continuationIdentity = defaultProviderContinuationIdentity({
84 - driverKind: DRIVER_KIND,
85 - instanceId,
86 - });
87 - const stampIdentity = withInstanceIdentity({
88 - instanceId,
89 - driverKind: DRIVER_KIND,
90 - displayName,
91 - accentColor,
92 - continuationGroupKey: continuationIdentity.continuationKey,
93 - });
94 - const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
95 - const resolveInstallation = yield* makeCachedProviderMaintenanceResolution(
96 - resolveProviderMaintenanceCapabilitiesEffect(museMaintenance, {
97 - binaryPath: effectiveConfig.binaryPath,
98 - env: processEnvironment,
99 - }).pipe(
100 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
101 - Effect.provideService(FileSystem.FileSystem, fileSystem),
102 - Effect.provideService(Path.Path, path),
103 - ),
104 - );
105 - const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>
106 - Effect.gen(function* () {
107 - const capabilities = yield* resolveInstallation(options);
108 - // The maintenance runner requests fresh capabilities around an explicit update
109 - // and needs the native target version to verify that the command actually upgraded.
110 - const latestVersion = options?.fresh
111 - ? yield* latestMuseVersion(processEnvironment, { fresh: true }).pipe(
112 - Effect.provideService(HttpClient.HttpClient, httpClient),
113 - Effect.provideService(
114 - ProviderLatestVersions.ProviderLatestVersions,
115 - latestVersions,
116 - ),
117 - )
118 - : undefined;
119 - return latestVersion !== undefined ? { ...capabilities, latestVersion } : capabilities;
120 - });
121 - const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<MuseSettings>>({
122 - // Status refresh respects update checks; explicit updates use the resolver below.
123 - resolveMaintenance: (options) =>
124 - host.settings.get.pipe(
125 - Effect.orDie,
126 - Effect.flatMap((settings) =>
127 - settings.enableProviderUpdateChecks
128 - ? resolveMaintenance(options)
129 - : resolveInstallation(options),
130 - ),
131 - ),
132 - getSettings: snapshotSettings.getSettings,
133 - streamSettings: snapshotSettings.streamSettings,
134 - haveSettingsChanged: haveProviderSnapshotSettingsChanged,
135 - initialSnapshot: (settings) =>
136 - makePendingMuseProvider(settings.provider).pipe(Effect.map(stampIdentity)),
137 - checkProvider: checkMuseProviderStatus(effectiveConfig, processEnvironment, cwd).pipe(
138 - Effect.map(stampIdentity),
139 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
140 - Effect.provideService(FileSystem.FileSystem, fileSystem),
141 - Effect.provideService(Path.Path, path),
142 - ),
143 - enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
144 - resolveMaintenance().pipe(
145 - Effect.flatMap((maintenanceCapabilities) =>
146 - enrichMuseSnapshot({
147 - snapshot: currentSnapshot,
148 - maintenanceCapabilities,
149 - enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
150 - environment: processEnvironment,
151 - }),
152 - ),
61 + create: Effect.fn("MuseDriver.create")(function* ({
62 + instanceId,
63 + displayName,
64 + accentColor,
65 + environment,
66 + enabled,
67 + config,
68 + }) {
69 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
70 + const fileSystem = yield* FileSystem.FileSystem;
71 + const path = yield* Path.Path;
72 + const httpClient = yield* HttpClient.HttpClient;
73 + const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
74 + const host = yield* ProviderHost.ProviderHost;
75 + const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
76 + const { cwd } = host.paths;
77 + const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
78 + const hostEnvironment = yield* HostProcess.Environment;
79 + // Drop an inherited META_API_KEY so Muse uses its login; an instance value still wins.
80 + const processEnvironment = yield* mergeProviderInstanceEnvironment(
81 + environment,
82 + makeMuseEnvironment(hostEnvironment),
83 + );
84 + const effectiveConfig = {
85 + ...config,
86 + enabled,
87 + binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
88 + } satisfies MuseSettings;
89 + const continuationIdentity = defaultProviderContinuationIdentity({
90 + driverKind: DRIVER_KIND,
91 + instanceId,
92 + });
93 + const stampIdentity = withInstanceIdentity({
94 + instanceId,
95 + driverKind: DRIVER_KIND,
96 + displayName,
97 + accentColor,
98 + continuationGroupKey: continuationIdentity.continuationKey,
99 + });
100 + const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
101 + const resolveInstallation = yield* makeCachedProviderMaintenanceResolution(
102 + resolveProviderMaintenanceCapabilitiesEffect(museMaintenance, {
103 + binaryPath: effectiveConfig.binaryPath,
104 + env: processEnvironment,
105 + }).pipe(
106 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
107 + Effect.provideService(FileSystem.FileSystem, fileSystem),
108 + Effect.provideService(Path.Path, path),
109 + ),
110 + );
111 + const resolveMaintenance = Effect.fn("MuseDriver.resolveMaintenance")(function* (options?: {
112 + readonly fresh?: boolean;
113 + }) {
114 + const capabilities = yield* resolveInstallation(options);
115 + // The maintenance runner requests fresh capabilities around an explicit update
116 + // and needs the native target version to verify that the command actually upgraded.
117 + const latestVersion = options?.fresh
118 + ? yield* latestMuseVersion(processEnvironment, { fresh: true }).pipe(
119 Effect.provideService(HttpClient.HttpClient, httpClient),
120 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
155 - Effect.flatMap(publishSnapshot),
121 + )
122 + : undefined;
123 + return latestVersion !== undefined ? { ...capabilities, latestVersion } : capabilities;
124 + });
125 + const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<MuseSettings>>({
126 + // Status refresh respects update checks; explicit updates use the resolver below.
127 + resolveMaintenance: (options) =>
128 + host.settings.get.pipe(
129 + Effect.orDie,
130 + Effect.flatMap((settings) =>
131 + settings.enableProviderUpdateChecks
132 + ? resolveMaintenance(options)
133 + : resolveInstallation(options),
134 ),
157 - }).pipe(
158 - Effect.mapError(
159 - (cause) =>
160 - new ProviderDriverError({
161 - driver: DRIVER_KIND,
162 - instanceId,
163 - detail: "Failed to build Muse Code snapshot.",
164 - cause,
135 + ),
136 + getSettings: snapshotSettings.getSettings,
137 + streamSettings: snapshotSettings.streamSettings,
138 + haveSettingsChanged: haveProviderSnapshotSettingsChanged,
139 + initialSnapshot: (settings) =>
140 + makePendingMuseProvider(settings.provider).pipe(Effect.map(stampIdentity)),
141 + checkProvider: checkMuseProviderStatus(effectiveConfig, processEnvironment, cwd).pipe(
142 + Effect.map(stampIdentity),
143 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
144 + Effect.provideService(FileSystem.FileSystem, fileSystem),
145 + Effect.provideService(Path.Path, path),
146 + ),
147 + enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
148 + resolveMaintenance().pipe(
149 + Effect.flatMap((maintenanceCapabilities) =>
150 + enrichMuseSnapshot({
151 + snapshot: currentSnapshot,
152 + maintenanceCapabilities,
153 + enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
154 + environment: processEnvironment,
155 }),
156 + ),
157 + Effect.provideService(HttpClient.HttpClient, httpClient),
158 + Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
159 + Effect.flatMap(publishSnapshot),
160 ),
167 - );
168 - const modelCatalog = snapshot.getSnapshot.pipe(Effect.map((current) => current.models));
169 - const orchestrationAdapter = yield* makeMuseAdapterV2({
170 - instanceId,
171 - settings: effectiveConfig,
172 - environment: processEnvironment,
173 - modelCatalog,
174 - ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
175 - continuationRequests,
176 - });
177 - const textGeneration = yield* makeMuseTextGeneration(effectiveConfig, {
178 - environment: processEnvironment,
179 - modelCatalog,
180 - });
181 - return {
182 - instanceId,
183 - driverKind: DRIVER_KIND,
184 - continuationIdentity,
185 - displayName,
186 - accentColor,
187 - enabled,
188 - snapshot: { ...snapshot, resolveMaintenance },
189 - orchestrationAdapter,
190 - textGeneration,
191 - } satisfies ProviderInstance;
192 - }),
161 + }).pipe(
162 + Effect.mapError(
163 + (cause) =>
164 + new ProviderDriverError({
165 + driver: DRIVER_KIND,
166 + instanceId,
167 + detail: "Failed to build Muse Code snapshot.",
168 + cause,
169 + }),
170 + ),
171 + );
172 + const modelCatalog = snapshot.getSnapshot.pipe(Effect.map((current) => current.models));
173 + const orchestrationAdapter = yield* makeMuseAdapterV2({
174 + instanceId,
175 + settings: effectiveConfig,
176 + environment: processEnvironment,
177 + modelCatalog,
178 + ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
179 + continuationRequests,
180 + });
181 + const textGeneration = yield* makeMuseTextGeneration(effectiveConfig, {
182 + environment: processEnvironment,
183 + modelCatalog,
184 + });
185 + return {
186 + instanceId,
187 + driverKind: DRIVER_KIND,
188 + continuationIdentity,
189 + displayName,
190 + accentColor,
191 + enabled,
192 + snapshot: { ...snapshot, resolveMaintenance },
193 + orchestrationAdapter,
194 + textGeneration,
195 + } satisfies ProviderInstance;
196 + }),
197 };
packages/provider-muse/src/server/maintenance.ts
+40 -41
@@ -39,47 +39,46 @@ export const compareMuseVersions = (current: string, latest: string) =>
39
40 /** Only the official launcher owns an update channel; a standalone binary cannot update itself. */
41 export const museMaintenance: ProviderMaintenanceCapabilitiesResolver = {
42 - resolve: (context) =>
43 - Effect.gen(function* () {
44 - const manual = {
45 - ...makeManualOnlyProviderMaintenanceCapabilities({ provider: DRIVER, packageName: null }),
46 - compareVersions: compareMuseVersions,
47 - };
48 - if (!context || context.platform === "win32") return manual;
49 - const fs = yield* FileSystem.FileSystem;
50 - const isLauncher = yield* Effect.gen(function* () {
51 - const stat = yield* fs.stat(context.realCommandPath);
52 - if (Number(stat.size) > 128 * 1_024) return false;
53 - const source = yield* fs.readFileString(context.realCommandPath);
54 - return source.includes("muse-code/launcher-") && source.includes("MUSE_SYNC_UPDATE");
55 - }).pipe(Effect.orElseSucceed(() => false));
56 - if (!isLauncher) return manual;
57 - // The launcher has no `update` subcommand. Its documented launch environment
58 - // forces a synchronous refresh of this executable's own installation.
59 - const updateEnv = {
60 - ...(context.env.MUSE_CHANNEL ? { MUSE_CHANNEL: context.env.MUSE_CHANNEL } : {}),
61 - MUSE_NO_AUTO_UPDATE: "0",
62 - MUSE_SYNC_UPDATE: "1",
63 - MUSE_UPDATE_INTERVAL_SECONDS: "0",
64 - };
65 - return {
66 - ...makeProviderMaintenanceCapabilities({
67 - provider: DRIVER,
68 - packageName: null,
69 - updateExecutable: context.resolvedCommandPath,
70 - updateArgs: ["--version"],
71 - updateCommand: [
72 - ...Object.entries(updateEnv).map(([key, value]) => `${key}=${shellQuote(value)}`),
73 - shellQuote(context.resolvedCommandPath),
74 - "--version",
75 - ].join(" "),
76 - updateLockKey: `muse:${context.realCommandPath}`,
77 - platform: context.platform,
78 - env: { ...context.env, ...updateEnv },
79 - }),
80 - compareVersions: compareMuseVersions,
81 - };
82 - }),
42 + resolve: Effect.fn("MuseMaintenance.resolve")(function* (context) {
43 + const manual = {
44 + ...makeManualOnlyProviderMaintenanceCapabilities({ provider: DRIVER, packageName: null }),
45 + compareVersions: compareMuseVersions,
46 + };
47 + if (!context || context.platform === "win32") return manual;
48 + const fs = yield* FileSystem.FileSystem;
49 + const isLauncher = yield* Effect.gen(function* () {
50 + const stat = yield* fs.stat(context.realCommandPath);
51 + if (Number(stat.size) > 128 * 1_024) return false;
52 + const source = yield* fs.readFileString(context.realCommandPath);
53 + return source.includes("muse-code/launcher-") && source.includes("MUSE_SYNC_UPDATE");
54 + }).pipe(Effect.orElseSucceed(() => false));
55 + if (!isLauncher) return manual;
56 + // The launcher has no `update` subcommand. Its documented launch environment
57 + // forces a synchronous refresh of this executable's own installation.
58 + const updateEnv = {
59 + ...(context.env.MUSE_CHANNEL ? { MUSE_CHANNEL: context.env.MUSE_CHANNEL } : {}),
60 + MUSE_NO_AUTO_UPDATE: "0",
61 + MUSE_SYNC_UPDATE: "1",
62 + MUSE_UPDATE_INTERVAL_SECONDS: "0",
63 + };
64 + return {
65 + ...makeProviderMaintenanceCapabilities({
66 + provider: DRIVER,
67 + packageName: null,
68 + updateExecutable: context.resolvedCommandPath,
69 + updateArgs: ["--version"],
70 + updateCommand: [
71 + ...Object.entries(updateEnv).map(([key, value]) => `${key}=${shellQuote(value)}`),
72 + shellQuote(context.resolvedCommandPath),
73 + "--version",
74 + ].join(" "),
75 + updateLockKey: `muse:${context.realCommandPath}`,
76 + platform: context.platform,
77 + env: { ...context.env, ...updateEnv },
78 + }),
79 + compareVersions: compareMuseVersions,
80 + };
81 + }),
82 };
83
84 function shellQuote(word: string) {
packages/provider-opencode/src/server/OpenCodeRuntime.ts
+305 -300
@@ -604,8 +604,10 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
604 const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
605 resolveSpawnCommand(command, args, { ...(env ? { env } : {}), bypassNpmShim: true });
606
607 - const runOpenCodeCommand: OpenCodeRuntime["Service"]["runOpenCodeCommand"] = (input) =>
608 - Effect.gen(function* () {
607 + const runOpenCodeCommand: OpenCodeRuntime["Service"]["runOpenCodeCommand"] = Effect.fn(
608 + "OpenCodeRuntime.runOpenCodeCommand",
609 + )(
610 + function* (input) {
611 const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);
612 const child = yield* spawner.spawn(
613 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
@@ -646,16 +648,19 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
648 stderr,
649 code: exitCode,
650 } satisfies OpenCodeCommandResult;
649 - }).pipe(
650 - Effect.scoped,
651 - Effect.mapError((cause) =>
652 - ensureRuntimeError(
653 - "runOpenCodeCommand",
654 - `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
655 - cause,
651 + },
652 + (effect, input) =>
653 + effect.pipe(
654 + Effect.scoped,
655 + Effect.mapError((cause) =>
656 + ensureRuntimeError(
657 + "runOpenCodeCommand",
658 + `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
659 + cause,
660 + ),
661 ),
662 ),
658 - );
663 + );
664
665 const createOpenCodeSdkClient: OpenCodeRuntime["Service"]["createOpenCodeSdkClient"] = (input) =>
666 createOpencodeClient({
@@ -671,220 +676,219 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
676 throwOnError: true,
677 });
678
674 - const startServerAttempt: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = (input) =>
675 - Effect.gen(function* () {
676 - const runtimeScope = yield* Scope.Scope;
677 -
678 - const hostname = input.hostname ?? DEFAULT_HOSTNAME;
679 - const port =
680 - input.port ??
681 - (yield* netService.findAvailablePort(0).pipe(
682 - Effect.mapError(
683 - (cause) =>
684 - new OpenCodeRuntimeError({
685 - operation: "startOpenCodeServerProcess",
686 - detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
687 - cause,
688 - }),
689 - ),
690 - ));
691 - const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
692 - const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
693 - const launch = yield* agentScope.wrap({
694 - command: input.binaryPath,
695 - args,
696 - name: "opencode",
697 - env: input.environment,
698 - });
699 - const spawnCommand = yield* resolveCommand(launch.command, launch.args, input.environment);
700 - const serverPassword = resolveOpenCodeServerPassword({
701 - external: false,
702 - ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
703 - ...(input.environment !== undefined ? { environment: input.environment } : {}),
704 - });
705 -
706 - // Scopes close in reverse order. Forking this before the group kill is
707 - // registered forgets the ledger entry only once the group is stopped.
708 - const ledgerScope = yield* Scope.fork(runtimeScope);
709 - const child = yield* spawner
710 - .spawn(
711 - ChildProcess.make(spawnCommand.command, spawnCommand.args, {
712 - detached: hostPlatform !== "win32",
713 - shell: spawnCommand.shell,
714 - env: {
715 - ...input.environment,
716 - ...(serverPassword !== undefined ? { OPENCODE_SERVER_PASSWORD: serverPassword } : {}),
717 - // The value is set explicitly (rather than relying on inheritance) because
718 - // `extendEnv` is false whenever `input.environment` is provided.
719 - OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment),
720 - },
721 - extendEnv: input.environment === undefined,
722 - }),
723 - )
724 - .pipe(
725 - Effect.provideService(Scope.Scope, runtimeScope),
726 - Effect.mapError(
727 - (cause) =>
728 - new OpenCodeRuntimeError({
729 - operation: "startOpenCodeServerProcess",
730 - detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
731 - cause,
732 - }),
733 - ),
734 - );
735 -
736 - const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
737 - hostPlatform === "win32"
738 - ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
739 - : Effect.sync(() => {
740 - try {
741 - signalProcessGroup(Number(child.pid), signal);
742 - } catch {}
743 - });
744 - const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
745 - Effect.andThen(Effect.sleep("1 second")),
746 - Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
747 - Effect.ignore,
748 - );
749 - // Registered before recording, so an interrupt while the ledger writes
750 - // still stops the group.
751 - yield* Scope.addFinalizer(runtimeScope, terminateChild);
752 - const forgetServer = yield* serverLedger.track({ pid: Number(child.pid), port, args });
753 - yield* Scope.addFinalizer(ledgerScope, forgetServer);
754 -
755 - const stdoutRef = yield* Ref.make<string | null>("");
756 - const stderrRef = yield* Ref.make<string | null>("");
757 - const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
758 -
759 - const setReadyFromStdoutChunk = (chunk: string) =>
760 - Ref.modify(stdoutRef, (stdout) => {
761 - if (stdout === null) {
762 - return [null, null] as const;
763 - }
764 - const nextStdout = `${stdout}${chunk}`;
765 - return [
766 - parseServerUrlFromOutput(nextStdout),
767 - nextStdout.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
768 - ] as const;
769 - }).pipe(
770 - Effect.flatMap((parsed) =>
771 - parsed ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore) : Effect.void,
772 - ),
773 - );
679 + const startServerAttempt: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = Effect.fn(
680 + "OpenCodeRuntime.startServerAttempt",
681 + )(function* (input) {
682 + const runtimeScope = yield* Scope.Scope;
683 +
684 + const hostname = input.hostname ?? DEFAULT_HOSTNAME;
685 + const port =
686 + input.port ??
687 + (yield* netService.findAvailablePort(0).pipe(
688 + Effect.mapError(
689 + (cause) =>
690 + new OpenCodeRuntimeError({
691 + operation: "startOpenCodeServerProcess",
692 + detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
693 + cause,
694 + }),
695 + ),
696 + ));
697 + const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
698 + const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
699 + const launch = yield* agentScope.wrap({
700 + command: input.binaryPath,
701 + args,
702 + name: "opencode",
703 + env: input.environment,
704 + });
705 + const spawnCommand = yield* resolveCommand(launch.command, launch.args, input.environment);
706 + const serverPassword = resolveOpenCodeServerPassword({
707 + external: false,
708 + ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
709 + ...(input.environment !== undefined ? { environment: input.environment } : {}),
710 + });
711
775 - const stdoutFiber = yield* child.stdout.pipe(
776 - Stream.decodeText(),
777 - Stream.runForEach(setReadyFromStdoutChunk),
778 - Effect.ignore,
779 - Effect.forkIn(runtimeScope),
780 - );
781 - const stderrFiber = yield* child.stderr.pipe(
782 - Stream.decodeText(),
783 - Stream.runForEach((chunk) =>
784 - Ref.update(stderrRef, (stderr) =>
785 - stderr === null
786 - ? null
787 - : `${stderr}${chunk}`.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
788 - ),
712 + // Scopes close in reverse order. Forking this before the group kill is
713 + // registered forgets the ledger entry only once the group is stopped.
714 + const ledgerScope = yield* Scope.fork(runtimeScope);
715 + const child = yield* spawner
716 + .spawn(
717 + ChildProcess.make(spawnCommand.command, spawnCommand.args, {
718 + detached: hostPlatform !== "win32",
719 + shell: spawnCommand.shell,
720 + env: {
721 + ...input.environment,
722 + ...(serverPassword !== undefined ? { OPENCODE_SERVER_PASSWORD: serverPassword } : {}),
723 + // The value is set explicitly (rather than relying on inheritance) because
724 + // `extendEnv` is false whenever `input.environment` is provided.
725 + OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment),
726 + },
727 + extendEnv: input.environment === undefined,
728 + }),
729 + )
730 + .pipe(
731 + Effect.provideService(Scope.Scope, runtimeScope),
732 + Effect.mapError(
733 + (cause) =>
734 + new OpenCodeRuntimeError({
735 + operation: "startOpenCodeServerProcess",
736 + detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
737 + cause,
738 + }),
739 ),
790 - Effect.ignore,
791 - Effect.forkIn(runtimeScope),
740 );
741
794 - const exitFiber = yield* child.exitCode.pipe(
795 - Effect.flatMap((code) =>
796 - Effect.gen(function* () {
797 - // Allow trailing diagnostics to drain, but descendants can keep pipes open.
798 - const drained = yield* Fiber.joinAll([stdoutFiber, stderrFiber]).pipe(
799 - Effect.timeoutOption(OPENCODE_SERVER_EXIT_DRAIN_TIMEOUT),
800 - );
801 - if (Option.isNone(drained)) {
802 - yield* Fiber.interruptAll([stdoutFiber, stderrFiber]);
803 - }
804 - const stdout = (yield* Ref.get(stdoutRef)) ?? "";
805 - const stderr = (yield* Ref.get(stderrRef)) ?? "";
806 - const exitCode = Number(code);
807 - const reason = classifyStartupExit(stderr);
808 - yield* Deferred.fail(
809 - readyDeferred,
810 - new OpenCodeRuntimeError({
811 - operation: "startOpenCodeServerProcess",
812 - ...(reason ? { reason } : {}),
813 - detail: [
814 - `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
815 - stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
816 - stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
817 - ]
818 - .filter(Boolean)
819 - .join("\n\n"),
820 - cause: { exitCode, stdout, stderr },
821 - }),
822 - ).pipe(Effect.ignore);
823 - }),
742 + const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
743 + hostPlatform === "win32"
744 + ? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
745 + : Effect.sync(() => {
746 + try {
747 + signalProcessGroup(Number(child.pid), signal);
748 + } catch {}
749 + });
750 + const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
751 + Effect.andThen(Effect.sleep("1 second")),
752 + Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
753 + Effect.ignore,
754 + );
755 + // Registered before recording, so an interrupt while the ledger writes
756 + // still stops the group.
757 + yield* Scope.addFinalizer(runtimeScope, terminateChild);
758 + const forgetServer = yield* serverLedger.track({ pid: Number(child.pid), port, args });
759 + yield* Scope.addFinalizer(ledgerScope, forgetServer);
760 +
761 + const stdoutRef = yield* Ref.make<string | null>("");
762 + const stderrRef = yield* Ref.make<string | null>("");
763 + const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
764 +
765 + const setReadyFromStdoutChunk = (chunk: string) =>
766 + Ref.modify(stdoutRef, (stdout) => {
767 + if (stdout === null) {
768 + return [null, null] as const;
769 + }
770 + const nextStdout = `${stdout}${chunk}`;
771 + return [
772 + parseServerUrlFromOutput(nextStdout),
773 + nextStdout.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
774 + ] as const;
775 + }).pipe(
776 + Effect.flatMap((parsed) =>
777 + parsed ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore) : Effect.void,
778 ),
825 - Effect.ignore,
826 - Effect.forkIn(runtimeScope),
779 );
780
829 - const readyExit = yield* Effect.exit(
830 - Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
831 - );
781 + const stdoutFiber = yield* child.stdout.pipe(
782 + Stream.decodeText(),
783 + Stream.runForEach(setReadyFromStdoutChunk),
784 + Effect.ignore,
785 + Effect.forkIn(runtimeScope),
786 + );
787 + const stderrFiber = yield* child.stderr.pipe(
788 + Stream.decodeText(),
789 + Stream.runForEach((chunk) =>
790 + Ref.update(stderrRef, (stderr) =>
791 + stderr === null
792 + ? null
793 + : `${stderr}${chunk}`.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS),
794 + ),
795 + ),
796 + Effect.ignore,
797 + Effect.forkIn(runtimeScope),
798 + );
799
833 - if (Exit.isFailure(readyExit) || Option.isNone(readyExit.value)) {
834 - yield* Fiber.interruptAll([stdoutFiber, stderrFiber, exitFiber]).pipe(Effect.ignore);
835 - }
800 + const exitFiber = yield* child.exitCode.pipe(
801 + Effect.flatMap((code) =>
802 + Effect.gen(function* () {
803 + // Allow trailing diagnostics to drain, but descendants can keep pipes open.
804 + const drained = yield* Fiber.joinAll([stdoutFiber, stderrFiber]).pipe(
805 + Effect.timeoutOption(OPENCODE_SERVER_EXIT_DRAIN_TIMEOUT),
806 + );
807 + if (Option.isNone(drained)) {
808 + yield* Fiber.interruptAll([stdoutFiber, stderrFiber]);
809 + }
810 + const stdout = (yield* Ref.get(stdoutRef)) ?? "";
811 + const stderr = (yield* Ref.get(stderrRef)) ?? "";
812 + const exitCode = Number(code);
813 + const reason = classifyStartupExit(stderr);
814 + yield* Deferred.fail(
815 + readyDeferred,
816 + new OpenCodeRuntimeError({
817 + operation: "startOpenCodeServerProcess",
818 + ...(reason ? { reason } : {}),
819 + detail: [
820 + `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
821 + stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
822 + stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
823 + ]
824 + .filter(Boolean)
825 + .join("\n\n"),
826 + cause: { exitCode, stdout, stderr },
827 + }),
828 + ).pipe(Effect.ignore);
829 + }),
830 + ),
831 + Effect.ignore,
832 + Effect.forkIn(runtimeScope),
833 + );
834
837 - if (Exit.isFailure(readyExit)) {
838 - const squashed = Cause.squash(readyExit.cause);
839 - return yield* ensureRuntimeError(
840 - "startOpenCodeServerProcess",
841 - `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
842 - squashed,
843 - );
844 - }
835 + const readyExit = yield* Effect.exit(
836 + Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
837 + );
838
846 - const readyOption = readyExit.value;
847 - if (Option.isNone(readyOption)) {
848 - return yield* new OpenCodeRuntimeError({
849 - operation: "startOpenCodeServerProcess",
850 - detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
851 - });
852 - }
839 + if (Exit.isFailure(readyExit) || Option.isNone(readyExit.value)) {
840 + yield* Fiber.interruptAll([stdoutFiber, stderrFiber, exitFiber]).pipe(Effect.ignore);
841 + }
842
854 - // Keep draining both pipes until the process scope closes. Stopping the
855 - // readers can block OpenCode when its output buffers fill. Startup output
856 - // is no longer needed, so discard later output instead of retaining it.
857 - yield* Ref.set(stdoutRef, null);
858 - yield* Ref.set(stderrRef, null);
859 -
860 - const url = readyOption.value;
861 - const version = yield* (
862 - input.verify?.(url) ??
863 - verifyOpenCodeServerVersion(
864 - createOpenCodeSdkClient({
865 - baseUrl: url,
866 - directory: input.directory,
867 - ...(serverPassword !== undefined ? { serverPassword } : {}),
868 - }),
869 - )
843 + if (Exit.isFailure(readyExit)) {
844 + const squashed = Cause.squash(readyExit.cause);
845 + return yield* ensureRuntimeError(
846 + "startOpenCodeServerProcess",
847 + `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
848 + squashed,
849 );
850 + }
851
872 - return {
873 - url,
874 - ...(serverPassword !== undefined ? { serverPassword } : {}),
875 - version,
876 - isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)),
877 - exitCode: child.exitCode.pipe(
878 - Effect.map(Number),
879 - Effect.orElseSucceed(() => 0),
880 - ),
881 - } satisfies OpenCodeServerProcess;
882 - });
852 + const readyOption = readyExit.value;
853 + if (Option.isNone(readyOption)) {
854 + return yield* new OpenCodeRuntimeError({
855 + operation: "startOpenCodeServerProcess",
856 + detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
857 + });
858 + }
859
884 - const startOpenCodeServerProcess: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = (
885 - input,
886 - ) =>
887 - Effect.gen(function* () {
860 + // Keep draining both pipes until the process scope closes. Stopping the
861 + // readers can block OpenCode when its output buffers fill. Startup output
862 + // is no longer needed, so discard later output instead of retaining it.
863 + yield* Ref.set(stdoutRef, null);
864 + yield* Ref.set(stderrRef, null);
865 +
866 + const url = readyOption.value;
867 + const version = yield* (
868 + input.verify?.(url) ??
869 + verifyOpenCodeServerVersion(
870 + createOpenCodeSdkClient({
871 + baseUrl: url,
872 + directory: input.directory,
873 + ...(serverPassword !== undefined ? { serverPassword } : {}),
874 + }),
875 + )
876 + );
877 +
878 + return {
879 + url,
880 + ...(serverPassword !== undefined ? { serverPassword } : {}),
881 + version,
882 + isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)),
883 + exitCode: child.exitCode.pipe(
884 + Effect.map(Number),
885 + Effect.orElseSucceed(() => 0),
886 + ),
887 + } satisfies OpenCodeServerProcess;
888 + });
889 +
890 + const startOpenCodeServerProcess: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] =
891 + Effect.fn("OpenCodeRuntime.startOpenCodeServerProcess")(function* (input) {
892 const ownerScope = yield* Scope.Scope;
893 const attempt = Effect.gen(function* () {
894 const attemptScope = yield* Scope.fork(ownerScope);
@@ -1006,102 +1010,103 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
1010 })),
1011 );
1012
1009 - const loadInventoryFromCli: OpenCodeRuntime["Service"]["loadInventoryFromCli"] = (input) =>
1010 - Effect.gen(function* () {
1011 - const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});
1012 - const commandContext = { cwd: input.cwd, ...env };
1013 -
1014 - const runModelsCli = () =>
1015 - runOpenCodeCommand({
1016 - binaryPath: input.binaryPath,
1017 - args: ["models", "--verbose"],
1018 - ...commandContext,
1019 - }).pipe(Effect.exit);
1020 - const runAgentsCli = () =>
1021 - runOpenCodeCommand({
1022 - binaryPath: input.binaryPath,
1023 - args: ["agent", "list"],
1024 - ...commandContext,
1025 - }).pipe(Effect.exit);
1026 - const runSkillsCli = () =>
1027 - runOpenCodeCommand({
1028 - binaryPath: input.binaryPath,
1029 - args: ["debug", "skill"],
1030 - maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
1031 - ...commandContext,
1032 - }).pipe(Effect.exit);
1033 -
1034 - // Every OpenCode CLI command opens the same shared SQLite database. Running them
1035 - // concurrently causes "database is locked" failures, so run them one at a time.
1036 - const [initialModelsResult, initialAgentsResult, initialSkillsResult] = yield* Effect.all(
1037 - [runModelsCli(), runAgentsCli(), runSkillsCli()],
1013 + const loadInventoryFromCli: OpenCodeRuntime["Service"]["loadInventoryFromCli"] = Effect.fn(
1014 + "OpenCodeRuntime.loadInventoryFromCli",
1015 + )(function* (input) {
1016 + const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});
1017 + const commandContext = { cwd: input.cwd, ...env };
1018 +
1019 + const runModelsCli = () =>
1020 + runOpenCodeCommand({
1021 + binaryPath: input.binaryPath,
1022 + args: ["models", "--verbose"],
1023 + ...commandContext,
1024 + }).pipe(Effect.exit);
1025 + const runAgentsCli = () =>
1026 + runOpenCodeCommand({
1027 + binaryPath: input.binaryPath,
1028 + args: ["agent", "list"],
1029 + ...commandContext,
1030 + }).pipe(Effect.exit);
1031 + const runSkillsCli = () =>
1032 + runOpenCodeCommand({
1033 + binaryPath: input.binaryPath,
1034 + args: ["debug", "skill"],
1035 + maxOutputBytes: OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES,
1036 + ...commandContext,
1037 + }).pipe(Effect.exit);
1038 +
1039 + // Every OpenCode CLI command opens the same shared SQLite database. Running them
1040 + // concurrently causes "database is locked" failures, so run them one at a time.
1041 + const [initialModelsResult, initialAgentsResult, initialSkillsResult] = yield* Effect.all(
1042 + [runModelsCli(), runAgentsCli(), runSkillsCli()],
1043 + { concurrency: 1 },
1044 + );
1045 + let modelsResult = initialModelsResult;
1046 + let agentsResult = initialAgentsResult;
1047 + let skillsResult = initialSkillsResult;
1048 +
1049 + const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;
1050 + const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;
1051 + const needsSkillsRetry = skillsResult._tag === "Failure" || skillsResult.value.code !== 0;
1052 + if (needsModelsRetry || needsAgentsRetry || needsSkillsRetry) {
1053 + yield* Effect.sleep("1 second");
1054 + const [m2, a2, s2] = yield* Effect.all(
1055 + [
1056 + needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),
1057 + needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),
1058 + needsSkillsRetry ? runSkillsCli() : Effect.succeed(skillsResult),
1059 + ],
1060 { concurrency: 1 },
1061 );
1040 - let modelsResult = initialModelsResult;
1041 - let agentsResult = initialAgentsResult;
1042 - let skillsResult = initialSkillsResult;
1043 -
1044 - const needsModelsRetry = modelsResult._tag === "Failure" || modelsResult.value.code !== 0;
1045 - const needsAgentsRetry = agentsResult._tag === "Failure" || agentsResult.value.code !== 0;
1046 - const needsSkillsRetry = skillsResult._tag === "Failure" || skillsResult.value.code !== 0;
1047 - if (needsModelsRetry || needsAgentsRetry || needsSkillsRetry) {
1048 - yield* Effect.sleep("1 second");
1049 - const [m2, a2, s2] = yield* Effect.all(
1050 - [
1051 - needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),
1052 - needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),
1053 - needsSkillsRetry ? runSkillsCli() : Effect.succeed(skillsResult),
1054 - ],
1055 - { concurrency: 1 },
1056 - );
1057 - modelsResult = m2;
1058 - agentsResult = a2;
1059 - skillsResult = s2;
1060 - }
1061 -
1062 - if (modelsResult._tag === "Failure") {
1063 - const cause = Cause.squash(modelsResult.cause);
1064 - return yield* ensureRuntimeError(
1065 - "loadInventoryFromCli",
1066 - `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
1067 - cause,
1068 - );
1069 - }
1070 - if (modelsResult.value.code !== 0) {
1071 - return yield* new OpenCodeRuntimeError({
1072 - operation: "loadInventoryFromCli",
1073 - detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
1074 - });
1075 - }
1062 + modelsResult = m2;
1063 + agentsResult = a2;
1064 + skillsResult = s2;
1065 + }
1066
1077 - const parsed = parseModelsCliOutput(modelsResult.value.stdout);
1078 - const connected = [...parsed.connected];
1079 - const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
1080 - (provider) => ({
1081 - id: provider.id,
1082 - name: provider.name,
1083 - source: "config" as const,
1084 - env: [],
1085 - options: {},
1086 - models: provider.models,
1087 - }),
1067 + if (modelsResult._tag === "Failure") {
1068 + const cause = Cause.squash(modelsResult.cause);
1069 + return yield* ensureRuntimeError(
1070 + "loadInventoryFromCli",
1071 + `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,
1072 + cause,
1073 );
1074 + }
1075 + if (modelsResult.value.code !== 0) {
1076 + return yield* new OpenCodeRuntimeError({
1077 + operation: "loadInventoryFromCli",
1078 + detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,
1079 + });
1080 + }
1081
1090 - let agents: ReadonlyArray<Agent> = [];
1091 - if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
1092 - agents = parseAgentListCliOutput(agentsResult.value.stdout);
1093 - }
1094 - let skills: ReadonlyArray<OpenCodeSkill> = [];
1095 - if (skillsResult._tag === "Success" && skillsResult.value.code === 0) {
1096 - skills = parseSkillsCliOutput(skillsResult.value.stdout);
1097 - }
1082 + const parsed = parseModelsCliOutput(modelsResult.value.stdout);
1083 + const connected = [...parsed.connected];
1084 + const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map(
1085 + (provider) => ({
1086 + id: provider.id,
1087 + name: provider.name,
1088 + source: "config" as const,
1089 + env: [],
1090 + options: {},
1091 + models: provider.models,
1092 + }),
1093 + );
1094
1099 - return {
1100 - providerList: { all: allProviders, default: {}, connected },
1101 - agents,
1102 - skills,
1103 - };
1104 - });
1095 + let agents: ReadonlyArray<Agent> = [];
1096 + if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
1097 + agents = parseAgentListCliOutput(agentsResult.value.stdout);
1098 + }
1099 + let skills: ReadonlyArray<OpenCodeSkill> = [];
1100 + if (skillsResult._tag === "Success" && skillsResult.value.code === 0) {
1101 + skills = parseSkillsCliOutput(skillsResult.value.stdout);
1102 + }
1103 +
1104 + return {
1105 + providerList: { all: allProviders, default: {}, connected },
1106 + agents,
1107 + skills,
1108 + };
1109 + });
1110
1111 const loadSkillsFromCli: OpenCodeRuntime["Service"]["loadSkillsFromCli"] = (input) =>
1112 runOpenCodeCommand({
packages/provider-opencode/src/server/OpenCodeServerLedger.ts
+60 -56
@@ -99,26 +99,26 @@ export const make = Effect.fn("OpenCodeServerLedger.make")(function* (input: {
99 const directory = path.join(input.stateDir, ENTRY_DIRECTORY);
100 const recordable = platform === "linux" || platform === "darwin";
101
102 - const observeLinux = (pid: number, group?: number) =>
103 - Effect.gen(function* () {
104 - const stat = yield* fs.readFileString(`/proc/${pid}/stat`);
105 - const fields = stat
106 - .slice(stat.lastIndexOf(")") + 2)
107 - .trim()
108 - .split(/\s+/);
109 - const pgid = Number(fields[2]);
110 - const startTime = fields[19];
111 - if (!Number.isSafeInteger(pgid) || startTime === undefined) return undefined;
112 - if (group !== undefined && pgid !== group) return undefined;
113 - const cmdline = yield* fs.readFileString(`/proc/${pid}/cmdline`);
114 - return {
115 - pid,
116 - pgid,
117 - startTime,
118 - command: cmdline.replace(/\0$/, "").replaceAll("\0", " "),
119 - zombie: fields[0] === "Z",
120 - } satisfies ObservedProcess;
121 - });
102 + // A process-group scan calls this for every /proc entry; avoid a span per process.
103 + const observeLinux = Effect.fnUntraced(function* (pid: number, group?: number) {
104 + const stat = yield* fs.readFileString(`/proc/${pid}/stat`);
105 + const fields = stat
106 + .slice(stat.lastIndexOf(")") + 2)
107 + .trim()
108 + .split(/\s+/);
109 + const pgid = Number(fields[2]);
110 + const startTime = fields[19];
111 + if (!Number.isSafeInteger(pgid) || startTime === undefined) return undefined;
112 + if (group !== undefined && pgid !== group) return undefined;
113 + const cmdline = yield* fs.readFileString(`/proc/${pid}/cmdline`);
114 + return {
115 + pid,
116 + pgid,
117 + startTime,
118 + command: cmdline.replace(/\0$/, "").replaceAll("\0", " "),
119 + zombie: fields[0] === "Z",
120 + } satisfies ObservedProcess;
121 + });
122
123 const psDarwin = (selection: ReadonlyArray<string>) =>
124 spawner
@@ -183,8 +183,8 @@ export const make = Effect.fn("OpenCodeServerLedger.make")(function* (input: {
183 const owner =
184 ownerProcess === undefined ? undefined : { pid: ownerPid, startTime: ownerProcess.startTime };
185
186 - const track: OpenCodeServerLedger["Service"]["track"] = (server) =>
187 - Effect.gen(function* () {
186 + const track: OpenCodeServerLedger["Service"]["track"] = Effect.fn("OpenCodeServerLedger.track")(
187 + function* (server) {
188 if (!recordable) return Effect.void;
189 const pgid = server.pid;
190 // 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: {
232 Effect.logWarning("Could not forget a stopped OpenCode server", { cause }),
233 ),
234 );
235 - }).pipe(
236 - Effect.catchCause((cause) =>
237 - Effect.logWarning("Could not record an OpenCode server process", { cause }).pipe(
238 - Effect.as(Effect.void),
239 - ),
235 + },
236 + Effect.catchCause((cause) =>
237 + Effect.logWarning("Could not record an OpenCode server process", { cause }).pipe(
238 + Effect.as(Effect.void),
239 ),
241 - );
240 + ),
241 + );
242
243 // Signals only a group whose recorded member still has the same pid, start
244 // time, group, and full command line, so a recycled pid is never touched.
245 - const stopOrphan = (entry: OpenCodeServerEntry) =>
246 - Effect.gen(function* () {
247 - const observed = yield* observe(entry.pid);
248 - if (
249 - observed === undefined ||
250 - observed.zombie ||
251 - observed.startTime !== entry.startTime ||
252 - observed.pgid !== entry.pgid ||
253 - observed.command !== entry.command
254 - ) {
255 - return;
256 - }
257 - yield* Effect.logInfo("Stopping an OpenCode server left by a previous T3 Code server", {
258 - pid: entry.pgid,
259 - port: entry.port,
260 - });
261 - signalGroup(entry.pgid, "SIGTERM");
262 - for (let attempt = 0; attempt < STOP_POLL_ATTEMPTS && groupExists(entry.pgid); attempt++) {
263 - yield* Effect.sleep(STOP_POLL_INTERVAL);
264 - }
265 - // The group never emptied, so its pgid cannot have been reused.
266 - if (groupExists(entry.pgid)) signalGroup(entry.pgid, "SIGKILL");
245 + const stopOrphan = Effect.fn("OpenCodeServerLedger.stopOrphan")(function* (
246 + entry: OpenCodeServerEntry,
247 + ) {
248 + const observed = yield* observe(entry.pid);
249 + if (
250 + observed === undefined ||
251 + observed.zombie ||
252 + observed.startTime !== entry.startTime ||
253 + observed.pgid !== entry.pgid ||
254 + observed.command !== entry.command
255 + ) {
256 + return;
257 + }
258 + yield* Effect.logInfo("Stopping an OpenCode server left by a previous T3 Code server", {
259 + pid: entry.pgid,
260 + port: entry.port,
261 });
262 + signalGroup(entry.pgid, "SIGTERM");
263 + for (let attempt = 0; attempt < STOP_POLL_ATTEMPTS && groupExists(entry.pgid); attempt++) {
264 + yield* Effect.sleep(STOP_POLL_INTERVAL);
265 + }
266 + // The group never emptied, so its pgid cannot have been reused.
267 + if (groupExists(entry.pgid)) signalGroup(entry.pgid, "SIGKILL");
268 + });
269
269 - const reapEntry = (entryPath: string) =>
270 - Effect.gen(function* () {
270 + const reapEntry = Effect.fn("OpenCodeServerLedger.reapEntry")(
271 + function* (entryPath: string) {
272 const entry = decodeEntry(yield* fs.readFileString(entryPath));
273 if (Option.isSome(entry) && entry.value.stateDir === input.stateDir) {
274 if (yield* isRunning(entry.value.owner)) return;
275 yield* stopOrphan(entry.value);
276 }
277 yield* fs.remove(entryPath, { force: true });
277 - }).pipe(
278 - Effect.catchCause((cause) =>
279 - Effect.logWarning("Could not clean up a recorded OpenCode server", { entryPath, cause }),
278 + },
279 + (effect, entryPath) =>
280 + effect.pipe(
281 + Effect.catchCause((cause) =>
282 + Effect.logWarning("Could not clean up a recorded OpenCode server", { entryPath, cause }),
283 + ),
284 ),
281 - );
285 + );
286
287 const reapOrphans = Effect.gen(function* () {
288 const names = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
packages/provider-opencode/src/server/adapter.ts
+169 -145
@@ -1047,56 +1047,55 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
1047 ),
1048 );
1049
1050 - const abortDescendants = (rootId: string) =>
1051 - Effect.gen(function* () {
1052 - const visited = new Set([rootId]);
1053 - const semaphore = Semaphore.makeUnsafe(8);
1054 - const visit = (
1055 - sessionId: string,
1056 - abort: boolean,
1057 - ): Effect.Effect<OpenCodeRuntime.OpenCodeRuntimeError | undefined> =>
1058 - Effect.gen(function* () {
1059 - const abortResult = abort
1060 - ? yield* sdkCall("session.abort", { sessionID: sessionId }, (signal) =>
1061 - client.session.abort({ sessionID: sessionId }, { signal }),
1062 - ).pipe(
1063 - semaphore.withPermit,
1064 - Effect.catchIf(isOpenCodeNotFound, () => Effect.void),
1065 - Effect.result,
1066 - )
1067 - : undefined;
1068 - const childrenResult = yield* sdkCall(
1069 - "session.children",
1070 - { sessionID: sessionId },
1071 - (signal) => client.session.children({ sessionID: sessionId }, { signal }),
1050 + const abortDescendants = Effect.fn("OpencodeAdapter.abortDescendants")(function* (
1051 + rootId: string,
1052 + ) {
1053 + const visited = new Set([rootId]);
1054 + const semaphore = Semaphore.makeUnsafe(8);
1055 + const visit = Effect.fn("OpencodeAdapter.visit")(function* (
1056 + sessionId: string,
1057 + abort: boolean,
1058 + ): Effect.fn.Return<OpenCodeRuntime.OpenCodeRuntimeError | undefined> {
1059 + const abortResult = abort
1060 + ? yield* sdkCall("session.abort", { sessionID: sessionId }, (signal) =>
1061 + client.session.abort({ sessionID: sessionId }, { signal }),
1062 ).pipe(
1063 semaphore.withPermit,
1064 Effect.catchIf(isOpenCodeNotFound, () => Effect.void),
1065 Effect.result,
1076 - );
1077 - const firstFailure =
1078 - abortResult?._tag === "Failure" ? abortResult.failure : undefined;
1079 - if (childrenResult._tag === "Failure")
1080 - return firstFailure ?? childrenResult.failure;
1081 - const fresh = (childrenResult.success?.data ?? []).filter((child) => {
1082 - if (visited.has(child.id)) return false;
1083 - visited.add(child.id);
1084 - return true;
1085 - });
1086 - const failures = yield* Effect.forEach(fresh, (child) => visit(child.id, true), {
1087 - concurrency: 8,
1088 - });
1089 - return firstFailure ?? failures.find((failure) => failure !== undefined);
1090 - });
1091 - const failure = yield* visit(rootId, false);
1092 - if (failure) return yield* Effect.fail(failure);
1093 - }).pipe(Effect.timeout("15 seconds"));
1094 -
1095 - const updateProviderSession = (
1096 - status: OrchestrationV2ProviderSession["status"],
1097 - lastError: string | null = sessionEntity.lastError,
1098 - ) =>
1099 - Effect.gen(function* () {
1066 + )
1067 + : undefined;
1068 + const childrenResult = yield* sdkCall(
1069 + "session.children",
1070 + { sessionID: sessionId },
1071 + (signal) => client.session.children({ sessionID: sessionId }, { signal }),
1072 + ).pipe(
1073 + semaphore.withPermit,
1074 + Effect.catchIf(isOpenCodeNotFound, () => Effect.void),
1075 + Effect.result,
1076 + );
1077 + const firstFailure = abortResult?._tag === "Failure" ? abortResult.failure : undefined;
1078 + if (childrenResult._tag === "Failure") return firstFailure ?? childrenResult.failure;
1079 + const fresh = (childrenResult.success?.data ?? []).filter((child) => {
1080 + if (visited.has(child.id)) return false;
1081 + visited.add(child.id);
1082 + return true;
1083 + });
1084 + const failures = yield* Effect.forEach(fresh, (child) => visit(child.id, true), {
1085 + concurrency: 8,
1086 + });
1087 + return firstFailure ?? failures.find((failure) => failure !== undefined);
1088 + });
1089 + const failure = yield* visit(rootId, false);
1090 + if (failure) return yield* Effect.fail(failure);
1091 + }, Effect.timeout("15 seconds"));
1092 +
1093 + const updateProviderSession =
1094 + /* Provider events include streaming deltas; avoid a span for each update. */
1095 + Effect.fnUntraced(function* (
1096 + status: OrchestrationV2ProviderSession["status"],
1097 + lastError: string | null = sessionEntity.lastError,
1098 + ) {
1099 const updatedAt = yield* DateTime.now;
1100 sessionEntity = { ...sessionEntity, status, lastError, updatedAt };
1101 yield* emitProviderEvent({
@@ -1106,11 +1105,12 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
1105 });
1106 });
1107
1109 - const updateProviderThread = (
1110 - state: OpenCodeThreadState,
1111 - patch: Partial<OrchestrationV2ProviderThread>,
1112 - ) =>
1113 - Effect.gen(function* () {
1108 + const updateProviderThread =
1109 + /* Provider events include streaming deltas; avoid a span for each update. */
1110 + Effect.fnUntraced(function* (
1111 + state: OpenCodeThreadState,
1112 + patch: Partial<OrchestrationV2ProviderThread>,
1113 + ) {
1114 const updatedAt = yield* DateTime.now;
1115 state.providerThread = { ...state.providerThread, ...patch, updatedAt };
1116 yield* emitProviderEvent({
@@ -2998,8 +2998,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2998 providerSession: sessionEntity,
2999 events: Stream.fromEffectRepeat(Queue.take(events)),
3000 hasPendingBackgroundWork: Effect.sync(() => busySessionIds.size > 0),
3001 - ensureThread: (threadInput) =>
3002 - Effect.gen(function* () {
3001 + ensureThread: Effect.fn("OpencodeAdapter.ensureThread")(
3002 + function* (threadInput) {
3003 if (threadInput.existingProviderThread?.nativeThreadRef != null) {
3004 return yield* runtimeSession.resumeThread({
3005 providerThread: threadInput.existingProviderThread,
@@ -3039,18 +3039,21 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3039 };
3040 registerThread(nativeSession, providerThread, null);
3041 return providerThread;
3042 - }).pipe(
3043 - Effect.mapError(
3044 - (cause) =>
3045 - new ProviderAdapter.ProviderAdapterEnsureThreadError({
3046 - driver: OPENCODE_PROVIDER,
3047 - threadId: threadInput.threadId,
3048 - cause,
3049 - }),
3042 + },
3043 + (effect, threadInput) =>
3044 + effect.pipe(
3045 + Effect.mapError(
3046 + (cause) =>
3047 + new ProviderAdapter.ProviderAdapterEnsureThreadError({
3048 + driver: OPENCODE_PROVIDER,
3049 + threadId: threadInput.threadId,
3050 + cause,
3051 + }),
3052 + ),
3053 ),
3051 - ),
3052 - resumeThread: (threadInput) =>
3053 - Effect.gen(function* () {
3054 + ),
3055 + resumeThread: Effect.fn("OpencodeAdapter.resumeThread")(
3056 + function* (threadInput) {
3057 const sessionId = nativeThreadId(threadInput.providerThread);
3058 const response = yield* sdkCall("session.get", { sessionID: sessionId }, () =>
3059 client.session.get({ sessionID: sessionId }),
@@ -3065,24 +3068,27 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3068 };
3069 registerThread(nativeSession, providerThread, null);
3070 return providerThread;
3068 - }).pipe(
3069 - Effect.mapError(
3070 - (cause) =>
3071 - new ProviderAdapter.ProviderAdapterResumeThreadError({
3072 - driver: OPENCODE_PROVIDER,
3073 - providerSessionId: input.providerSessionId,
3074 - providerThreadId: threadInput.providerThread.id,
3075 - cause,
3076 - }),
3071 + },
3072 + (effect, threadInput) =>
3073 + effect.pipe(
3074 + Effect.mapError(
3075 + (cause) =>
3076 + new ProviderAdapter.ProviderAdapterResumeThreadError({
3077 + driver: OPENCODE_PROVIDER,
3078 + providerSessionId: input.providerSessionId,
3079 + providerThreadId: threadInput.providerThread.id,
3080 + cause,
3081 + }),
3082 + ),
3083 ),
3078 - ),
3084 + ),
3085 compactThread: (turnInput) =>
3086 runtimeSession.startTurn({
3087 ...turnInput,
3088 message: { ...turnInput.message, text: "/compact" },
3089 }),
3084 - startTurn: (turnInput) =>
3085 - Effect.gen(function* () {
3090 + startTurn: Effect.fn("OpencodeAdapter.startTurn")(
3091 + function* (turnInput) {
3092 if (nativeStreamFailure !== null) {
3093 return yield* protocolError(
3094 "OpenCode event stream has ended; reconnect the provider session before starting another turn.",
@@ -3279,20 +3285,23 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3285 yield* reconcilePromptAdmission(state, turn);
3286 }
3287 }
3282 - }).pipe(
3283 - Effect.mapError(
3284 - (cause) =>
3285 - new ProviderAdapter.ProviderAdapterTurnStartError({
3286 - driver: OPENCODE_PROVIDER,
3287 - threadId: turnInput.threadId,
3288 - providerThreadId: turnInput.providerThread.id,
3289 - runId: turnInput.runId,
3290 - cause,
3291 - }),
3288 + },
3289 + (effect, turnInput) =>
3290 + effect.pipe(
3291 + Effect.mapError(
3292 + (cause) =>
3293 + new ProviderAdapter.ProviderAdapterTurnStartError({
3294 + driver: OPENCODE_PROVIDER,
3295 + threadId: turnInput.threadId,
3296 + providerThreadId: turnInput.providerThread.id,
3297 + runId: turnInput.runId,
3298 + cause,
3299 + }),
3300 + ),
3301 ),
3293 - ),
3294 - steerTurn: (steerInput) =>
3295 - Effect.gen(function* () {
3302 + ),
3303 + steerTurn: Effect.fn("OpencodeAdapter.steerTurn")(
3304 + function* (steerInput) {
3305 const sessionId = nativeThreadId(steerInput.providerThread);
3306 const state = threads.get(sessionId);
3307 const turn = state?.activeTurn;
@@ -3369,19 +3378,22 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3378 yield* reconcilePromptAdmission(state, turn);
3379 }
3380 }
3372 - }).pipe(
3373 - Effect.mapError(
3374 - (cause) =>
3375 - new ProviderAdapter.ProviderAdapterSteerRunError({
3376 - driver: OPENCODE_PROVIDER,
3377 - providerThreadId: steerInput.providerThread.id,
3378 - providerTurnId: steerInput.providerTurnId,
3379 - cause,
3380 - }),
3381 + },
3382 + (effect, steerInput) =>
3383 + effect.pipe(
3384 + Effect.mapError(
3385 + (cause) =>
3386 + new ProviderAdapter.ProviderAdapterSteerRunError({
3387 + driver: OPENCODE_PROVIDER,
3388 + providerThreadId: steerInput.providerThread.id,
3389 + providerTurnId: steerInput.providerTurnId,
3390 + cause,
3391 + }),
3392 + ),
3393 ),
3382 - ),
3383 - interruptTurn: (interruptInput) =>
3384 - Effect.gen(function* () {
3394 + ),
3395 + interruptTurn: Effect.fn("OpencodeAdapter.interruptTurn")(
3396 + function* (interruptInput) {
3397 const sessionId = nativeThreadId(interruptInput.providerThread);
3398 const state = threads.get(sessionId);
3399 const turn = state?.activeTurn;
@@ -3432,19 +3444,22 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3444 // Root abort does not stop child sessions. Report incomplete cleanup
3445 // even if the root has already emitted its terminal event.
3446 yield* abortDescendants(sessionId);
3435 - }).pipe(
3436 - Effect.mapError(
3437 - (cause) =>
3438 - new ProviderAdapter.ProviderAdapterInterruptError({
3439 - driver: OPENCODE_PROVIDER,
3440 - providerThreadId: interruptInput.providerThread.id,
3441 - providerTurnId: interruptInput.providerTurnId,
3442 - cause,
3443 - }),
3447 + },
3448 + (effect, interruptInput) =>
3449 + effect.pipe(
3450 + Effect.mapError(
3451 + (cause) =>
3452 + new ProviderAdapter.ProviderAdapterInterruptError({
3453 + driver: OPENCODE_PROVIDER,
3454 + providerThreadId: interruptInput.providerThread.id,
3455 + providerTurnId: interruptInput.providerTurnId,
3456 + cause,
3457 + }),
3458 + ),
3459 ),
3445 - ),
3446 - respondToRuntimeRequest: (requestInput) =>
3447 - Effect.gen(function* () {
3460 + ),
3461 + respondToRuntimeRequest: Effect.fn("OpencodeAdapter.respondToRuntimeRequest")(
3462 + function* (requestInput) {
3463 const pending = pendingRequests.get(String(requestInput.requestId));
3464 if (pending === undefined) {
3465 return yield* protocolError(
@@ -3493,16 +3508,19 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3508 { signal },
3509 ),
3510 ).pipe(Effect.timeout("10 seconds"));
3496 - }).pipe(
3497 - Effect.mapError(
3498 - (cause) =>
3499 - new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
3500 - driver: OPENCODE_PROVIDER,
3501 - requestId: requestInput.requestId,
3502 - cause,
3503 - }),
3511 + },
3512 + (effect, requestInput) =>
3513 + effect.pipe(
3514 + Effect.mapError(
3515 + (cause) =>
3516 + new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
3517 + driver: OPENCODE_PROVIDER,
3518 + requestId: requestInput.requestId,
3519 + cause,
3520 + }),
3521 + ),
3522 ),
3505 - ),
3523 + ),
3524 readThreadSnapshot: (snapshotInput) =>
3525 readSnapshot(snapshotInput.providerThread).pipe(
3526 Effect.mapError(
@@ -3514,8 +3532,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3532 }),
3533 ),
3534 ),
3517 - rollbackThread: (rollbackInput) =>
3518 - Effect.gen(function* () {
3535 + rollbackThread: Effect.fn("OpencodeAdapter.rollbackThread")(
3536 + function* (rollbackInput) {
3537 const sessionId = nativeThreadId(rollbackInput.providerThread);
3538 const state = threads.get(sessionId);
3539 if (state?.activeTurn !== null && state?.activeTurn !== undefined) {
@@ -3587,19 +3605,22 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3605 : null,
3606 },
3607 };
3590 - }).pipe(
3591 - Effect.mapError(
3592 - (cause) =>
3593 - new ProviderAdapter.ProviderAdapterRollbackThreadError({
3594 - driver: OPENCODE_PROVIDER,
3595 - providerThreadId: rollbackInput.providerThread.id,
3596 - checkpointId: rollbackInput.target.checkpointId,
3597 - cause,
3598 - }),
3608 + },
3609 + (effect, rollbackInput) =>
3610 + effect.pipe(
3611 + Effect.mapError(
3612 + (cause) =>
3613 + new ProviderAdapter.ProviderAdapterRollbackThreadError({
3614 + driver: OPENCODE_PROVIDER,
3615 + providerThreadId: rollbackInput.providerThread.id,
3616 + checkpointId: rollbackInput.target.checkpointId,
3617 + cause,
3618 + }),
3619 + ),
3620 ),
3600 - ),
3601 - forkThread: (forkInput) =>
3602 - Effect.gen(function* () {
3621 + ),
3622 + forkThread: Effect.fn("OpencodeAdapter.forkThread")(
3623 + function* (forkInput) {
3624 const sourceSessionId = nativeThreadId(forkInput.sourceProviderThread);
3625 const sourceState = threads.get(sourceSessionId);
3626 if (sourceState?.activeTurn !== null && sourceState?.activeTurn !== undefined) {
@@ -3651,16 +3672,19 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3672 });
3673 registerThread(nativeSession, providerThread, null);
3674 return providerThread;
3654 - }).pipe(
3655 - Effect.mapError(
3656 - (cause) =>
3657 - new ProviderAdapter.ProviderAdapterForkThreadError({
3658 - driver: OPENCODE_PROVIDER,
3659 - providerThreadId: forkInput.sourceProviderThread.id,
3660 - cause,
3661 - }),
3675 + },
3676 + (effect, forkInput) =>
3677 + effect.pipe(
3678 + Effect.mapError(
3679 + (cause) =>
3680 + new ProviderAdapter.ProviderAdapterForkThreadError({
3681 + driver: OPENCODE_PROVIDER,
3682 + providerThreadId: forkInput.sourceProviderThread.id,
3683 + cause,
3684 + }),
3685 + ),
3686 ),
3663 - ),
3687 + ),
3688 };
3689
3690 return runtimeSession;
packages/provider-opencode/src/server/driver.ts
+310 -312
@@ -186,343 +186,341 @@ export const OpenCodeDriver: ProviderDriver<
186 configSchema: OpenCodeSettings,
187 defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
188 usage: openCodeUsageReader,
189 - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
190 - Effect.gen(function* () {
191 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
192 - const fileSystem = yield* FileSystem.FileSystem;
193 - const pathService = yield* Path.Path;
194 - const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
195 - const httpClient = yield* HttpClient.HttpClient;
196 - const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
197 - const crypto = yield* Crypto.Crypto;
198 - const host = yield* ProviderHost.ProviderHost;
199 - const processEnv = yield* mergeProviderInstanceEnvironment(environment);
200 - const continuationIdentity = defaultProviderContinuationIdentity({
201 - driverKind: DRIVER_KIND,
202 - instanceId,
203 - });
204 - const stampIdentity = withInstanceIdentity({
205 - instanceId,
206 - driverKind: DRIVER_KIND,
207 - displayName,
208 - accentColor,
209 - continuationGroupKey: continuationIdentity.continuationKey,
210 - });
211 - const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
212 - const runtimeProbe = yield* makeOpenCodeRuntimeProbe(
213 - probeOpenCodeRuntime(effectiveConfig, processEnv).pipe(
214 - Effect.provideService(HttpClient.HttpClient, httpClient),
215 - Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
216 - ),
217 - );
218 - const noUpdate = makeManualOnlyProviderMaintenanceCapabilities({
219 - provider: DRIVER_KIND,
220 - packageName: null,
221 - });
222 - const maintenanceFor = (probed: typeof runtimeProbe.get) =>
223 - probed.pipe(
224 - Effect.map((result) => result.generation),
225 - Effect.option,
226 - Effect.flatMap((generation) =>
227 - Option.isNone(generation)
228 - ? Effect.succeed(noUpdate)
229 - : resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation.value), {
230 - binaryPath: effectiveConfig.binaryPath,
231 - env: processEnv,
232 - }),
233 - ),
234 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
235 - Effect.provideService(FileSystem.FileSystem, fileSystem),
236 - Effect.provideService(Path.Path, pathService),
237 - );
238 - const cachedMaintenance = yield* makeCachedProviderMaintenanceResolution(
239 - maintenanceFor(runtimeProbe.get),
240 - );
241 - const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>
242 - !effectiveConfig.enabled
243 - ? Effect.succeed(noUpdate)
244 - : options?.fresh === true
245 - ? runtimeProbe.refresh.pipe(
246 - Effect.ignore,
247 - Effect.andThen(cachedMaintenance({ fresh: true })),
248 - )
249 - : cachedMaintenance();
250 - const openCodeV1Adapter = yield* OpenCodeAdapterV2.OpenCodeAdapterV2Driver.create({
251 - instanceId,
252 - displayName,
253 - accentColor,
254 - environment,
255 - enabled,
256 - config,
257 - }).pipe(
258 - Effect.mapError(
259 - (cause) =>
260 - new ProviderDriverError({
261 - driver: DRIVER_KIND,
262 - instanceId,
263 - detail: "Failed to build OpenCode orchestration adapter.",
264 - cause,
265 - }),
266 - ),
267 - );
268 - const openCode2Server = yield* OpenCode2Server.make({
269 - binaryPath: effectiveConfig.binaryPath,
270 - serverUrl: effectiveConfig.serverUrl,
271 - serverPassword: effectiveConfig.serverPassword,
272 - directory: host.paths.cwd,
273 - environment: processEnv,
274 - }).pipe(
189 + create: Effect.fn("OpencodeDriver.create")(function* ({
190 + instanceId,
191 + displayName,
192 + accentColor,
193 + environment,
194 + enabled,
195 + config,
196 + }) {
197 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
198 + const fileSystem = yield* FileSystem.FileSystem;
199 + const pathService = yield* Path.Path;
200 + const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
201 + const httpClient = yield* HttpClient.HttpClient;
202 + const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
203 + const crypto = yield* Crypto.Crypto;
204 + const host = yield* ProviderHost.ProviderHost;
205 + const processEnv = yield* mergeProviderInstanceEnvironment(environment);
206 + const continuationIdentity = defaultProviderContinuationIdentity({
207 + driverKind: DRIVER_KIND,
208 + instanceId,
209 + });
210 + const stampIdentity = withInstanceIdentity({
211 + instanceId,
212 + driverKind: DRIVER_KIND,
213 + displayName,
214 + accentColor,
215 + continuationGroupKey: continuationIdentity.continuationKey,
216 + });
217 + const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
218 + const runtimeProbe = yield* makeOpenCodeRuntimeProbe(
219 + probeOpenCodeRuntime(effectiveConfig, processEnv).pipe(
220 + Effect.provideService(HttpClient.HttpClient, httpClient),
221 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
276 - Effect.provideService(
277 - OpenCode2Client.OpenCode2Client,
278 - yield* OpenCode2Client.make.pipe(
279 - Effect.provideService(HttpClient.HttpClient, httpClient),
280 - ),
281 - ),
282 - );
283 - const orchestrationAdapter = selectOpenCodeRuntimeAdapter({
284 - probe: runtimeProbe,
285 - v1: openCodeV1Adapter,
286 - v2: yield* OpenCode2AdapterV2.make(instanceId).pipe(
287 - Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
288 - ),
289 - });
290 - const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(
291 - openCode2Server.withConnection(({ client }) =>
292 - loadOpenCode2Catalog(client, host.paths.cwd),
222 + ),
223 + );
224 + const noUpdate = makeManualOnlyProviderMaintenanceCapabilities({
225 + provider: DRIVER_KIND,
226 + packageName: null,
227 + });
228 + const maintenanceFor = (probed: typeof runtimeProbe.get) =>
229 + probed.pipe(
230 + Effect.map((result) => result.generation),
231 + Effect.option,
232 + Effect.flatMap((generation) =>
233 + Option.isNone(generation)
234 + ? Effect.succeed(noUpdate)
235 + : resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation.value), {
236 + binaryPath: effectiveConfig.binaryPath,
237 + env: processEnv,
238 + }),
239 ),
240 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
241 + Effect.provideService(FileSystem.FileSystem, fileSystem),
242 + Effect.provideService(Path.Path, pathService),
243 );
295 - const listOpenCode2Workspace = (cwd: string) =>
296 - openCode2Server.withConnection(({ client, events }) =>
297 - Effect.gen(function* () {
298 - const location = { directory: cwd };
299 - const scanned = yield* Deferred.make<void>();
300 - const pending = new Set(["command.updated", "skill.updated"]);
301 - const stream = yield* events.pipe(Effect.option);
302 - if (stream._tag === "Some") {
303 - yield* stream.value.pipe(
304 - Stream.runForEach((event) =>
305 - "location" in event &&
306 - event.location?.directory === cwd &&
307 - pending.delete(event.type) &&
308 - pending.size === 0
309 - ? Deferred.succeed(scanned, undefined)
310 - : Effect.void,
311 - ),
312 - Effect.ignore,
313 - Effect.forkScoped,
314 - );
315 - }
316 - return yield* loadOpenCode2Workspace(
317 - Effect.all(
318 - {
319 - skills: client.skill.list({ location }).pipe(Effect.map((list) => list.data)),
320 - commands: client.command.list({ location }).pipe(Effect.map((list) => list.data)),
321 - },
322 - { concurrency: "unbounded" },
244 + const cachedMaintenance = yield* makeCachedProviderMaintenanceResolution(
245 + maintenanceFor(runtimeProbe.get),
246 + );
247 + const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>
248 + !effectiveConfig.enabled
249 + ? Effect.succeed(noUpdate)
250 + : options?.fresh === true
251 + ? runtimeProbe.refresh.pipe(
252 + Effect.ignore,
253 + Effect.andThen(cachedMaintenance({ fresh: true })),
254 + )
255 + : cachedMaintenance();
256 + const openCodeV1Adapter = yield* OpenCodeAdapterV2.OpenCodeAdapterV2Driver.create({
257 + instanceId,
258 + displayName,
259 + accentColor,
260 + environment,
261 + enabled,
262 + config,
263 + }).pipe(
264 + Effect.mapError(
265 + (cause) =>
266 + new ProviderDriverError({
267 + driver: DRIVER_KIND,
268 + instanceId,
269 + detail: "Failed to build OpenCode orchestration adapter.",
270 + cause,
271 + }),
272 + ),
273 + );
274 + const openCode2Server = yield* OpenCode2Server.make({
275 + binaryPath: effectiveConfig.binaryPath,
276 + serverUrl: effectiveConfig.serverUrl,
277 + serverPassword: effectiveConfig.serverPassword,
278 + directory: host.paths.cwd,
279 + environment: processEnv,
280 + }).pipe(
281 + Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
282 + Effect.provideService(
283 + OpenCode2Client.OpenCode2Client,
284 + yield* OpenCode2Client.make.pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
285 + ),
286 + );
287 + const orchestrationAdapter = selectOpenCodeRuntimeAdapter({
288 + probe: runtimeProbe,
289 + v1: openCodeV1Adapter,
290 + v2: yield* OpenCode2AdapterV2.make(instanceId).pipe(
291 + Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
292 + ),
293 + });
294 + const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(
295 + openCode2Server.withConnection(({ client }) => loadOpenCode2Catalog(client, host.paths.cwd)),
296 + );
297 + const listOpenCode2Workspace = (cwd: string) =>
298 + openCode2Server.withConnection(({ client, events }) =>
299 + Effect.gen(function* () {
300 + const location = { directory: cwd };
301 + const scanned = yield* Deferred.make<void>();
302 + const pending = new Set(["command.updated", "skill.updated"]);
303 + const stream = yield* events.pipe(Effect.option);
304 + if (stream._tag === "Some") {
305 + yield* stream.value.pipe(
306 + Stream.runForEach((event) =>
307 + "location" in event &&
308 + event.location?.directory === cwd &&
309 + pending.delete(event.type) &&
310 + pending.size === 0
311 + ? Deferred.succeed(scanned, undefined)
312 + : Effect.void,
313 ),
324 - Deferred.await(scanned),
314 + Effect.ignore,
315 + Effect.forkScoped,
316 );
326 - }).pipe(Effect.scoped),
327 - );
328 - const serverOwner = yield* OpenCodeServerOwner.make({
329 - binaryPath: effectiveConfig.binaryPath,
330 - directory: host.paths.cwd,
331 - ...(effectiveConfig.serverPassword
332 - ? { serverPassword: effectiveConfig.serverPassword }
333 - : {}),
334 - environment: processEnv,
335 - });
336 - const textGeneration = selectOpenCodeRuntimeTextGeneration(
337 - runtimeProbe,
338 - yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(
339 - Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
340 - ),
341 - yield* OpenCode2TextGeneration.make().pipe(
342 - Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
343 - ),
317 + }
318 + return yield* loadOpenCode2Workspace(
319 + Effect.all(
320 + {
321 + skills: client.skill.list({ location }).pipe(Effect.map((list) => list.data)),
322 + commands: client.command.list({ location }).pipe(Effect.map((list) => list.data)),
323 + },
324 + { concurrency: "unbounded" },
325 + ),
326 + Deferred.await(scanned),
327 + );
328 + }).pipe(Effect.scoped),
329 );
330 + const serverOwner = yield* OpenCodeServerOwner.make({
331 + binaryPath: effectiveConfig.binaryPath,
332 + directory: host.paths.cwd,
333 + ...(effectiveConfig.serverPassword ? { serverPassword: effectiveConfig.serverPassword } : {}),
334 + environment: processEnv,
335 + });
336 + const textGeneration = selectOpenCodeRuntimeTextGeneration(
337 + runtimeProbe,
338 + yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(
339 + Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
340 + ),
341 + yield* OpenCode2TextGeneration.make().pipe(
342 + Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
343 + ),
344 + );
345
346 - const checkProvider = Effect.all(
346 + const checkProvider = Effect.all(
347 + {
348 + provider: checkOpenCodeProviderStatus(
349 + effectiveConfig,
350 + host.paths.cwd,
351 + runtimeProbe.refresh,
352 + loadOpenCode2Models,
353 + ),
354 + usageLimits: readOpenCodeGoUsageLimits({
355 + enabled: effectiveConfig.enabled,
356 + serverUrl: effectiveConfig.serverUrl,
357 + environment: processEnv,
358 + }),
359 + },
360 + { concurrency: "unbounded" },
361 + ).pipe(
362 + Effect.map(({ provider, usageLimits }) => ({ ...provider, usageLimits })),
363 + Effect.map(stampIdentity),
364 + Effect.provideService(FileSystem.FileSystem, fileSystem),
365 + Effect.provideService(Path.Path, pathService),
366 + Effect.provideService(HttpClient.HttpClient, httpClient),
367 + Effect.provideService(Crypto.Crypto, crypto),
368 + Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
369 + Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
370 + );
371 + // The CLI writes its full JSON inventory to stdout, but the Bun-compiled binary does not
372 + // flush more than one 64KB pipe buffer to a non-TTY stdout, so the piped output arrives
373 + // truncated and unparseable — which degrades to an empty skill list and poisons the workspace
374 + // snapshot the `$` picker reads.
375 + const loadWorkspaceInventory = (
376 + client: Parameters<typeof OpenCodeRuntime.loadOpenCodeCommands>[0],
377 + ) =>
378 + Effect.all(
379 {
348 - provider: checkOpenCodeProviderStatus(
349 - effectiveConfig,
350 - host.paths.cwd,
351 - runtimeProbe.refresh,
352 - loadOpenCode2Models,
380 + skills: openCodeRuntime.loadOpenCodeSkills(client),
381 + commands: OpenCodeRuntime.loadOpenCodeCommands(client).pipe(
382 + Effect.timeout("10 seconds"),
383 + Effect.option,
384 ),
354 - usageLimits: readOpenCodeGoUsageLimits({
355 - enabled: effectiveConfig.enabled,
356 - serverUrl: effectiveConfig.serverUrl,
357 - environment: processEnv,
358 - }),
385 },
386 { concurrency: "unbounded" },
387 ).pipe(
362 - Effect.map(({ provider, usageLimits }) => ({ ...provider, usageLimits })),
363 - Effect.map(stampIdentity),
364 - Effect.provideService(FileSystem.FileSystem, fileSystem),
365 - Effect.provideService(Path.Path, pathService),
366 - Effect.provideService(HttpClient.HttpClient, httpClient),
367 - Effect.provideService(Crypto.Crypto, crypto),
368 - Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
369 - Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
388 + // Only a finished lookup is reported as complete. A failed one leaves
389 + // the flag unset, so the registry decides from the provider's health.
390 + Effect.map(({ skills, commands }) => ({
391 + skills,
392 + commands: Option.getOrElse(commands, () => []),
393 + slashCommandsPending: Option.isSome(commands) ? false : undefined,
394 + })),
395 );
371 - // The CLI writes its full JSON inventory to stdout, but the Bun-compiled binary does not
372 - // flush more than one 64KB pipe buffer to a non-TTY stdout, so the piped output arrives
373 - // truncated and unparseable — which degrades to an empty skill list and poisons the workspace
374 - // snapshot the `$` picker reads.
375 - const loadWorkspaceInventory = (
376 - client: Parameters<typeof OpenCodeRuntime.loadOpenCodeCommands>[0],
377 - ) =>
378 - Effect.all(
379 - {
380 - skills: openCodeRuntime.loadOpenCodeSkills(client),
381 - commands: OpenCodeRuntime.loadOpenCodeCommands(client).pipe(
382 - Effect.timeout("10 seconds"),
383 - Effect.option,
384 - ),
385 - },
386 - { concurrency: "unbounded" },
387 - ).pipe(
388 - // Only a finished lookup is reported as complete. A failed one leaves
389 - // the flag unset, so the registry decides from the provider's health.
390 - Effect.map(({ skills, commands }) => ({
391 - skills,
392 - commands: Option.getOrElse(commands, () => []),
393 - slashCommandsPending: Option.isSome(commands) ? false : undefined,
394 - })),
395 - );
396 - const loadWorkspaceForCwd = (cwd: string) =>
397 - effectiveConfig.serverUrl.trim().length > 0
398 - ? Effect.scoped(
399 - Effect.gen(function* () {
400 - const server = yield* openCodeRuntime.connectToOpenCodeServer({
401 - binaryPath: effectiveConfig.binaryPath,
402 - directory: cwd,
403 - serverUrl: effectiveConfig.serverUrl,
404 - ...(effectiveConfig.serverPassword
405 - ? { serverPassword: effectiveConfig.serverPassword }
406 - : {}),
407 - environment: processEnv,
408 - });
409 - const client = openCodeRuntime.createOpenCodeSdkClient({
410 - baseUrl: server.url,
411 - directory: cwd,
412 - ...(effectiveConfig.serverPassword
413 - ? { serverPassword: effectiveConfig.serverPassword }
414 - : {}),
415 - });
416 - return yield* loadWorkspaceInventory(client);
396 + const loadWorkspaceForCwd = (cwd: string) =>
397 + effectiveConfig.serverUrl.trim().length > 0
398 + ? Effect.scoped(
399 + Effect.gen(function* () {
400 + const server = yield* openCodeRuntime.connectToOpenCodeServer({
401 + binaryPath: effectiveConfig.binaryPath,
402 + directory: cwd,
403 + serverUrl: effectiveConfig.serverUrl,
404 + ...(effectiveConfig.serverPassword
405 + ? { serverPassword: effectiveConfig.serverPassword }
406 + : {}),
407 + environment: processEnv,
408 + });
409 + const client = openCodeRuntime.createOpenCodeSdkClient({
410 + baseUrl: server.url,
411 + directory: cwd,
412 + ...(effectiveConfig.serverPassword
413 + ? { serverPassword: effectiveConfig.serverPassword }
414 + : {}),
415 + });
416 + return yield* loadWorkspaceInventory(client);
417 + }),
418 + )
419 + : serverOwner.withServer((server) =>
420 + loadWorkspaceInventory(
421 + openCodeRuntime.createOpenCodeSdkClient({
422 + baseUrl: server.url,
423 + directory: cwd,
424 + ...(server.serverPassword !== undefined
425 + ? { serverPassword: server.serverPassword }
426 + : {}),
427 }),
418 - )
419 - : serverOwner.withServer((server) =>
420 - loadWorkspaceInventory(
421 - openCodeRuntime.createOpenCodeSdkClient({
422 - baseUrl: server.url,
423 - directory: cwd,
424 - ...(server.serverPassword !== undefined
425 - ? { serverPassword: server.serverPassword }
426 - : {}),
427 - }),
428 - ),
429 - );
430 -
431 - const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
432 - const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
433 - {
434 - resolveMaintenance,
435 - getSettings: snapshotSettings.getSettings,
436 - streamSettings: snapshotSettings.streamSettings,
437 - haveSettingsChanged: haveProviderSnapshotSettingsChanged,
438 - checkProviderOnSettingsChange: () => false,
439 - refreshOnInterval: false,
440 - initialSnapshot: (settings) =>
441 - makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
442 - checkProvider,
443 - enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
444 - resolveMaintenance().pipe(
445 - Effect.flatMap((maintenanceCapabilities) =>
446 - enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
447 - enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
448 - }),
449 - ),
450 - Effect.provideService(HttpClient.HttpClient, httpClient),
451 - Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
452 - Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
428 ),
454 - },
455 - ).pipe(
456 - Effect.mapError(
457 - (cause) =>
458 - new ProviderDriverError({
459 - driver: DRIVER_KIND,
460 - instanceId,
461 - detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
462 - cause,
429 + );
430 +
431 + const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
432 + const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>({
433 + resolveMaintenance,
434 + getSettings: snapshotSettings.getSettings,
435 + streamSettings: snapshotSettings.streamSettings,
436 + haveSettingsChanged: haveProviderSnapshotSettingsChanged,
437 + checkProviderOnSettingsChange: () => false,
438 + refreshOnInterval: false,
439 + initialSnapshot: (settings) =>
440 + makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
441 + checkProvider,
442 + enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
443 + resolveMaintenance().pipe(
444 + Effect.flatMap((maintenanceCapabilities) =>
445 + enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
446 + enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
447 }),
448 + ),
449 + Effect.provideService(HttpClient.HttpClient, httpClient),
450 + Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
451 + Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
452 ),
465 - );
453 + }).pipe(
454 + Effect.mapError(
455 + (cause) =>
456 + new ProviderDriverError({
457 + driver: DRIVER_KIND,
458 + instanceId,
459 + detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
460 + cause,
461 + }),
462 + ),
463 + );
464
467 - return {
468 - instanceId,
469 - driverKind: DRIVER_KIND,
470 - continuationIdentity,
471 - displayName,
472 - accentColor,
473 - enabled,
474 - snapshot,
475 - snapshotForCwd: (cwd) =>
476 - !effectiveConfig.enabled
477 - ? snapshot.getSnapshot
478 - : byOpenCodeRuntime(runtimeProbe.get, {
479 - v2: Effect.all([
480 - snapshot.getSnapshot,
481 - listOpenCode2Workspace(cwd).pipe(
482 - Effect.timeout("20 seconds"),
483 - Effect.mapError(
484 - (cause) =>
485 - new ProviderDriverError({
486 - driver: DRIVER_KIND,
487 - instanceId,
488 - detail: `Failed to list OpenCode commands and skills for '${cwd}'`,
489 - cause,
490 - }),
491 - ),
492 - ),
493 - ]).pipe(
494 - Effect.map(([machineSnapshot, { skills, commands }]) => ({
495 - ...machineSnapshot,
496 - skills: openCode2SkillsToServerProviderSkills(skills),
497 - slashCommands: openCode2CommandsToServerProviderSlashCommands(commands),
498 - // A finished scan lists at least the built-ins. None means it
499 - // timed out, so the registry decides from the provider's health.
500 - slashCommandsPending: commands.length > 0 ? false : undefined,
501 - })),
502 - ),
503 - v1: Effect.all([
504 - snapshot.getSnapshot,
505 - loadWorkspaceForCwd(cwd).pipe(Effect.timeout("20 seconds")),
506 - ]).pipe(
507 - Effect.map(([machineSnapshot, { skills, commands, slashCommandsPending }]) => ({
508 - ...machineSnapshot,
509 - skills: openCodeSkillsToServerProviderSkills(skills),
510 - slashCommands: openCodeCommandsToServerProviderSlashCommands(commands),
511 - slashCommandsPending,
512 - })),
465 + return {
466 + instanceId,
467 + driverKind: DRIVER_KIND,
468 + continuationIdentity,
469 + displayName,
470 + accentColor,
471 + enabled,
472 + snapshot,
473 + snapshotForCwd: (cwd) =>
474 + !effectiveConfig.enabled
475 + ? snapshot.getSnapshot
476 + : byOpenCodeRuntime(runtimeProbe.get, {
477 + v2: Effect.all([
478 + snapshot.getSnapshot,
479 + listOpenCode2Workspace(cwd).pipe(
480 + Effect.timeout("20 seconds"),
481 Effect.mapError(
482 (cause) =>
483 new ProviderDriverError({
484 driver: DRIVER_KIND,
485 instanceId,
518 - detail: `Failed to probe OpenCode commands and skills for '${cwd}'`,
486 + detail: `Failed to list OpenCode commands and skills for '${cwd}'`,
487 cause,
488 }),
489 ),
490 ),
523 - }),
524 - orchestrationAdapter,
525 - textGeneration,
526 - } satisfies ProviderInstance;
527 - }),
491 + ]).pipe(
492 + Effect.map(([machineSnapshot, { skills, commands }]) => ({
493 + ...machineSnapshot,
494 + skills: openCode2SkillsToServerProviderSkills(skills),
495 + slashCommands: openCode2CommandsToServerProviderSlashCommands(commands),
496 + // A finished scan lists at least the built-ins. None means it
497 + // timed out, so the registry decides from the provider's health.
498 + slashCommandsPending: commands.length > 0 ? false : undefined,
499 + })),
500 + ),
501 + v1: Effect.all([
502 + snapshot.getSnapshot,
503 + loadWorkspaceForCwd(cwd).pipe(Effect.timeout("20 seconds")),
504 + ]).pipe(
505 + Effect.map(([machineSnapshot, { skills, commands, slashCommandsPending }]) => ({
506 + ...machineSnapshot,
507 + skills: openCodeSkillsToServerProviderSkills(skills),
508 + slashCommands: openCodeCommandsToServerProviderSlashCommands(commands),
509 + slashCommandsPending,
510 + })),
511 + Effect.mapError(
512 + (cause) =>
513 + new ProviderDriverError({
514 + driver: DRIVER_KIND,
515 + instanceId,
516 + detail: `Failed to probe OpenCode commands and skills for '${cwd}'`,
517 + cause,
518 + }),
519 + ),
520 + ),
521 + }),
522 + orchestrationAdapter,
523 + textGeneration,
524 + } satisfies ProviderInstance;
525 + }),
526 };
packages/provider-opencode/src/server/status.ts
+34 -37
@@ -328,39 +328,20 @@ export function openCodeCommandsToServerProviderSlashCommands(
328 return commands;
329 }
330
331 -export const makePendingOpenCodeProvider = (
332 - openCodeSettings: OpenCodeSettings,
333 -): Effect.Effect<ServerProviderDraft> =>
334 - Effect.gen(function* () {
335 - const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
336 - const models = providerModelsFromSettings(
337 - [],
338 - openCodeSettings.customModels,
339 - DEFAULT_OPENCODE_MODEL_CAPABILITIES,
340 - );
341 -
342 - if (!openCodeSettings.enabled) {
343 - return buildServerProvider({
344 - presentation: OPENCODE_PRESENTATION,
345 - enabled: false,
346 - checkedAt,
347 - models,
348 - probe: {
349 - installed: false,
350 - version: null,
351 - status: "warning",
352 - auth: { status: "unknown" },
353 - message:
354 - openCodeSettings.serverUrl.trim().length > 0
355 - ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
356 - : "OpenCode is disabled in T3 Code settings.",
357 - },
358 - });
359 - }
331 +export const makePendingOpenCodeProvider = Effect.fn(
332 + "OpencodeProviderStatus.makePendingOpenCodeProvider",
333 +)(function* (openCodeSettings: OpenCodeSettings): Effect.fn.Return<ServerProviderDraft> {
334 + const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
335 + const models = providerModelsFromSettings(
336 + [],
337 + openCodeSettings.customModels,
338 + DEFAULT_OPENCODE_MODEL_CAPABILITIES,
339 + );
340
341 + if (!openCodeSettings.enabled) {
342 return buildServerProvider({
343 presentation: OPENCODE_PRESENTATION,
363 - enabled: true,
344 + enabled: false,
345 checkedAt,
346 models,
347 probe: {
@@ -368,10 +349,28 @@ export const makePendingOpenCodeProvider = (
349 version: null,
350 status: "warning",
351 auth: { status: "unknown" },
371 - message: "OpenCode provider status has not been checked in this session yet.",
352 + message:
353 + openCodeSettings.serverUrl.trim().length > 0
354 + ? "OpenCode is disabled in T3 Code settings. A server URL is configured."
355 + : "OpenCode is disabled in T3 Code settings.",
356 },
357 });
358 + }
359 +
360 + return buildServerProvider({
361 + presentation: OPENCODE_PRESENTATION,
362 + enabled: true,
363 + checkedAt,
364 + models,
365 + probe: {
366 + installed: false,
367 + version: null,
368 + status: "warning",
369 + auth: { status: "unknown" },
370 + message: "OpenCode provider status has not been checked in this session yet.",
371 + },
372 });
373 +});
374
375 export interface OpenCode2Model {
376 readonly providerID: string;
@@ -461,16 +460,14 @@ export interface OpenCode2Workspace {
460 * for the directory end the scan. `scanned` must be listening before `read` runs, since
461 * the read is what starts the scan.
462 */
464 -export const loadOpenCode2Workspace = <E>(
465 - read: Effect.Effect<OpenCode2Workspace, E>,
466 - scanned: Effect.Effect<void>,
467 -) =>
468 - Effect.gen(function* () {
463 +export const loadOpenCode2Workspace = Effect.fn("OpencodeProviderStatus.loadOpenCode2Workspace")(
464 + function* <E>(read: Effect.Effect<OpenCode2Workspace, E>, scanned: Effect.Effect<void>) {
465 const first = yield* read;
466 if (first.commands.length > 0) return first;
467 yield* scanned.pipe(Effect.timeoutOption("10 seconds"));
468 return yield* read;
473 - });
469 + },
470 +);
471
472 export function openCode2SkillsToServerProviderSkills(
473 skills: OpenCode2Workspace["skills"],
packages/provider-opencode/src/server/v2/OpenCode2Client.ts
+28 -28
@@ -91,34 +91,34 @@ const decodeEnvelope = Schema.decodeUnknownOption(
91 ),
92 );
93
94 -const undecodable = (data: string) =>
95 - Effect.gen(function* () {
96 - const envelope = decodeEnvelope(data);
97 - const type = envelope._tag === "Some" ? envelope.value.type.slice(0, 80) : "<unreadable>";
98 - const sessionID = envelope._tag === "Some" ? envelope.value.data?.sessionID : undefined;
99 - if (isExecutionEnd(type) && sessionID !== undefined) {
100 - yield* Effect.logWarning(
101 - "Ended an OpenCode execution from an event this build cannot decode.",
102 - {
103 - type,
104 - },
105 - );
106 - return Result.succeed<OpenCode2StreamEvent>({
107 - type: "unreadable.execution.ended",
108 - executionType: type,
109 - sessionID,
110 - });
111 - }
112 - if (type === "session.execution.started" && sessionID !== undefined) {
113 - yield* Effect.logDebug("Read an OpenCode execution start this build cannot decode.");
114 - return Result.succeed<OpenCode2StreamEvent>({
115 - type: "unreadable.execution.started",
116 - sessionID,
117 - });
118 - }
119 - yield* Effect.logDebug("Skipped an OpenCode event this build cannot decode.", { type });
120 - return Result.failVoid;
121 - });
94 +// Rejected stream frames can be frequent when the server introduces new event types.
95 +const undecodable = Effect.fnUntraced(function* (data: string) {
96 + const envelope = decodeEnvelope(data);
97 + const type = envelope._tag === "Some" ? envelope.value.type.slice(0, 80) : "<unreadable>";
98 + const sessionID = envelope._tag === "Some" ? envelope.value.data?.sessionID : undefined;
99 + if (isExecutionEnd(type) && sessionID !== undefined) {
100 + yield* Effect.logWarning(
101 + "Ended an OpenCode execution from an event this build cannot decode.",
102 + {
103 + type,
104 + },
105 + );
106 + return Result.succeed<OpenCode2StreamEvent>({
107 + type: "unreadable.execution.ended",
108 + executionType: type,
109 + sessionID,
110 + });
111 + }
112 + if (type === "session.execution.started" && sessionID !== undefined) {
113 + yield* Effect.logDebug("Read an OpenCode execution start this build cannot decode.");
114 + return Result.succeed<OpenCode2StreamEvent>({
115 + type: "unreadable.execution.started",
116 + sessionID,
117 + });
118 + }
119 + yield* Effect.logDebug("Skipped an OpenCode event this build cannot decode.", { type });
120 + return Result.failVoid;
121 +});
122
123 const readEvents = HttpClient.get("/api/event", {
124 headers: { accept: "text/event-stream" },
packages/provider-opencode/src/server/v2/OpenCode2Server.ts
+9 -6
@@ -136,12 +136,15 @@ export const make = Effect.fn("OpenCode2Server.make")(function* (input: {
136 readonly environment: NodeJS.ProcessEnv;
137 }) {
138 const opencode = yield* OpenCode2Client.OpenCode2Client;
139 - const connectTo = (url: string, password: Redacted.Redacted, external: boolean) =>
140 - Effect.gen(function* () {
141 - const api = yield* opencode.connect({ baseUrl: url, password });
142 - const version = yield* verifyServer(api.client);
143 - return { ...api, url, version, external } satisfies OpenCode2Connection;
144 - });
139 + const connectTo = Effect.fn("OpenCode2Server.connectTo")(function* (
140 + url: string,
141 + password: Redacted.Redacted,
142 + external: boolean,
143 + ) {
144 + const api = yield* opencode.connect({ baseUrl: url, password });
145 + const version = yield* verifyServer(api.client);
146 + return { ...api, url, version, external } satisfies OpenCode2Connection;
147 + });
148 let latest: OpenCode2Connection | undefined;
149 const remember = (connection: OpenCode2Connection) =>
150 Effect.sync(() => {
packages/provider-opencode/src/server/v2/adapter.ts
+224 -195
@@ -839,11 +839,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
839
840 const hasBackground = (thread: ThreadState) => sessionsOf(thread).some(owesWork);
841
842 - const setSessionStatus = (
843 - status: OrchestrationV2ProviderSession["status"],
844 - lastError: string | null,
845 - ) =>
846 - Effect.gen(function* () {
842 + const setSessionStatus =
843 + /* Provider events include streaming deltas; avoid a span for each update. */
844 + Effect.fnUntraced(function* (
845 + status: OrchestrationV2ProviderSession["status"],
846 + lastError: string | null,
847 + ) {
848 // The session is shared by every thread on this instance and is persisted
849 // once per attached thread, so a repeat of the same state is not worth a write.
850 if (session.status === status && session.lastError === lastError) return;
@@ -3051,55 +3052,54 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3052 if (turn !== undefined) turn.before = before;
3053 });
3054
3054 - const beginTurn = (
3055 + const beginTurn = Effect.fn("OpenCode2Adapter.beginTurn")(function* (
3056 state: ThreadState,
3057 turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
3058 awaitingStart: boolean,
3058 - ) =>
3059 - Effect.gen(function* () {
3060 - const startedAt = yield* DateTime.now;
3061 - const nativeTurnId = `${state.sessionId}:attempt:${turnInput.attemptId}`;
3062 - const providerTurn: OrchestrationV2ProviderTurn = {
3063 - id: idAllocator.derive.providerTurn({ driver, nativeTurnId }),
3064 - providerThreadId: turnInput.providerThread.id,
3065 - nodeId: turnInput.rootNodeId,
3066 - runAttemptId: turnInput.attemptId,
3067 - nativeTurnRef: ref(
3068 - isContinuation(turnInput)
3069 - ? wakeTurnId(state.sessionId, turnInput.attemptId)
3070 - : turnPromptId(state.sessionId, turnInput.attemptId),
3071 - "weak",
3072 - ),
3073 - ordinal: turnInput.providerTurnOrdinal,
3074 - status: "running",
3075 - startedAt,
3076 - completedAt: null,
3077 - };
3078 - const turn = makeTurn(turnInput, providerTurn, { scope: "", awaitingStart });
3079 - if (streamFailure !== undefined) {
3080 - return yield* new ProviderAdapter.ProviderAdapterEventStreamError({
3081 - driver,
3082 - providerSessionId: input.providerSessionId,
3083 - cause: streamFailure,
3084 - });
3085 - }
3086 - state.active = turn;
3087 - yield* emitProviderTurn(state, turn, providerTurn);
3088 - state.providerThread = {
3089 - ...state.providerThread,
3090 - status: "active",
3091 - firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,
3092 - lastRunOrdinal: turnInput.runOrdinal,
3093 - updatedAt: startedAt,
3094 - };
3095 - yield* emit({
3096 - type: "provider_thread.updated",
3059 + ) {
3060 + const startedAt = yield* DateTime.now;
3061 + const nativeTurnId = `${state.sessionId}:attempt:${turnInput.attemptId}`;
3062 + const providerTurn: OrchestrationV2ProviderTurn = {
3063 + id: idAllocator.derive.providerTurn({ driver, nativeTurnId }),
3064 + providerThreadId: turnInput.providerThread.id,
3065 + nodeId: turnInput.rootNodeId,
3066 + runAttemptId: turnInput.attemptId,
3067 + nativeTurnRef: ref(
3068 + isContinuation(turnInput)
3069 + ? wakeTurnId(state.sessionId, turnInput.attemptId)
3070 + : turnPromptId(state.sessionId, turnInput.attemptId),
3071 + "weak",
3072 + ),
3073 + ordinal: turnInput.providerTurnOrdinal,
3074 + status: "running",
3075 + startedAt,
3076 + completedAt: null,
3077 + };
3078 + const turn = makeTurn(turnInput, providerTurn, { scope: "", awaitingStart });
3079 + if (streamFailure !== undefined) {
3080 + return yield* new ProviderAdapter.ProviderAdapterEventStreamError({
3081 driver,
3098 - providerThread: state.providerThread,
3082 + providerSessionId: input.providerSessionId,
3083 + cause: streamFailure,
3084 });
3100 - yield* setSessionStatus("running", null);
3101 - return turn;
3085 + }
3086 + state.active = turn;
3087 + yield* emitProviderTurn(state, turn, providerTurn);
3088 + state.providerThread = {
3089 + ...state.providerThread,
3090 + status: "active",
3091 + firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,
3092 + lastRunOrdinal: turnInput.runOrdinal,
3093 + updatedAt: startedAt,
3094 + };
3095 + yield* emit({
3096 + type: "provider_thread.updated",
3097 + driver,
3098 + providerThread: state.providerThread,
3099 });
3100 + yield* setSessionStatus("running", null);
3101 + return turn;
3102 + });
3103
3104 const replay = Effect.fnUntraced(function* (wake: Wake) {
3105 wake.dropped = true;
@@ -3344,8 +3344,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3344 selection.instanceId === instanceId
3345 ? windowOf(cwd === undefined ? session.cwd : cwd, selection.model)
3346 : undefined,
3347 - ensureThread: (threadInput) =>
3348 - Effect.gen(function* () {
3347 + ensureThread: Effect.fn("OpenCode2Adapter.ensureThread")(
3348 + function* (threadInput) {
3349 if (threadInput.existingProviderThread?.nativeThreadRef != null) {
3350 return yield* runtime.resumeThread({
3351 providerThread: threadInput.existingProviderThread,
@@ -3410,19 +3410,22 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3410 );
3411 state.policy = policy;
3412 return state.providerThread;
3413 - }).pipe(
3414 - Effect.mapError((cause) =>
3415 - isProviderAdapterError(cause)
3416 - ? cause
3417 - : new ProviderAdapter.ProviderAdapterEnsureThreadError({
3418 - driver,
3419 - threadId: threadInput.threadId,
3420 - cause,
3421 - }),
3413 + },
3414 + (effect, threadInput) =>
3415 + effect.pipe(
3416 + Effect.mapError((cause) =>
3417 + isProviderAdapterError(cause)
3418 + ? cause
3419 + : new ProviderAdapter.ProviderAdapterEnsureThreadError({
3420 + driver,
3421 + threadId: threadInput.threadId,
3422 + cause,
3423 + }),
3424 + ),
3425 ),
3423 - ),
3424 - resumeThread: (threadInput) =>
3425 - Effect.gen(function* () {
3426 + ),
3427 + resumeThread: Effect.fn("OpenCode2Adapter.resumeThread")(
3428 + function* (threadInput) {
3429 const sessionId = yield* sessionIdOf(threadInput.providerThread);
3430 if (threadInput.runtimePolicy !== undefined) {
3431 yield* readModelsOnce(threadInput.runtimePolicy.cwd);
@@ -3446,22 +3449,25 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3449 });
3450 }
3451 return state.providerThread;
3449 - }).pipe(
3450 - Effect.mapError((cause) =>
3451 - isProviderAdapterError(cause)
3452 - ? cause
3453 - : new ProviderAdapter.ProviderAdapterResumeThreadError({
3454 - driver,
3455 - providerSessionId: input.providerSessionId,
3456 - providerThreadId: threadInput.providerThread.id,
3457 - cause,
3458 - }),
3452 + },
3453 + (effect, threadInput) =>
3454 + effect.pipe(
3455 + Effect.mapError((cause) =>
3456 + isProviderAdapterError(cause)
3457 + ? cause
3458 + : new ProviderAdapter.ProviderAdapterResumeThreadError({
3459 + driver,
3460 + providerSessionId: input.providerSessionId,
3461 + providerThreadId: threadInput.providerThread.id,
3462 + cause,
3463 + }),
3464 + ),
3465 ),
3460 - ),
3466 + ),
3467 compactThread: (turnInput) =>
3468 runtime.startTurn({ ...turnInput, message: { ...turnInput.message, text: "/compact" } }),
3463 - startTurn: (turnInput) =>
3464 - Effect.gen(function* () {
3469 + startTurn: Effect.fn("OpenCode2Adapter.startTurn")(
3470 + function* (turnInput) {
3471 // Waited out before the session's gate, so a rollback or fork is not
3472 // held behind a reconnect.
3473 if (streamFailure !== undefined) {
@@ -3604,21 +3610,24 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3610 : Effect.void,
3611 ),
3612 );
3607 - }).pipe(
3608 - Effect.mapError((cause) =>
3609 - isProviderAdapterError(cause)
3610 - ? cause
3611 - : new ProviderAdapter.ProviderAdapterTurnStartError({
3612 - driver,
3613 - threadId: turnInput.threadId,
3614 - providerThreadId: turnInput.providerThread.id,
3615 - runId: turnInput.runId,
3616 - cause,
3617 - }),
3613 + },
3614 + (effect, turnInput) =>
3615 + effect.pipe(
3616 + Effect.mapError((cause) =>
3617 + isProviderAdapterError(cause)
3618 + ? cause
3619 + : new ProviderAdapter.ProviderAdapterTurnStartError({
3620 + driver,
3621 + threadId: turnInput.threadId,
3622 + providerThreadId: turnInput.providerThread.id,
3623 + runId: turnInput.runId,
3624 + cause,
3625 + }),
3626 + ),
3627 ),
3619 - ),
3620 - steerTurn: (steerInput) =>
3621 - Effect.gen(function* () {
3628 + ),
3629 + steerTurn: Effect.fn("OpenCode2Adapter.steerTurn")(
3630 + function* (steerInput) {
3631 const sessionId = yield* sessionIdOf(steerInput.providerThread);
3632 const state = threads.get(sessionId);
3633 const turn = state?.active;
@@ -3680,20 +3689,23 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3689 ),
3690 ),
3691 );
3683 - }).pipe(
3684 - Effect.mapError((cause) =>
3685 - isProviderAdapterError(cause)
3686 - ? cause
3687 - : new ProviderAdapter.ProviderAdapterSteerRunError({
3688 - driver,
3689 - providerThreadId: steerInput.providerThread.id,
3690 - providerTurnId: steerInput.providerTurnId,
3691 - cause,
3692 - }),
3692 + },
3693 + (effect, steerInput) =>
3694 + effect.pipe(
3695 + Effect.mapError((cause) =>
3696 + isProviderAdapterError(cause)
3697 + ? cause
3698 + : new ProviderAdapter.ProviderAdapterSteerRunError({
3699 + driver,
3700 + providerThreadId: steerInput.providerThread.id,
3701 + providerTurnId: steerInput.providerTurnId,
3702 + cause,
3703 + }),
3704 + ),
3705 ),
3694 - ),
3695 - interruptTurn: (interruptInput) =>
3696 - Effect.gen(function* () {
3706 + ),
3707 + interruptTurn: Effect.fn("OpenCode2Adapter.interruptTurn")(
3708 + function* (interruptInput) {
3709 const sessionId = yield* sessionIdOf(interruptInput.providerThread);
3710 const state = threads.get(sessionId);
3711 if (state === undefined) return;
@@ -3738,40 +3750,42 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3750 detail: `OpenCode session ${sessionId} had nothing running to stop`,
3751 });
3752 }
3741 - }).pipe(
3742 - Effect.mapError((cause) =>
3743 - isProviderAdapterError(cause)
3744 - ? cause
3745 - : new ProviderAdapter.ProviderAdapterInterruptError({
3746 - driver,
3747 - providerThreadId: interruptInput.providerThread.id,
3748 - providerTurnId: interruptInput.providerTurnId,
3749 - cause,
3750 - }),
3753 + },
3754 + (effect, interruptInput) =>
3755 + effect.pipe(
3756 + Effect.mapError((cause) =>
3757 + isProviderAdapterError(cause)
3758 + ? cause
3759 + : new ProviderAdapter.ProviderAdapterInterruptError({
3760 + driver,
3761 + providerThreadId: interruptInput.providerThread.id,
3762 + providerTurnId: interruptInput.providerTurnId,
3763 + cause,
3764 + }),
3765 + ),
3766 ),
3752 - ),
3753 - unloadThread: ({ providerThread }) =>
3754 - Effect.gen(function* () {
3755 - const nativeId = providerThread.nativeThreadRef?.nativeId;
3756 - const state = nativeId == null ? undefined : threads.get(nativeId);
3757 - if (
3758 - nativeId == null ||
3759 - state === undefined ||
3760 - state.active !== undefined ||
3761 - hasBackground(state)
3762 - ) {
3763 - return;
3764 - }
3765 - threads.delete(nativeId);
3766 - for (const [child, owner] of childOwners) {
3767 - if (owner !== state) continue;
3768 - childOwners.delete(child);
3769 - threads.delete(child);
3770 - }
3771 - if (state.mcp !== undefined) yield* removeMcp(state.mcp);
3772 - }),
3773 - respondToRuntimeRequest: (requestInput) =>
3774 - Effect.gen(function* () {
3767 + ),
3768 + unloadThread: Effect.fn("OpenCode2Adapter.unloadThread")(function* ({ providerThread }) {
3769 + const nativeId = providerThread.nativeThreadRef?.nativeId;
3770 + const state = nativeId == null ? undefined : threads.get(nativeId);
3771 + if (
3772 + nativeId == null ||
3773 + state === undefined ||
3774 + state.active !== undefined ||
3775 + hasBackground(state)
3776 + ) {
3777 + return;
3778 + }
3779 + threads.delete(nativeId);
3780 + for (const [child, owner] of childOwners) {
3781 + if (owner !== state) continue;
3782 + childOwners.delete(child);
3783 + threads.delete(child);
3784 + }
3785 + if (state.mcp !== undefined) yield* removeMcp(state.mcp);
3786 + }),
3787 + respondToRuntimeRequest: Effect.fn("OpenCode2Adapter.respondToRuntimeRequest")(
3788 + function* (requestInput) {
3789 const entry = pending.get(requestInput.requestId);
3790 if (entry === undefined || entry.answering) {
3791 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
@@ -3844,34 +3858,40 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3858 );
3859 yield* forgetRequest(entry);
3860 if (!delivered) yield* abandonRequest(asker, "answer not delivered");
3847 - }).pipe(
3848 - Effect.mapError((cause) =>
3849 - isProviderAdapterError(cause)
3850 - ? cause
3851 - : new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
3852 - driver,
3853 - requestId: requestInput.requestId,
3854 - cause,
3855 - }),
3861 + },
3862 + (effect, requestInput) =>
3863 + effect.pipe(
3864 + Effect.mapError((cause) =>
3865 + isProviderAdapterError(cause)
3866 + ? cause
3867 + : new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
3868 + driver,
3869 + requestId: requestInput.requestId,
3870 + cause,
3871 + }),
3872 + ),
3873 ),
3857 - ),
3858 - readThreadSnapshot: ({ providerThread }) =>
3859 - Effect.gen(function* () {
3874 + ),
3875 + readThreadSnapshot: Effect.fn("OpenCode2Adapter.readThreadSnapshot")(
3876 + function* ({ providerThread }) {
3877 const sessionId = yield* sessionIdOf(providerThread);
3878 return yield* snapshotOf(providerThread, sessionId);
3862 - }).pipe(
3863 - Effect.mapError((cause) =>
3864 - isProviderAdapterError(cause)
3865 - ? cause
3866 - : new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
3867 - driver,
3868 - providerThreadId: providerThread.id,
3869 - cause,
3870 - }),
3879 + },
3880 + (effect, { providerThread }) =>
3881 + effect.pipe(
3882 + Effect.mapError((cause) =>
3883 + isProviderAdapterError(cause)
3884 + ? cause
3885 + : new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
3886 + driver,
3887 + providerThreadId: providerThread.id,
3888 + cause,
3889 + }),
3890 + ),
3891 ),
3872 - ),
3873 - rollbackThread: (rollbackInput) =>
3874 - Effect.gen(function* () {
3892 + ),
3893 + rollbackThread: Effect.fn("OpenCode2Adapter.rollbackThread")(
3894 + function* (rollbackInput) {
3895 const { providerThread, target } = rollbackInput;
3896 const sessionId = yield* sessionIdOf(providerThread);
3897 yield* ensureQuiet(sessionId, "roll back");
@@ -3904,21 +3924,24 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3924 );
3925 for (const turn of snapshot.providerTurns) kept.set(turn.id, turn);
3926 return { ...snapshot, providerTurns: [...kept.values()] };
3907 - }).pipe(
3908 - exclusive(rollbackInput.providerThread),
3909 - Effect.mapError((cause) =>
3910 - isProviderAdapterError(cause)
3911 - ? cause
3912 - : new ProviderAdapter.ProviderAdapterRollbackThreadError({
3913 - driver,
3914 - providerThreadId: rollbackInput.providerThread.id,
3915 - checkpointId: rollbackInput.target.checkpointId,
3916 - cause,
3917 - }),
3927 + },
3928 + (effect, rollbackInput) =>
3929 + effect.pipe(
3930 + exclusive(rollbackInput.providerThread),
3931 + Effect.mapError((cause) =>
3932 + isProviderAdapterError(cause)
3933 + ? cause
3934 + : new ProviderAdapter.ProviderAdapterRollbackThreadError({
3935 + driver,
3936 + providerThreadId: rollbackInput.providerThread.id,
3937 + checkpointId: rollbackInput.target.checkpointId,
3938 + cause,
3939 + }),
3940 + ),
3941 ),
3919 - ),
3920 - forkThread: (forkInput) =>
3921 - Effect.gen(function* () {
3942 + ),
3943 + forkThread: Effect.fn("OpenCode2Adapter.forkThread")(
3944 + function* (forkInput) {
3945 const source = forkInput.sourceProviderThread;
3946 const sourceId = yield* sessionIdOf(source);
3947 // 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
4006 });
4007 }
4008 return state.providerThread;
3986 - }).pipe(
3987 - exclusive(forkInput.sourceProviderThread),
3988 - Effect.mapError((cause) =>
3989 - isProviderAdapterError(cause)
3990 - ? cause
3991 - : new ProviderAdapter.ProviderAdapterForkThreadError({
3992 - driver,
3993 - providerThreadId: forkInput.sourceProviderThread.id,
3994 - cause,
3995 - }),
4009 + },
4010 + (effect, forkInput) =>
4011 + effect.pipe(
4012 + exclusive(forkInput.sourceProviderThread),
4013 + Effect.mapError((cause) =>
4014 + isProviderAdapterError(cause)
4015 + ? cause
4016 + : new ProviderAdapter.ProviderAdapterForkThreadError({
4017 + driver,
4018 + providerThreadId: forkInput.sourceProviderThread.id,
4019 + cause,
4020 + }),
4021 + ),
4022 ),
3997 - ),
4023 + ),
4024 };
4025 return runtime;
4026 });
@@ -4006,21 +4032,24 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
4032 planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),
4033 // The session borrows the instance's server for as long as it is open, so a
4034 // spawned server is not idle-stopped under a long tool call.
4009 - openSession: (input) =>
4010 - Effect.gen(function* () {
4035 + openSession: Effect.fn("OpenCode2Adapter.borrowAndOpenSession")(
4036 + function* (input) {
4037 const scope = yield* Scope.make();
4038 yield* Effect.addFinalizer((exit) => Scope.close(scope, exit));
4039 const connection = yield* borrow.pipe(Effect.provideService(Scope.Scope, scope));
4040 return yield* openSession(input, { connection, scope });
4015 - }).pipe(
4016 - Effect.mapError(
4017 - (cause) =>
4018 - new ProviderAdapter.ProviderAdapterOpenSessionError({
4019 - driver,
4020 - providerSessionId: input.providerSessionId,
4021 - cause,
4022 - }),
4041 + },
4042 + (effect, input) =>
4043 + effect.pipe(
4044 + Effect.mapError(
4045 + (cause) =>
4046 + new ProviderAdapter.ProviderAdapterOpenSessionError({
4047 + driver,
4048 + providerSessionId: input.providerSessionId,
4049 + cause,
4050 + }),
4051 + ),
4052 ),
4024 - ),
4053 + ),
4054 });
4055 });
packages/provider-opencode/src/server/v2/textGeneration.ts
+136 -137
@@ -32,149 +32,148 @@ type Outcome =
32 | { readonly _tag: "text"; readonly text: string }
33 | { readonly _tag: "failed"; readonly detail: string; readonly cause?: unknown };
34
35 -const runOnServer = (
35 +const runOnServer = Effect.fn("Opencode2TextGeneration.runOnServer")(function* (
36 connection: OpenCode2Server.OpenCode2Connection,
37 input: TextGenerationOperations.Request<Schema.Top>,
38 -) =>
39 - Effect.gen(function* () {
40 - const { resolveAttachmentPath } = yield* ProviderHost.ProviderHost;
41 - const { client } = connection;
42 - const parsed = OpenCodeRuntime.parseOpenCodeModelSlug(input.modelSelection.model);
43 - if (parsed === null) {
44 - return yield* new TextGenerationError({
45 - operation: input.operation,
46 - detail: "OpenCode model selection must use the 'provider/model' format.",
47 - });
48 - }
49 - const variant = getModelSelectionStringOptionValue(input.modelSelection, "variant");
50 - const outcome = yield* Deferred.make<Outcome>();
51 - let sessionId: string | undefined;
52 - const texts = new Map<string, string>();
53 - // Subscribed first: the stream is volatile, and the reply arrives on it.
54 - const events = yield* connection.events;
55 - yield* events.pipe(
56 - Stream.runForEach((event) => {
57 - // An execution end a newer server sent in a shape this build cannot
58 - // read still ends the generation, as it ends a turn in the adapter.
59 - if (event.type === "unreadable.execution.ended") {
60 - if (event.sessionID !== sessionId) return Effect.void;
61 - return Deferred.succeed(
62 - outcome,
63 - event.executionType === "session.execution.succeeded"
64 - ? { _tag: "text", text: [...texts.values()].join("\n").trim() }
65 - : {
66 - _tag: "failed",
67 - detail: "OpenCode ended the generation in a way this version cannot read.",
68 - cause: event,
69 - },
70 - );
71 - }
72 - if (
73 - sessionId === undefined ||
74 - !("data" in event) ||
75 - !("sessionID" in event.data) ||
76 - event.data.sessionID !== sessionId
77 - ) {
38 +) {
39 + const { resolveAttachmentPath } = yield* ProviderHost.ProviderHost;
40 + const { client } = connection;
41 + const parsed = OpenCodeRuntime.parseOpenCodeModelSlug(input.modelSelection.model);
42 + if (parsed === null) {
43 + return yield* new TextGenerationError({
44 + operation: input.operation,
45 + detail: "OpenCode model selection must use the 'provider/model' format.",
46 + });
47 + }
48 + const variant = getModelSelectionStringOptionValue(input.modelSelection, "variant");
49 + const outcome = yield* Deferred.make<Outcome>();
50 + let sessionId: string | undefined;
51 + const texts = new Map<string, string>();
52 + // Subscribed first: the stream is volatile, and the reply arrives on it.
53 + const events = yield* connection.events;
54 + yield* events.pipe(
55 + Stream.runForEach((event) => {
56 + // An execution end a newer server sent in a shape this build cannot
57 + // read still ends the generation, as it ends a turn in the adapter.
58 + if (event.type === "unreadable.execution.ended") {
59 + if (event.sessionID !== sessionId) return Effect.void;
60 + return Deferred.succeed(
61 + outcome,
62 + event.executionType === "session.execution.succeeded"
63 + ? { _tag: "text", text: [...texts.values()].join("\n").trim() }
64 + : {
65 + _tag: "failed",
66 + detail: "OpenCode ended the generation in a way this version cannot read.",
67 + cause: event,
68 + },
69 + );
70 + }
71 + if (
72 + sessionId === undefined ||
73 + !("data" in event) ||
74 + !("sessionID" in event.data) ||
75 + event.data.sessionID !== sessionId
76 + ) {
77 + return Effect.void;
78 + }
79 + switch (event.type) {
80 + case "session.text.ended":
81 + texts.set(`${event.data.assistantMessageID}:${event.data.ordinal}`, event.data.text);
82 return Effect.void;
79 - }
80 - switch (event.type) {
81 - case "session.text.ended":
82 - texts.set(`${event.data.assistantMessageID}:${event.data.ordinal}`, event.data.text);
83 - return Effect.void;
84 - case "permission.asked":
85 - return client.permission
86 - .reply({
87 - sessionID: event.data.sessionID,
88 - requestID: event.data.id,
89 - decision: "reject",
90 - message: "Tools are not available while generating text.",
91 - })
92 - .pipe(Effect.ignore({ log: true }));
93 - case "session.execution.succeeded":
94 - return Deferred.succeed(outcome, {
95 - _tag: "text",
96 - text: [...texts.values()].join("\n").trim(),
97 - });
98 - case "session.execution.failed":
99 - return Deferred.succeed(outcome, {
100 - _tag: "failed",
101 - detail: "OpenCode could not generate the text.",
102 - cause: event.data.error,
103 - });
104 - case "session.execution.interrupted":
105 - return Deferred.succeed(outcome, {
106 - _tag: "failed",
107 - detail: "OpenCode stopped the generation.",
108 - });
109 - default:
110 - return Effect.void;
111 - }
112 - }),
113 - // The reply only arrives on this stream, so a lost stream ends the wait.
114 - Effect.exit,
115 - Effect.flatMap((exit) =>
116 - Deferred.succeed(outcome, {
117 - _tag: "failed",
118 - detail: "The OpenCode event stream was lost.",
119 - cause: exit,
120 - }),
121 - ),
122 - Effect.forkScoped,
123 - );
124 - const session = yield* client.session.create({
125 - title: `T3 Code ${input.operation}`,
126 - location: Location.PublicRef.make({ directory: AbsolutePath.make(input.cwd) }),
127 - model: Model.Ref.make({
128 - providerID: Provider.ID.make(parsed.providerID),
129 - id: Model.ID.make(parsed.modelID),
130 - ...(variant === undefined ? {} : { variant: Model.VariantID.make(variant) }),
83 + case "permission.asked":
84 + return client.permission
85 + .reply({
86 + sessionID: event.data.sessionID,
87 + requestID: event.data.id,
88 + decision: "reject",
89 + message: "Tools are not available while generating text.",
90 + })
91 + .pipe(Effect.ignore({ log: true }));
92 + case "session.execution.succeeded":
93 + return Deferred.succeed(outcome, {
94 + _tag: "text",
95 + text: [...texts.values()].join("\n").trim(),
96 + });
97 + case "session.execution.failed":
98 + return Deferred.succeed(outcome, {
99 + _tag: "failed",
100 + detail: "OpenCode could not generate the text.",
101 + cause: event.data.error,
102 + });
103 + case "session.execution.interrupted":
104 + return Deferred.succeed(outcome, {
105 + _tag: "failed",
106 + detail: "OpenCode stopped the generation.",
107 + });
108 + default:
109 + return Effect.void;
110 + }
111 + }),
112 + // The reply only arrives on this stream, so a lost stream ends the wait.
113 + Effect.exit,
114 + Effect.flatMap((exit) =>
115 + Deferred.succeed(outcome, {
116 + _tag: "failed",
117 + detail: "The OpenCode event stream was lost.",
118 + cause: exit,
119 }),
132 - permissions: GENERATION_PERMISSIONS,
133 - });
134 - sessionId = session.id;
135 - yield* Effect.addFinalizer(() =>
136 - client.session
137 - .remove({ sessionID: session.id })
138 - .pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })),
139 - );
140 - const images = (input.attachments ?? []).flatMap((attachment) => {
141 - if (attachment.type !== "image") return [];
142 - const path = resolveAttachmentPath(attachment);
143 - return path === null ? [] : [{ uri: `file://${path}`, name: attachment.name }];
120 + ),
121 + Effect.forkScoped,
122 + );
123 + const session = yield* client.session.create({
124 + title: `T3 Code ${input.operation}`,
125 + location: Location.PublicRef.make({ directory: AbsolutePath.make(input.cwd) }),
126 + model: Model.Ref.make({
127 + providerID: Provider.ID.make(parsed.providerID),
128 + id: Model.ID.make(parsed.modelID),
129 + ...(variant === undefined ? {} : { variant: Model.VariantID.make(variant) }),
130 + }),
131 + permissions: GENERATION_PERMISSIONS,
132 + });
133 + sessionId = session.id;
134 + yield* Effect.addFinalizer(() =>
135 + client.session
136 + .remove({ sessionID: session.id })
137 + .pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })),
138 + );
139 + const images = (input.attachments ?? []).flatMap((attachment) => {
140 + if (attachment.type !== "image") return [];
141 + const path = resolveAttachmentPath(attachment);
142 + return path === null ? [] : [{ uri: `file://${path}`, name: attachment.name }];
143 + });
144 + yield* client.session.prompt({
145 + sessionID: session.id,
146 + text: input.prompt,
147 + ...(images.length === 0 ? {} : { files: images }),
148 + });
149 + const result = yield* Deferred.await(outcome).pipe(
150 + Effect.timeoutOrElse({
151 + duration: GENERATION_TIMEOUT,
152 + orElse: () =>
153 + client.session.interrupt({ sessionID: Session.ID.make(session.id) }).pipe(
154 + Effect.ignore,
155 + Effect.as<Outcome>({
156 + _tag: "failed",
157 + detail: "OpenCode did not finish generating in time.",
158 + }),
159 + ),
160 + }),
161 + );
162 + if (result._tag === "failed") {
163 + return yield* new TextGenerationError({
164 + operation: input.operation,
165 + detail: result.detail,
166 + ...(result.cause === undefined ? {} : { cause: result.cause }),
167 });
145 - yield* client.session.prompt({
146 - sessionID: session.id,
147 - text: input.prompt,
148 - ...(images.length === 0 ? {} : { files: images }),
168 + }
169 + if (result.text.length === 0) {
170 + return yield* new TextGenerationError({
171 + operation: input.operation,
172 + detail: "OpenCode returned empty output.",
173 });
150 - const result = yield* Deferred.await(outcome).pipe(
151 - Effect.timeoutOrElse({
152 - duration: GENERATION_TIMEOUT,
153 - orElse: () =>
154 - client.session.interrupt({ sessionID: Session.ID.make(session.id) }).pipe(
155 - Effect.ignore,
156 - Effect.as<Outcome>({
157 - _tag: "failed",
158 - detail: "OpenCode did not finish generating in time.",
159 - }),
160 - ),
161 - }),
162 - );
163 - if (result._tag === "failed") {
164 - return yield* new TextGenerationError({
165 - operation: input.operation,
166 - detail: result.detail,
167 - ...(result.cause === undefined ? {} : { cause: result.cause }),
168 - });
169 - }
170 - if (result.text.length === 0) {
171 - return yield* new TextGenerationError({
172 - operation: input.operation,
173 - detail: "OpenCode returned empty output.",
174 - });
175 - }
176 - return result.text;
177 - }).pipe(Effect.scoped);
174 + }
175 + return result.text;
176 +}, Effect.scoped);
177
178 export const make = Effect.fn("OpenCode2TextGeneration.make")(function* () {
179 const server = yield* OpenCode2Server.OpenCode2Server;
packages/provider-pi/src/server/adapter.ts
+175 -142
@@ -582,11 +582,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
582 const emit = (event: ProviderAdapter.ProviderAdapterV2Event) =>
583 Queue.offer(events, event).pipe(Effect.asVoid);
584
585 - const updateProviderSession = (
586 - status: OrchestrationV2ProviderSession["status"],
587 - lastError: string | null = sessionEntity.lastError,
588 - ) =>
589 - Effect.gen(function* () {
585 + const updateProviderSession =
586 + /* Provider events include streaming deltas; avoid a span for each update. */
587 + Effect.fnUntraced(function* (
588 + status: OrchestrationV2ProviderSession["status"],
589 + lastError: string | null = sessionEntity.lastError,
590 + ) {
591 const updatedAt = yield* DateTime.now;
592 sessionEntity = { ...sessionEntity, status, lastError, updatedAt };
593 yield* emit({
@@ -596,12 +597,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
597 });
598 });
599
599 - const updateProviderThread = (
600 - state: PiThreadState,
601 - patch: Partial<OrchestrationV2ProviderThread>,
602 - retainedNativeTurnIds?: ReadonlyArray<string>,
603 - ) =>
604 - Effect.gen(function* () {
600 + const updateProviderThread =
601 + /* Provider events include streaming deltas; avoid a span for each update. */
602 + Effect.fnUntraced(function* (
603 + state: PiThreadState,
604 + patch: Partial<OrchestrationV2ProviderThread>,
605 + retainedNativeTurnIds?: ReadonlyArray<string>,
606 + ) {
607 const updatedAt = yield* DateTime.now;
608 state.providerThread = { ...state.providerThread, ...patch, updatedAt };
609 yield* emit({
@@ -692,8 +694,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
694 /**
695 * Pi attaches the current message's cumulative usage to every streaming update (0.84.2+).
696 */
695 - const reportLiveUsage = (turn: ActivePiTurn, usage: unknown) =>
696 - Effect.gen(function* () {
697 + const reportLiveUsage =
698 + /* Provider events include streaming deltas; avoid a span for each update. */
699 + Effect.fnUntraced(function* (turn: ActivePiTurn, usage: unknown) {
700 const usedTokens = nonNegativeInteger(usage, "totalTokens");
701 if (
702 usedTokens === undefined ||
@@ -849,8 +852,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
852 });
853 });
854
852 - const emitStreamItem = (turn: ActivePiTurn, item: PiStreamItemState, streaming: boolean) =>
853 - Effect.gen(function* () {
855 + const emitStreamItem =
856 + /* Provider events include streaming deltas; avoid a span for each update. */
857 + Effect.fnUntraced(function* (
858 + turn: ActivePiTurn,
859 + item: PiStreamItemState,
860 + streaming: boolean,
861 + ) {
862 const emittedAt = yield* DateTime.now;
863 const base = baseItemFields(turn, item.nativeItemId, item.startedAt, emittedAt);
864 yield* emitItemNode(
@@ -918,8 +926,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
926 });
927 });
928
921 - const scheduleStreamFlush = (turn: ActivePiTurn, item: PiStreamItemState) =>
922 - Effect.gen(function* () {
929 + const scheduleStreamFlush =
930 + /* Provider events include streaming deltas; avoid a span for each update. */
931 + Effect.fnUntraced(function* (turn: ActivePiTurn, item: PiStreamItemState) {
932 if (item.flushScheduled || item.completed) return;
933 item.flushScheduled = true;
934 yield* Effect.sleep(Duration.millis(STREAM_FLUSH_MS)).pipe(
@@ -1159,52 +1168,55 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
1168 }
1169 });
1170
1162 - const cancelPrompt = (pending: PendingPiPrompt, resolvedAt: DateTime.Utc) =>
1163 - Effect.gen(function* () {
1164 - if (pending.expirationFiber !== null) yield* Fiber.interrupt(pending.expirationFiber);
1165 - yield* connection
1166 - .send({
1167 - type: "extension_ui_response",
1168 - id: pending.nativeRequestId,
1169 - cancelled: true,
1170 - })
1171 - .pipe(Effect.ignore);
1172 - pending.runtimeRequest = {
1173 - ...pending.runtimeRequest,
1171 + const cancelPrompt = Effect.fn("PiAdapter.cancelPrompt")(function* (
1172 + pending: PendingPiPrompt,
1173 + resolvedAt: DateTime.Utc,
1174 + ) {
1175 + if (pending.expirationFiber !== null) yield* Fiber.interrupt(pending.expirationFiber);
1176 + yield* connection
1177 + .send({
1178 + type: "extension_ui_response",
1179 + id: pending.nativeRequestId,
1180 + cancelled: true,
1181 + })
1182 + .pipe(Effect.ignore);
1183 + pending.runtimeRequest = {
1184 + ...pending.runtimeRequest,
1185 + status: "cancelled",
1186 + resolvedAt,
1187 + };
1188 + yield* emit({
1189 + type: "runtime_request.updated",
1190 + driver: PI_PROVIDER,
1191 + threadId: pending.node.threadId,
1192 + runtimeRequest: pending.runtimeRequest,
1193 + });
1194 + yield* emit({
1195 + type: "node.updated",
1196 + driver: PI_PROVIDER,
1197 + node: { ...pending.node, status: "cancelled", completedAt: resolvedAt },
1198 + });
1199 + yield* emit({
1200 + type: "turn_item.updated",
1201 + driver: PI_PROVIDER,
1202 + turnItem: {
1203 + ...pending.turnItem,
1204 status: "cancelled",
1175 - resolvedAt,
1176 - };
1177 - yield* emit({
1178 - type: "runtime_request.updated",
1179 - driver: PI_PROVIDER,
1180 - threadId: pending.node.threadId,
1181 - runtimeRequest: pending.runtimeRequest,
1182 - });
1183 - yield* emit({
1184 - type: "node.updated",
1185 - driver: PI_PROVIDER,
1186 - node: { ...pending.node, status: "cancelled", completedAt: resolvedAt },
1187 - });
1188 - yield* emit({
1189 - type: "turn_item.updated",
1190 - driver: PI_PROVIDER,
1191 - turnItem: {
1192 - ...pending.turnItem,
1193 - status: "cancelled",
1194 - completedAt: resolvedAt,
1195 - updatedAt: resolvedAt,
1196 - },
1197 - });
1205 + completedAt: resolvedAt,
1206 + updatedAt: resolvedAt,
1207 + },
1208 });
1209 + });
1210
1200 - const cancelPendingPrompts = (resolvedAt: DateTime.Utc) =>
1201 - Effect.gen(function* () {
1202 - const pending = Array.from(pendingPrompts.values());
1203 - pendingPrompts.clear();
1204 - yield* Effect.forEach(pending, (prompt) => cancelPrompt(prompt, resolvedAt), {
1205 - discard: true,
1206 - });
1211 + const cancelPendingPrompts = Effect.fn("PiAdapter.cancelPendingPrompts")(function* (
1212 + resolvedAt: DateTime.Utc,
1213 + ) {
1214 + const pending = Array.from(pendingPrompts.values());
1215 + pendingPrompts.clear();
1216 + yield* Effect.forEach(pending, (prompt) => cancelPrompt(prompt, resolvedAt), {
1217 + discard: true,
1218 });
1219 + });
1220
1221 const handleExtensionUiRequest = Effect.fnUntraced(function* (event: PiRpcRecord) {
1222 const method = recordString(event, "method");
@@ -2409,8 +2421,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2421 ...turnInput,
2422 message: { ...turnInput.message, text: "/compact" },
2423 }),
2412 - startTurn: (turnInput) =>
2413 - Effect.gen(function* () {
2424 + startTurn: Effect.fn("PiAdapter.startTurn")(
2425 + function* (turnInput) {
2426 if (rollbackBarrier !== null)
2427 return yield* protocolError("Cannot start a Pi turn during rollback");
2428 const state = threadState;
@@ -2585,20 +2597,23 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2597 // and extension commands may block on user dialogs indefinitely.
2598 // Rejections therefore return later as id-less response records
2599 // handled by the event pump.
2588 - }).pipe(
2589 - Effect.mapError(
2590 - (cause) =>
2591 - new ProviderAdapter.ProviderAdapterTurnStartError({
2592 - driver: PI_PROVIDER,
2593 - threadId: turnInput.threadId,
2594 - providerThreadId: turnInput.providerThread.id,
2595 - runId: turnInput.runId,
2596 - cause,
2597 - }),
2600 + },
2601 + (effect, turnInput) =>
2602 + effect.pipe(
2603 + Effect.mapError(
2604 + (cause) =>
2605 + new ProviderAdapter.ProviderAdapterTurnStartError({
2606 + driver: PI_PROVIDER,
2607 + threadId: turnInput.threadId,
2608 + providerThreadId: turnInput.providerThread.id,
2609 + runId: turnInput.runId,
2610 + cause,
2611 + }),
2612 + ),
2613 ),
2599 - ),
2600 - steerTurn: (steerInput: ProviderAdapter.ProviderAdapterV2SteerInput) =>
2601 - Effect.gen(function* () {
2614 + ),
2615 + steerTurn: Effect.fn("PiAdapter.steerTurn")(
2616 + function* (steerInput: ProviderAdapter.ProviderAdapterV2SteerInput) {
2617 const turn = threadState?.activeTurn ?? null;
2618 if (turn === null || turn.providerTurn.id !== steerInput.providerTurnId) {
2619 return yield* protocolError(`Pi turn ${steerInput.providerTurnId} is not active`);
@@ -2645,19 +2660,22 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2660 turn.settleProbeGeneration += 1;
2661 }),
2662 );
2648 - }).pipe(
2649 - Effect.mapError(
2650 - (cause) =>
2651 - new ProviderAdapter.ProviderAdapterSteerRunError({
2652 - driver: PI_PROVIDER,
2653 - providerThreadId: steerInput.providerThread.id,
2654 - providerTurnId: steerInput.providerTurnId,
2655 - cause,
2656 - }),
2663 + },
2664 + (effect, steerInput) =>
2665 + effect.pipe(
2666 + Effect.mapError(
2667 + (cause) =>
2668 + new ProviderAdapter.ProviderAdapterSteerRunError({
2669 + driver: PI_PROVIDER,
2670 + providerThreadId: steerInput.providerThread.id,
2671 + providerTurnId: steerInput.providerTurnId,
2672 + cause,
2673 + }),
2674 + ),
2675 ),
2658 - ),
2659 - interruptTurn: (interruptInput) =>
2660 - Effect.gen(function* () {
2676 + ),
2677 + interruptTurn: Effect.fn("PiAdapter.interruptTurn")(
2678 + function* (interruptInput) {
2679 const turn = threadState?.activeTurn ?? null;
2680 if (turn === null && interruptInput.requestRuntimeRestart === true) {
2681 if (pendingWake !== null)
@@ -2697,19 +2715,22 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2715 yield* request({ type: "abort" }).pipe(
2716 Effect.tapError(() => Effect.sync(() => (turn.interrupted = false))),
2717 );
2700 - }).pipe(
2701 - Effect.mapError(
2702 - (cause) =>
2703 - new ProviderAdapter.ProviderAdapterInterruptError({
2704 - driver: PI_PROVIDER,
2705 - providerThreadId: interruptInput.providerThread.id,
2706 - providerTurnId: interruptInput.providerTurnId,
2707 - cause,
2708 - }),
2718 + },
2719 + (effect, interruptInput) =>
2720 + effect.pipe(
2721 + Effect.mapError(
2722 + (cause) =>
2723 + new ProviderAdapter.ProviderAdapterInterruptError({
2724 + driver: PI_PROVIDER,
2725 + providerThreadId: interruptInput.providerThread.id,
2726 + providerTurnId: interruptInput.providerTurnId,
2727 + cause,
2728 + }),
2729 + ),
2730 ),
2710 - ),
2711 - respondToRuntimeRequest: (requestInput) =>
2712 - Effect.gen(function* () {
2731 + ),
2732 + respondToRuntimeRequest: Effect.fn("PiAdapter.respondToRuntimeRequest")(
2733 + function* (requestInput) {
2734 const pending = pendingPrompts.get(String(requestInput.requestId));
2735 if (pending === undefined) {
2736 return yield* protocolError(
@@ -2765,19 +2786,22 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2786 updatedAt: resolvedAt,
2787 },
2788 });
2768 - }).pipe(
2769 - sessionEventPermit.withPermits(1),
2770 - Effect.mapError(
2771 - (cause) =>
2772 - new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
2773 - driver: PI_PROVIDER,
2774 - requestId: requestInput.requestId,
2775 - cause,
2776 - }),
2789 + },
2790 + (effect, requestInput) =>
2791 + effect.pipe(
2792 + sessionEventPermit.withPermits(1),
2793 + Effect.mapError(
2794 + (cause) =>
2795 + new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
2796 + driver: PI_PROVIDER,
2797 + requestId: requestInput.requestId,
2798 + cause,
2799 + }),
2800 + ),
2801 ),
2778 - ),
2779 - readThreadSnapshot: (snapshotInput) =>
2780 - Effect.gen(function* () {
2802 + ),
2803 + readThreadSnapshot: Effect.fn("PiAdapter.readThreadSnapshot")(
2804 + function* (snapshotInput) {
2805 const state = threadState;
2806 const boundNativeId = state?.providerThread.nativeThreadRef?.nativeId;
2807 const wantedNativeId = snapshotInput.providerThread.nativeThreadRef?.nativeId;
@@ -2830,18 +2854,21 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2854 messages,
2855 runtimeRequests: [],
2856 };
2833 - }).pipe(
2834 - Effect.mapError(
2835 - (cause) =>
2836 - new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
2837 - driver: PI_PROVIDER,
2838 - providerThreadId: snapshotInput.providerThread.id,
2839 - cause,
2840 - }),
2857 + },
2858 + (effect, snapshotInput) =>
2859 + effect.pipe(
2860 + Effect.mapError(
2861 + (cause) =>
2862 + new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
2863 + driver: PI_PROVIDER,
2864 + providerThreadId: snapshotInput.providerThread.id,
2865 + cause,
2866 + }),
2867 + ),
2868 ),
2842 - ),
2843 - rollbackThread: (rollbackInput) =>
2844 - Effect.gen(function* () {
2869 + ),
2870 + rollbackThread: Effect.fn("PiAdapter.rollbackThread")(
2871 + function* (rollbackInput) {
2872 const state = threadState;
2873 if (state === null) {
2874 return yield* protocolError("Pi session has no registered thread");
@@ -2952,19 +2979,22 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
2979 if (rollbackBarrier === barrier) rollbackBarrier = null;
2980 }),
2981 );
2955 - }).pipe(
2956 - Effect.mapError(
2957 - (cause) =>
2958 - new ProviderAdapter.ProviderAdapterRollbackThreadError({
2959 - driver: PI_PROVIDER,
2960 - providerThreadId: rollbackInput.providerThread.id,
2961 - checkpointId: rollbackInput.target.checkpointId,
2962 - cause,
2963 - }),
2982 + },
2983 + (effect, rollbackInput) =>
2984 + effect.pipe(
2985 + Effect.mapError(
2986 + (cause) =>
2987 + new ProviderAdapter.ProviderAdapterRollbackThreadError({
2988 + driver: PI_PROVIDER,
2989 + providerThreadId: rollbackInput.providerThread.id,
2990 + checkpointId: rollbackInput.target.checkpointId,
2991 + cause,
2992 + }),
2993 + ),
2994 ),
2965 - ),
2966 - forkThread: (forkInput) =>
2967 - Effect.gen(function* () {
2995 + ),
2996 + forkThread: Effect.fn("PiAdapter.forkThread")(
2997 + function* (forkInput) {
2998 if (threadState?.activeTurn != null) {
2999 return yield* protocolError("Cannot fork while a Pi turn is active");
3000 }
@@ -3063,16 +3093,19 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
3093 },
3094 false,
3095 );
3066 - }).pipe(
3067 - Effect.mapError(
3068 - (cause) =>
3069 - new ProviderAdapter.ProviderAdapterForkThreadError({
3070 - driver: PI_PROVIDER,
3071 - providerThreadId: forkInput.sourceProviderThread.id,
3072 - cause,
3073 - }),
3096 + },
3097 + (effect, forkInput) =>
3098 + effect.pipe(
3099 + Effect.mapError(
3100 + (cause) =>
3101 + new ProviderAdapter.ProviderAdapterForkThreadError({
3102 + driver: PI_PROVIDER,
3103 + providerThreadId: forkInput.sourceProviderThread.id,
3104 + cause,
3105 + }),
3106 + ),
3107 ),
3075 - ),
3108 + ),
3109 };
3110 return runtime;
3111 }),
packages/provider-pi/src/server/driver.ts
+125 -119
@@ -85,131 +85,137 @@ export const PiDriver: ProviderDriver<PiSettings, PiDriverEnv, Path.Path> = {
85 usage: piUsageReader,
86 configSchema: PiSettings,
87 defaultConfig: (): PiSettings => decodePiSettings({}),
88 - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
89 - Effect.gen(function* () {
90 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
91 - const fileSystem = yield* FileSystem.FileSystem;
92 - const pathService = yield* Path.Path;
93 - const httpClient = yield* HttpClient.HttpClient;
94 - const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
95 - const host = yield* ProviderHost.ProviderHost;
96 - const { cwd } = host.paths;
97 - const processEnv = yield* mergeProviderInstanceEnvironment(environment);
98 - const continuationIdentity = defaultProviderContinuationIdentity({
99 - driverKind: DRIVER_KIND,
100 - instanceId,
101 - });
102 - const stampIdentity = withInstanceIdentity({
103 - instanceId,
104 - displayName,
105 - accentColor,
106 - continuationGroupKey: continuationIdentity.continuationKey,
107 - });
108 - const effectiveConfig = { ...config, enabled } satisfies PiSettings;
109 - const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
110 - resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
111 - binaryPath: effectiveConfig.binaryPath,
112 - env: processEnv,
113 - }).pipe(
114 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
115 - Effect.provideService(FileSystem.FileSystem, fileSystem),
116 - Effect.provideService(Path.Path, pathService),
117 - ),
118 - );
119 -
120 - const orchestrationAdapter = yield* PiAdapterV2Driver.create({
121 - instanceId,
122 - displayName,
123 - accentColor,
124 - environment,
125 - enabled,
126 - config,
88 + create: Effect.fn("PiDriver.create")(function* ({
89 + instanceId,
90 + displayName,
91 + accentColor,
92 + environment,
93 + enabled,
94 + config,
95 + }) {
96 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
97 + const fileSystem = yield* FileSystem.FileSystem;
98 + const pathService = yield* Path.Path;
99 + const httpClient = yield* HttpClient.HttpClient;
100 + const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
101 + const host = yield* ProviderHost.ProviderHost;
102 + const { cwd } = host.paths;
103 + const processEnv = yield* mergeProviderInstanceEnvironment(environment);
104 + const continuationIdentity = defaultProviderContinuationIdentity({
105 + driverKind: DRIVER_KIND,
106 + instanceId,
107 + });
108 + const stampIdentity = withInstanceIdentity({
109 + instanceId,
110 + displayName,
111 + accentColor,
112 + continuationGroupKey: continuationIdentity.continuationKey,
113 + });
114 + const effectiveConfig = { ...config, enabled } satisfies PiSettings;
115 + const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
116 + resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
117 + binaryPath: effectiveConfig.binaryPath,
118 + env: processEnv,
119 }).pipe(
128 - Effect.mapError(
129 - (cause) =>
130 - new ProviderDriverError({
131 - driver: DRIVER_KIND,
132 - instanceId,
133 - detail: "Failed to build Pi orchestration adapter.",
134 - cause,
135 - }),
136 - ),
137 - );
138 - const textGeneration = yield* makePiTextGeneration(effectiveConfig, processEnv);
139 -
140 - const checkProvider = checkPiProviderStatus(effectiveConfig, processEnv, cwd).pipe(
141 - Effect.map(stampIdentity),
120 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
143 - );
121 + Effect.provideService(FileSystem.FileSystem, fileSystem),
122 + Effect.provideService(Path.Path, pathService),
123 + ),
124 + );
125
145 - const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
146 - const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<PiSettings>>({
147 - resolveMaintenance,
148 - getSettings: snapshotSettings.getSettings,
149 - streamSettings: snapshotSettings.streamSettings,
150 - haveSettingsChanged: haveProviderSnapshotSettingsChanged,
151 - initialSnapshot: (settings) =>
152 - buildInitialPiProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
153 - checkProvider,
154 - enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
155 - resolveMaintenance().pipe(
156 - Effect.flatMap((maintenanceCapabilities) =>
157 - enrichPiSnapshot({
158 - snapshot: currentSnapshot,
159 - maintenanceCapabilities,
160 - enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
161 - publishSnapshot,
162 - }),
163 - ),
164 - Effect.provideService(HttpClient.HttpClient, httpClient),
165 - Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
166 - ),
167 - }).pipe(
168 - Effect.mapError(
169 - (cause) =>
170 - new ProviderDriverError({
171 - driver: DRIVER_KIND,
172 - instanceId,
173 - detail: "Failed to build Pi snapshot.",
174 - cause,
126 + const orchestrationAdapter = yield* PiAdapterV2Driver.create({
127 + instanceId,
128 + displayName,
129 + accentColor,
130 + environment,
131 + enabled,
132 + config,
133 + }).pipe(
134 + Effect.mapError(
135 + (cause) =>
136 + new ProviderDriverError({
137 + driver: DRIVER_KIND,
138 + instanceId,
139 + detail: "Failed to build Pi orchestration adapter.",
140 + cause,
141 + }),
142 + ),
143 + );
144 + const textGeneration = yield* makePiTextGeneration(effectiveConfig, processEnv);
145 +
146 + const checkProvider = checkPiProviderStatus(effectiveConfig, processEnv, cwd).pipe(
147 + Effect.map(stampIdentity),
148 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
149 + );
150 +
151 + const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
152 + const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<PiSettings>>({
153 + resolveMaintenance,
154 + getSettings: snapshotSettings.getSettings,
155 + streamSettings: snapshotSettings.streamSettings,
156 + haveSettingsChanged: haveProviderSnapshotSettingsChanged,
157 + initialSnapshot: (settings) =>
158 + buildInitialPiProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),
159 + checkProvider,
160 + enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
161 + resolveMaintenance().pipe(
162 + Effect.flatMap((maintenanceCapabilities) =>
163 + enrichPiSnapshot({
164 + snapshot: currentSnapshot,
165 + maintenanceCapabilities,
166 + enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
167 + publishSnapshot,
168 }),
169 + ),
170 + Effect.provideService(HttpClient.HttpClient, httpClient),
171 + Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
172 ),
177 - );
173 + }).pipe(
174 + Effect.mapError(
175 + (cause) =>
176 + new ProviderDriverError({
177 + driver: DRIVER_KIND,
178 + instanceId,
179 + detail: "Failed to build Pi snapshot.",
180 + cause,
181 + }),
182 + ),
183 + );
184
179 - return {
180 - instanceId,
181 - driverKind: DRIVER_KIND,
182 - continuationIdentity,
183 - displayName,
184 - accentColor,
185 - enabled,
186 - snapshot,
187 - snapshotForCwd: (workspaceCwd) =>
188 - !effectiveConfig.enabled
189 - ? snapshot.getSnapshot
190 - : Effect.all([
191 - snapshot.getSnapshot,
192 - discoverPiCommandsForCwd(effectiveConfig, processEnv, workspaceCwd).pipe(
193 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
194 - Effect.mapError(
195 - (cause) =>
196 - new ProviderDriverError({
197 - driver: DRIVER_KIND,
198 - instanceId,
199 - detail: "Failed to discover Pi workspace commands.",
200 - cause,
201 - }),
202 - ),
185 + return {
186 + instanceId,
187 + driverKind: DRIVER_KIND,
188 + continuationIdentity,
189 + displayName,
190 + accentColor,
191 + enabled,
192 + snapshot,
193 + snapshotForCwd: (workspaceCwd) =>
194 + !effectiveConfig.enabled
195 + ? snapshot.getSnapshot
196 + : Effect.all([
197 + snapshot.getSnapshot,
198 + discoverPiCommandsForCwd(effectiveConfig, processEnv, workspaceCwd).pipe(
199 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
200 + Effect.mapError(
201 + (cause) =>
202 + new ProviderDriverError({
203 + driver: DRIVER_KIND,
204 + instanceId,
205 + detail: "Failed to discover Pi workspace commands.",
206 + cause,
207 + }),
208 ),
204 - ]).pipe(
205 - Effect.map(([machineSnapshot, commands]) => ({
206 - ...machineSnapshot,
207 - ...commands,
208 - slashCommandsPending: false,
209 - })),
209 ),
211 - orchestrationAdapter,
212 - textGeneration,
213 - } satisfies ProviderInstance;
214 - }),
210 + ]).pipe(
211 + Effect.map(([machineSnapshot, commands]) => ({
212 + ...machineSnapshot,
213 + ...commands,
214 + slashCommandsPending: false,
215 + })),
216 + ),
217 + orchestrationAdapter,
218 + textGeneration,
219 + } satisfies ProviderInstance;
220 + }),
221 };
packages/provider-pi/src/server/rpc.ts
+49 -47
@@ -167,14 +167,16 @@ function parsePiRecord(line: string): PiRpcRecord | undefined {
167 * gone its pid/pgid can be recycled by the OS, so escalating blindly could
168 * deliver SIGKILL to an unrelated process.
169 */
170 -const terminatePiProcess = (kill: (signal: NodeJS.Signals) => boolean, hasExited: () => boolean) =>
171 - Effect.gen(function* () {
172 - if (hasExited()) return;
173 - if (!kill("SIGTERM")) return;
174 - yield* Effect.sleep(TERMINATION_GRACE);
175 - if (hasExited()) return;
176 - kill("SIGKILL");
177 - });
170 +const terminatePiProcess = Effect.fn("PiRpc.terminatePiProcess")(function* (
171 + kill: (signal: NodeJS.Signals) => boolean,
172 + hasExited: () => boolean,
173 +) {
174 + if (hasExited()) return;
175 + if (!kill("SIGTERM")) return;
176 + yield* Effect.sleep(TERMINATION_GRACE);
177 + if (hasExited()) return;
178 + kill("SIGKILL");
179 +});
180
181 export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSpawnOptions) {
182 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -251,20 +253,20 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSp
253 const exitDeferred = yield* Deferred.make<number, PiRpcError>();
254 let nextRequestId = 0;
255
254 - const failTransport = (error: PiRpcError) =>
255 - Effect.gen(function* () {
256 - const claimed = yield* Deferred.fail(transportDown, error);
257 - if (!claimed) return;
258 - for (const [key, pending] of pendingRequests) {
259 - pendingRequests.delete(key);
260 - yield* Deferred.fail(pending.deferred, error);
261 - }
262 - yield* Queue.fail(outgoing, error);
263 - yield* Queue.fail(events, error);
264 - });
256 + const failTransport = Effect.fn("PiRpc.failTransport")(function* (error: PiRpcError) {
257 + const claimed = yield* Deferred.fail(transportDown, error);
258 + if (!claimed) return;
259 + for (const [key, pending] of pendingRequests) {
260 + pendingRequests.delete(key);
261 + yield* Deferred.fail(pending.deferred, error);
262 + }
263 + yield* Queue.fail(outgoing, error);
264 + yield* Queue.fail(events, error);
265 + });
266
266 - const routeRecord = (record: PiRpcRecord) =>
267 - Effect.gen(function* () {
267 + const routeRecord =
268 + /* Protocol records and writes include streaming deltas; avoid a span per record. */
269 + Effect.fnUntraced(function* (record: PiRpcRecord) {
270 if (record["type"] === "response" && typeof record["id"] === "string") {
271 const pending = pendingRequests.get(record["id"]);
272 if (pending !== undefined) {
@@ -386,8 +388,9 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSp
388 Effect.forkIn(scope),
389 );
390
389 - const send = (record: PiRpcRecord): Effect.Effect<void, PiRpcError> =>
390 - Effect.gen(function* () {
391 + const send =
392 + /* Protocol records and writes include streaming deltas; avoid a span per record. */
393 + Effect.fnUntraced(function* (record: PiRpcRecord): Effect.fn.Return<void, PiRpcError> {
394 const accepted = yield* Queue.offer(
395 outgoing,
396 new TextEncoder().encode(`${encodeJsonLine(record)}\n`),
@@ -397,32 +400,31 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSp
400 }
401 });
402
400 - const request = (
403 + const request = Effect.fn("PiRpc.request")(function* (
404 record: PiRpcRecord,
405 timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
403 - ): Effect.Effect<unknown, PiRpcError | PiRpcTimeoutError> =>
404 - Effect.gen(function* () {
405 - const id = `t3-${nextRequestId++}`;
406 - const deferred = yield* Deferred.make<unknown, PiRpcError>();
407 - pendingRequests.set(id, { deferred });
408 - yield* send({ ...record, id }).pipe(
409 - Effect.tapError(() => Effect.sync(() => pendingRequests.delete(id))),
410 - );
411 - return yield* Effect.raceFirst(Deferred.await(deferred), Deferred.await(transportDown)).pipe(
412 - Effect.timeoutOrElse({
413 - duration: Duration.millis(timeoutMs),
414 - orElse: () =>
415 - Effect.fail(
416 - new PiRpcTimeoutError({
417 - operation: String(record["type"] ?? "request"),
418 - timeoutMs,
419 - }),
420 - ),
421 - }),
422 - Effect.onInterrupt(() => Effect.sync(() => pendingRequests.delete(id))),
423 - Effect.onError(() => Effect.sync(() => pendingRequests.delete(id))),
424 - );
425 - });
406 + ): Effect.fn.Return<unknown, PiRpcError | PiRpcTimeoutError> {
407 + const id = `t3-${nextRequestId++}`;
408 + const deferred = yield* Deferred.make<unknown, PiRpcError>();
409 + pendingRequests.set(id, { deferred });
410 + yield* send({ ...record, id }).pipe(
411 + Effect.tapError(() => Effect.sync(() => pendingRequests.delete(id))),
412 + );
413 + return yield* Effect.raceFirst(Deferred.await(deferred), Deferred.await(transportDown)).pipe(
414 + Effect.timeoutOrElse({
415 + duration: Duration.millis(timeoutMs),
416 + orElse: () =>
417 + Effect.fail(
418 + new PiRpcTimeoutError({
419 + operation: String(record["type"] ?? "request"),
420 + timeoutMs,
421 + }),
422 + ),
423 + }),
424 + Effect.onInterrupt(() => Effect.sync(() => pendingRequests.delete(id))),
425 + Effect.onError(() => Effect.sync(() => pendingRequests.delete(id))),
426 + );
427 + });
428
429 return {
430 send,
packages/provider-pi/src/server/status.ts
+55 -56
@@ -156,28 +156,27 @@ const makePiDiscoveryConnection = Effect.fnUntraced(function* (
156 return connection;
157 });
158
159 -const discoverPiViaRpc = (
159 +const discoverPiViaRpc = Effect.fn("PiProviderStatus.discoverPiViaRpc")(function* (
160 piSettings: PiSettings,
161 environment: NodeJS.ProcessEnv,
162 launchArgs: ReadonlyArray<string>,
163 cwd?: string,
164 -) =>
165 - Effect.gen(function* () {
166 - const connection = yield* makePiDiscoveryConnection(piSettings, environment, launchArgs, cwd);
167 - const stateData = yield* connection.request({ type: "get_state" });
168 - const modelsData = yield* connection.request({ type: "get_available_models" });
169 - const commandsData = yield* connection
170 - .request({ type: "get_commands" })
171 - .pipe(Effect.orElseSucceed(() => undefined));
172 - const discoveredModels = yield* Effect.fromResult(parseDiscoveredModels(modelsData, stateData));
173 - const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
174 - return {
175 - models: discoveredModels,
176 - slashCommands: withPiBuiltinSlashCommands(slashCommands),
177 - skills,
178 - authenticated: discoveredModels.length > 0,
179 - } satisfies PiDiscovery;
180 - }).pipe(Effect.scoped);
164 +) {
165 + const connection = yield* makePiDiscoveryConnection(piSettings, environment, launchArgs, cwd);
166 + const stateData = yield* connection.request({ type: "get_state" });
167 + const modelsData = yield* connection.request({ type: "get_available_models" });
168 + const commandsData = yield* connection
169 + .request({ type: "get_commands" })
170 + .pipe(Effect.orElseSucceed(() => undefined));
171 + const discoveredModels = yield* Effect.fromResult(parseDiscoveredModels(modelsData, stateData));
172 + const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
173 + return {
174 + models: discoveredModels,
175 + slashCommands: withPiBuiltinSlashCommands(slashCommands),
176 + skills,
177 + authenticated: discoveredModels.length > 0,
178 + } satisfies PiDiscovery;
179 +}, Effect.scoped);
180
181 export const discoverPiCommandsForCwd = Effect.fn("discoverPiCommandsForCwd")(
182 function* (piSettings: PiSettings, environment: NodeJS.ProcessEnv, cwd: string) {
@@ -206,57 +205,57 @@ export const discoverPiCommandsForCwd = Effect.fn("discoverPiCommandsForCwd")(
205 }),
206 );
207
209 -const runPiVersionCommand = (piSettings: PiSettings, environment: NodeJS.ProcessEnv) =>
210 - Effect.gen(function* () {
211 - const command = piSettings.binaryPath || "pi";
212 - const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {
213 - env: environment,
214 - });
215 - return yield* spawnAndCollect(
216 - command,
217 - ChildProcess.make(spawnCommand.command, spawnCommand.args, {
218 - env: environment,
219 - shell: spawnCommand.shell,
220 - }),
221 - );
208 +const runPiVersionCommand = Effect.fn("PiProviderStatus.runPiVersionCommand")(function* (
209 + piSettings: PiSettings,
210 + environment: NodeJS.ProcessEnv,
211 +) {
212 + const command = piSettings.binaryPath || "pi";
213 + const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {
214 + env: environment,
215 });
216 + return yield* spawnAndCollect(
217 + command,
218 + ChildProcess.make(spawnCommand.command, spawnCommand.args, {
219 + env: environment,
220 + shell: spawnCommand.shell,
221 + }),
222 + );
223 +});
224
224 -export function buildInitialPiProviderSnapshot(
225 - piSettings: PiSettings,
226 -): Effect.Effect<ServerProviderDraft> {
227 - return Effect.gen(function* () {
228 - const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
229 - const models = piModelsFromSettings(piSettings.customModels);
230 - if (!piSettings.enabled) {
231 - return buildServerProvider({
232 - presentation: PI_PRESENTATION,
233 - enabled: false,
234 - checkedAt,
235 - models,
236 - probe: {
237 - installed: false,
238 - version: null,
239 - status: "warning",
240 - auth: { status: "unknown" },
241 - message: "Pi is disabled in T3 Code settings.",
242 - },
243 - });
244 - }
225 +export const buildInitialPiProviderSnapshot = Effect.fn(
226 + "PiProviderStatus.buildInitialPiProviderSnapshot",
227 +)(function* (piSettings: PiSettings): Effect.fn.Return<ServerProviderDraft> {
228 + const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
229 + const models = piModelsFromSettings(piSettings.customModels);
230 + if (!piSettings.enabled) {
231 return buildServerProvider({
232 presentation: PI_PRESENTATION,
247 - enabled: true,
233 + enabled: false,
234 checkedAt,
235 models,
236 probe: {
251 - installed: true,
237 + installed: false,
238 version: null,
239 status: "warning",
240 auth: { status: "unknown" },
255 - message: "Checking Pi CLI availability...",
241 + message: "Pi is disabled in T3 Code settings.",
242 },
243 });
244 + }
245 + return buildServerProvider({
246 + presentation: PI_PRESENTATION,
247 + enabled: true,
248 + checkedAt,
249 + models,
250 + probe: {
251 + installed: true,
252 + version: null,
253 + status: "warning",
254 + auth: { status: "unknown" },
255 + message: "Checking Pi CLI availability...",
256 + },
257 });
259 -}
258 +});
259
260 export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function* (
261 piSettings: PiSettings,
packages/provider-pi/src/server/textGeneration.ts
+29 -24
@@ -21,9 +21,10 @@ export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function*
21 ) {
22 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
23
24 - const runPiJson: TextGenerationOperations.Runner = (request) => {
25 - const { operation, cwd, prompt, modelSelection } = request;
26 - return Effect.gen(function* () {
24 + const runPiJson: TextGenerationOperations.Runner = Effect.fn("PiTextGeneration.runPiJson")(
25 + function* (request) {
26 + const { operation, cwd, prompt, modelSelection } = request;
27 +
28 const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
29 if (!resolvedLaunchArgs.ok) {
30 return yield* new TextGenerationError({
@@ -87,27 +88,31 @@ export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function*
88 });
89 }
90 return yield* TextGenerationOperations.decodeJsonReply(request, "Pi", text);
90 - }).pipe(
91 - Effect.timeoutOption(PI_TIMEOUT_MS),
92 - Effect.flatMap(
93 - Option.match({
94 - onNone: () =>
95 - Effect.fail(new TextGenerationError({ operation, detail: "Pi request timed out." })),
96 - onSome: (value) => Effect.succeed(value),
97 - }),
98 - ),
99 - Effect.mapError((cause) =>
100 - isTextGenerationError(cause)
101 - ? cause
102 - : new TextGenerationError({
103 - operation,
104 - detail: "Pi text generation failed.",
105 - cause,
106 - }),
107 - ),
108 - Effect.scoped,
109 - );
110 - };
91 + },
92 + (effect, request) => {
93 + const { operation } = request;
94 + return effect.pipe(
95 + Effect.timeoutOption(PI_TIMEOUT_MS),
96 + Effect.flatMap(
97 + Option.match({
98 + onNone: () =>
99 + Effect.fail(new TextGenerationError({ operation, detail: "Pi request timed out." })),
100 + onSome: (value) => Effect.succeed(value),
101 + }),
102 + ),
103 + Effect.mapError((cause) =>
104 + isTextGenerationError(cause)
105 + ? cause
106 + : new TextGenerationError({
107 + operation,
108 + detail: "Pi text generation failed.",
109 + cause,
110 + }),
111 + ),
112 + Effect.scoped,
113 + );
114 + },
115 + );
116
117 return TextGenerationOperations.fromRunner(
118 "PiTextGeneration",