TypeScript
refactor(server): use Effect functions at transport and startup boundaries (#21999)
Julius Marminge889bb95f7ed1
diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.tsindex 7ce72153b49..b7e63cc8064 100644--- a/apps/server/src/auth/McpOAuth.ts+++ b/apps/server/src/auth/McpOAuth.ts@@ -288,8 +288,8 @@ const make = Effect.gen(function* () {]),);- const register: McpOAuth["Service"]["register"] = (metadata) =>- Effect.gen(function* () {+ const register: McpOAuth["Service"]["register"] = Effect.fn("McpOAuth.register")(+ function* (metadata) {const rawName = metadata.client_name?.trim() ?? "";const name = (rawName.length > 0 ? rawName : DEFAULT_CLIENT_NAME).slice(0,@@ -314,59 +314,58 @@ const make = Effect.gen(function* () {// asks for refresh_token, and hosted agents may ask for a client secret; every client// is registered as public and proves itself with PKCE instead.return { clientId: signClientId(name, redirectUris), name, redirectUris };- });+ },+ );- const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = ({ urls, request }) =>- Effect.gen(function* () {- const client = parseClientId(request.client_id ?? "");- if (client === undefined) {- return yield* new McpOAuthPageError({- description: "This sign-in link names an unknown app. Start the sign-in again from it.",- });- }- const redirectUri = request.redirect_uri;- if (- redirectUri === undefined ||- !client.redirectUris.some((registered) => redirectMatches(registered, redirectUri))- ) {- return yield* new McpOAuthPageError({- description: "This sign-in link sends you to an address the app did not register.",- });- }- const state = request.state;- const fail = (error: McpOAuthRedirectError["error"], description: string) =>- new McpOAuthRedirectError({- error,- description,- redirectUri,- ...(state === undefined ? {} : { state }),- });- if (request.response_type !== "code") {- return yield* fail("unsupported_response_type", "Only response_type=code is supported.");- }- const codeChallenge = request.code_challenge;- if (- request.code_challenge_method !== "S256" ||- codeChallenge === undefined ||- !CODE_CHALLENGE_PATTERN.test(codeChallenge)- ) {- return yield* fail("invalid_request", "PKCE with code_challenge_method=S256 is required.");- }- if (!sameResource(urls, request.resource)) {- return yield* fail(- "invalid_target",- `This server only issues tokens for ${urls.resource}.`,- );- }- return {- client,+ const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = Effect.fn(+ "McpOAuth.validateAuthorization",+ )(function* ({ urls, request }) {+ const client = parseClientId(request.client_id ?? "");+ if (client === undefined) {+ return yield* new McpOAuthPageError({+ description: "This sign-in link names an unknown app. Start the sign-in again from it.",+ });+ }+ const redirectUri = request.redirect_uri;+ if (+ redirectUri === undefined ||+ !client.redirectUris.some((registered) => redirectMatches(registered, redirectUri))+ ) {+ return yield* new McpOAuthPageError({+ description: "This sign-in link sends you to an address the app did not register.",+ });+ }+ const state = request.state;+ const fail = (error: McpOAuthRedirectError["error"], description: string) =>+ new McpOAuthRedirectError({+ error,+ description,redirectUri,- codeChallenge,- state,- resource: urls.resource,- issuer: urls.issuer,- } satisfies AuthorizationRequest;- });+ ...(state === undefined ? {} : { state }),+ });+ if (request.response_type !== "code") {+ return yield* fail("unsupported_response_type", "Only response_type=code is supported.");+ }+ const codeChallenge = request.code_challenge;+ if (+ request.code_challenge_method !== "S256" ||+ codeChallenge === undefined ||+ !CODE_CHALLENGE_PATTERN.test(codeChallenge)+ ) {+ return yield* fail("invalid_request", "PKCE with code_challenge_method=S256 is required.");+ }+ if (!sameResource(urls, request.resource)) {+ return yield* fail("invalid_target", `This server only issues tokens for ${urls.resource}.`);+ }+ return {+ client,+ redirectUri,+ codeChallenge,+ state,+ resource: urls.resource,+ issuer: urls.issuer,+ } satisfies AuthorizationRequest;+ });const approvingBrowserSession: McpOAuth["Service"]["approvingBrowserSession"] = (request,@@ -383,73 +382,72 @@ const make = Effect.gen(function* () {Effect.orElseSucceed(() => undefined),);- const mintCode = (authorization: AuthorizationRequest, access: AuthMcpClientAccess) =>- Effect.gen(function* () {- const now = yield* Clock.currentTimeMillis;- const code = Buffer.from(yield* crypto.randomBytes(32).pipe(Effect.orDie)).toString(- "base64url",- );- yield* Ref.update(codes, (current) => {- const next = new Map(- Array.from(current).filter(([, pending]) => pending.expiresAtMs > now),- );- next.set(code, {- clientId: authorization.client.clientId,- clientName: authorization.client.name,- redirectUri: authorization.redirectUri,- codeChallenge: authorization.codeChallenge,- resource: authorization.resource,- access,- expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS,- });- return next;+ const mintCode = Effect.fn("McpOAuth.mintCode")(function* (+ authorization: AuthorizationRequest,+ access: AuthMcpClientAccess,+ ) {+ const now = yield* Clock.currentTimeMillis;+ const code = Buffer.from(yield* crypto.randomBytes(32).pipe(Effect.orDie)).toString(+ "base64url",+ );+ yield* Ref.update(codes, (current) => {+ const next = new Map(Array.from(current).filter(([, pending]) => pending.expiresAtMs > now));+ next.set(code, {+ clientId: authorization.client.clientId,+ clientName: authorization.client.name,+ redirectUri: authorization.redirectUri,+ codeChallenge: authorization.codeChallenge,+ resource: authorization.resource,+ access,+ expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS,});- return code;+ return next;});+ return code;+ });- const approve: McpOAuth["Service"]["approve"] = (input) =>- Effect.gen(function* () {- const { decision } = input;- if (decision._tag === "pairing-code") {- yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(- Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>- Effect.logError("MCP approval code check failed.", { cause }).pipe(- Effect.andThen(- Effect.fail(- new McpOAuthPageError({- description: "The code could not be checked. Try again.",- }),- ),+ const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) {+ const { decision } = input;+ if (decision._tag === "pairing-code") {+ yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(+ Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>+ Effect.logError("MCP approval code check failed.", { cause }).pipe(+ Effect.andThen(+ Effect.fail(+ new McpOAuthPageError({+ description: "The code could not be checked. Try again.",+ }),),),),- );- } else {- const session = yield* approvingBrowserSession(input.request, input.authorization);- if (- session === undefined ||- !timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||- !EnvironmentAuth.mcpClientScopes(decision.access).every((scope) =>- session.scopes.includes(scope),- )- ) {- return yield* new McpOAuthPageError({- description: "Your session cannot approve this request. Enter a pairing code instead.",- });- }+ ),+ );+ } else {+ const session = yield* approvingBrowserSession(input.request, input.authorization);+ if (+ session === undefined ||+ !timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||+ !EnvironmentAuth.mcpClientScopes(decision.access).every((scope) =>+ session.scopes.includes(scope),+ )+ ) {+ return yield* new McpOAuthPageError({+ description: "Your session cannot approve this request. Enter a pairing code instead.",+ });}- const code = yield* mintCode(input.authorization, decision.access);- yield* Effect.logInfo("Approved an MCP client sign-in.", {- client: input.authorization.client.name,- access: decision.access,- method: decision._tag,- });- return redirectWith(input.authorization.redirectUri, {- code,- state: input.authorization.state,- iss: input.authorization.issuer,- });+ }+ const code = yield* mintCode(input.authorization, decision.access);+ yield* Effect.logInfo("Approved an MCP client sign-in.", {+ client: input.authorization.client.name,+ access: decision.access,+ method: decision._tag,+ });+ return redirectWith(input.authorization.redirectUri, {+ code,+ state: input.authorization.state,+ iss: input.authorization.issuer,});+ });const deny: McpOAuth["Service"]["deny"] = (authorization) =>redirectWith(authorization.redirectUri, {@@ -458,8 +456,8 @@ const make = Effect.gen(function* () {iss: authorization.issuer,});- const exchangeCode: McpOAuth["Service"]["exchangeCode"] = ({ request, urls, token }) =>- Effect.gen(function* () {+ const exchangeCode: McpOAuth["Service"]["exchangeCode"] = Effect.fn("McpOAuth.exchangeCode")(+ function* ({ request, urls, token }) {const fail = (error: AuthMcpTokenError["error"], description: string) =>new AuthMcpTokenError({ error, error_description: description });if (token.grant_type !== "authorization_code") {@@ -517,7 +515,8 @@ const make = Effect.gen(function* () {expires_in: Math.max(0, Math.floor((issued.expiresAt.epochMilliseconds - now) / 1000)),scope: encodeOAuthScope(EnvironmentAuth.mcpClientScopes(pending.access)),};- });+ },+ );return McpOAuth.of({register,diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.tsindex b9fda7a67e4..5c08e978f91 100644--- a/apps/server/src/auth/SessionStore.ts+++ b/apps/server/src/auth/SessionStore.ts@@ -539,33 +539,34 @@ export const make = Effect.gen(function* () {sessionId,}).pipe(Effect.asVoid);- const loadActiveSession = (sessionId: AuthSessionId) =>- Effect.gen(function* () {- const row = yield* authSessions.getById({ sessionId });- if (Option.isNone(row) || row.value.revokedAt !== null) {- return Option.none<AuthClientSession>();- }+ const loadActiveSession = Effect.fn("SessionStore.loadActiveSession")(function* (+ sessionId: AuthSessionId,+ ) {+ const row = yield* authSessions.getById({ sessionId });+ if (Option.isNone(row) || row.value.revokedAt !== null) {+ return Option.none<AuthClientSession>();+ }- const connectedSessions = yield* Ref.get(connectedSessionsRef);- const connected = connectedSessions.has(row.value.sessionId);- const now = yield* DateTime.now;- if (!connected && row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {- return Option.none<AuthClientSession>();- }- return Option.some(- toAuthClientSession({- sessionId: row.value.sessionId,- subject: row.value.subject,- scopes: row.value.scopes,- method: row.value.method,- client: toClientMetadata(row.value.client),- issuedAt: row.value.issuedAt,- expiresAt: row.value.expiresAt,- lastConnectedAt: row.value.lastConnectedAt,- connected,- }),- );- });+ const connectedSessions = yield* Ref.get(connectedSessionsRef);+ const connected = connectedSessions.has(row.value.sessionId);+ const now = yield* DateTime.now;+ if (!connected && row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {+ return Option.none<AuthClientSession>();+ }+ return Option.some(+ toAuthClientSession({+ sessionId: row.value.sessionId,+ subject: row.value.subject,+ scopes: row.value.scopes,+ method: row.value.method,+ client: toClientMetadata(row.value.client),+ issuedAt: row.value.issuedAt,+ expiresAt: row.value.expiresAt,+ lastConnectedAt: row.value.lastConnectedAt,+ connected,+ }),+ );+ });const markConnected: SessionStore["Service"]["markConnected"] = (sessionId) =>Ref.modify(connectedSessionsRef, (current) => {diff --git a/apps/server/src/auth/dpop.ts b/apps/server/src/auth/dpop.tsindex f191c354e14..9d2262e6fc5 100644--- a/apps/server/src/auth/dpop.ts+++ b/apps/server/src/auth/dpop.ts@@ -52,74 +52,73 @@ export const mapDpopReplayStoreError = (cause: error,});-export const verifyRequestDpopProof = (input: {+export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(function* (input: {readonly request: HttpServerRequest.HttpServerRequest;readonly expectedThumbprint?: string;readonly expectedAccessToken?: string;-}) =>- Effect.gen(function* () {- const proof = input.request.headers.dpop;- const url = HttpServerRequest.toURL(input.request);- if (Option.isNone(url)) {- return yield* new ServerAuthInvalidCredentialError({- diagnostic: "Invalid DPoP request URL.",- });- }- const now = yield* DateTime.now;- const result = verifyDpopProof({- proof,- method: input.request.method,- url: url.value.href,- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),- ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),+}) {+ const proof = input.request.headers.dpop;+ const url = HttpServerRequest.toURL(input.request);+ if (Option.isNone(url)) {+ return yield* new ServerAuthInvalidCredentialError({+ diagnostic: "Invalid DPoP request URL.",});- if (!result.ok) {- yield* Effect.annotateCurrentSpan({- "environment.dpop.failure_code": result.code,- });- return yield* new ServerAuthInvalidCredentialError({- diagnostic: result.reason,- dpopFailureReason: mapDpopFailureReason(result.code),- });- }- const secretStore = yield* ServerSecretStore.ServerSecretStore;- const replayKey = yield* Crypto.Crypto.pipe(- Effect.flatMap((crypto) =>- crypto.digest("SHA-256", new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)),+ }+ const now = yield* DateTime.now;+ const result = verifyDpopProof({+ proof,+ method: input.request.method,+ url: url.value.href,+ nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),+ ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),+ ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),+ });+ if (!result.ok) {+ yield* Effect.annotateCurrentSpan({+ "environment.dpop.failure_code": result.code,+ });+ return yield* new ServerAuthInvalidCredentialError({+ diagnostic: result.reason,+ dpopFailureReason: mapDpopFailureReason(result.code),+ });+ }+ const secretStore = yield* ServerSecretStore.ServerSecretStore;+ const replayKey = yield* Crypto.Crypto.pipe(+ Effect.flatMap((crypto) =>+ crypto.digest("SHA-256", new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)),+ ),+ Effect.map(Base64Url.encode),+ Effect.mapError(+ (cause) =>+ new ServerAuthDpopReplayKeyCalculationError({+ cause,+ }),+ ),+ );+ yield* secretStore+ .create(+ `${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`,+ new TextEncoder().encode(+ [+ `thumbprint=${result.thumbprint}`,+ `jti=${result.jti}`,+ `iat=${result.iat}`,+ `consumedAt=${DateTime.formatIso(now)}`,+ ].join("\n"),),- Effect.map(Base64Url.encode),- Effect.mapError(- (cause) =>- new ServerAuthDpopReplayKeyCalculationError({- cause,- }),+ )+ .pipe(+ Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>+ Effect.gen(function* () {+ const mapped = mapDpopReplayStoreError(error);+ if (mapped._tag === "ServerAuthInvalidCredentialError") {+ yield* Effect.annotateCurrentSpan({+ "environment.dpop.failure_code": mapped.dpopFailureReason,+ });+ }+ return yield* mapped;+ }),),);- yield* secretStore- .create(- `${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`,- new TextEncoder().encode(- [- `thumbprint=${result.thumbprint}`,- `jti=${result.jti}`,- `iat=${result.iat}`,- `consumedAt=${DateTime.formatIso(now)}`,- ].join("\n"),- ),- )- .pipe(- Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>- Effect.gen(function* () {- const mapped = mapDpopReplayStoreError(error);- if (mapped._tag === "ServerAuthInvalidCredentialError") {- yield* Effect.annotateCurrentSpan({- "environment.dpop.failure_code": mapped.dpopFailureReason,- });- }- return yield* mapped;- }),- ),- );- return result.thumbprint;- });+ return result.thumbprint;+});diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.tsindex 0e02c8782cb..ae052abbf01 100644--- a/apps/server/src/auth/http.ts+++ b/apps/server/src/auth/http.ts@@ -51,8 +51,9 @@ const appendDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request,Effect.succeed(HttpServerResponse.setHeader(response, "www-authenticate", "DPoP")),);-const appendDpopChallengeOnUnauthorized = (error: EnvironmentAuthInvalidError) =>- Effect.gen(function* () {+const appendDpopChallengeOnUnauthorized =+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (error: EnvironmentAuthInvalidError) {const request = yield* HttpServerRequest.HttpServerRequest;const usesDpop =(request.originalUrl.startsWith("/oauth/token") && request.headers.dpop !== undefined) ||@@ -68,8 +69,9 @@ const currentEnvironmentTraceId = Effect.currentParentSpan.pipe(Effect.orElseSucceed(() => "unavailable"),);-export function annotateEnvironmentRequest(endpoint: string) {- return Effect.gen(function* () {+export const annotateEnvironmentRequest =+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (endpoint: string) {const request = yield* HttpServerRequest.HttpServerRequest;const url = HttpServerRequest.toURL(request);const traceId = yield* currentEnvironmentTraceId;@@ -91,7 +93,6 @@ export function annotateEnvironmentRequest(endpoint: string) {"url.path": url._tag === "Some" ? url.value.pathname : "unknown",});});-}export function failEnvironmentAuthInvalid(reason: EnvironmentAuthInvalidReason,@@ -160,8 +161,9 @@ export function failEnvironmentNotFound(reason: EnvironmentResourceNotFoundReaso* authenticate the way the `/ws` upgrade does: a cookie for browser sessions, or a short-lived* `wsTicket` minted over authenticated HTTP for bearer and DPoP clients.*/-export const authenticateMediaRequest = (requiredScope: AuthEnvironmentScope) =>- Effect.gen(function* () {+export const authenticateMediaRequest =+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (requiredScope: AuthEnvironmentScope) {const request = yield* HttpServerRequest.HttpServerRequest;const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(@@ -183,8 +185,9 @@ export const authenticateMediaRequest = (requiredScope: AuthEnvironmentScope) =>return session;});-export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {- return Effect.gen(function* () {+export const failEnvironmentInternal =+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (reason: EnvironmentInternalErrorReason, error?: unknown) {const traceId = yield* currentEnvironmentTraceId;if (error !== undefined) {yield* Effect.logError("environment api operation failed", {@@ -195,7 +198,6 @@ export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason,}return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId });});-}const appendSessionCookie = (cookieName: string, token: string, expiresAt: DateTime.DateTime) =>Effect.fromResult(diff --git a/apps/server/src/auth/mcpOAuthHttp.ts b/apps/server/src/auth/mcpOAuthHttp.tsindex 81a343dd8c1..d8f2471872e 100644--- a/apps/server/src/auth/mcpOAuthHttp.ts+++ b/apps/server/src/auth/mcpOAuthHttp.ts@@ -38,11 +38,12 @@ const requestUrls = Effect.map(HttpServerRequest.HttpServerRequest, McpOAuth.req* An unverified client or redirect is reported, never redirected; any other problem goes back to* the agent through its (verified) redirect URI.*/-const forwardedAuthorization = (- oauth: McpOAuth.McpOAuth["Service"],- request: AuthMcpAuthorizationRequest,-) =>- Effect.gen(function* () {+const forwardedAuthorization =+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (+ oauth: McpOAuth.McpOAuth["Service"],+ request: AuthMcpAuthorizationRequest,+ ) {const urls = yield* requestUrls;return yield* oauth.validateAuthorization({ urls, request }).pipe(Effect.catchTags({diff --git a/apps/server/src/bootstrap.ts b/apps/server/src/bootstrap.tsindex 708a8fd9119..09c8277a142 100644--- a/apps/server/src/bootstrap.ts+++ b/apps/server/src/bootstrap.ts@@ -166,43 +166,44 @@ const isFdReady = (fd: number) =>}),);-const makeBootstrapInputStream = (fd: number) =>- Effect.gen(function* () {- const platform = yield* HostProcess.Platform;- const fdPath = resolveFdPath(fd, platform);- return yield* Effect.try<NodeStream.Readable, BootstrapInputStreamOpenError>({- try: () => {- if (fdPath === undefined) {- return makeDirectBootstrapStream(fd);- }+const makeBootstrapInputStream = Effect.fn("bootstrap.makeBootstrapInputStream")(function* (+ fd: number,+) {+ const platform = yield* HostProcess.Platform;+ const fdPath = resolveFdPath(fd, platform);+ return yield* Effect.try<NodeStream.Readable, BootstrapInputStreamOpenError>({+ try: () => {+ if (fdPath === undefined) {+ return makeDirectBootstrapStream(fd);+ }- let streamFd: number | undefined;- try {- streamFd = NodeFS.openSync(fdPath, "r");- return NodeFS.createReadStream("", {- fd: streamFd,- encoding: "utf8",- autoClose: true,- });- } catch (error) {- if (isBootstrapFdPathDuplicationError(error)) {- if (streamFd !== undefined) {- NodeFS.closeSync(streamFd);- }- return makeDirectBootstrapStream(fd);+ let streamFd: number | undefined;+ try {+ streamFd = NodeFS.openSync(fdPath, "r");+ return NodeFS.createReadStream("", {+ fd: streamFd,+ encoding: "utf8",+ autoClose: true,+ });+ } catch (error) {+ if (isBootstrapFdPathDuplicationError(error)) {+ if (streamFd !== undefined) {+ NodeFS.closeSync(streamFd);}- throw error;+ return makeDirectBootstrapStream(fd);}- },- catch: (error) =>- new BootstrapInputStreamOpenError({- fd,- platform,- ...(fdPath === undefined ? {} : { fdPath }),- cause: error,- }),- });+ throw error;+ }+ },+ catch: (error) =>+ new BootstrapInputStreamOpenError({+ fd,+ platform,+ ...(fdPath === undefined ? {} : { fdPath }),+ cause: error,+ }),});+});const makeDirectBootstrapStream = (fd: number): NodeStream.Readable => {try {diff --git a/apps/server/src/cli/auth.ts b/apps/server/src/cli/auth.tsindex 8195538a55c..0aeb7d6a3b5 100644--- a/apps/server/src/cli/auth.ts+++ b/apps/server/src/cli/auth.ts@@ -23,29 +23,28 @@ import {resolveCliAuthConfig,} from "./config.ts";-const runWithEnvironmentAuth = <A, E>(+const runWithEnvironmentAuth = Effect.fn("auth.runWithEnvironmentAuth")(function* <A, E>(flags: CliAuthLocationFlags,run: (environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,options?: {readonly quietLogs?: boolean;},-) =>- Effect.gen(function* () {- const logLevel = yield* GlobalFlag.LogLevel;- const config = yield* resolveCliAuthConfig(flags, logLevel);- const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;- return yield* Effect.gen(function* () {- const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;- return yield* run(environmentAuth);- }).pipe(- Effect.provide(- Layer.mergeAll(EnvironmentAuth.layerRuntime).pipe(- Layer.provide(ServerConfig.layer(config)),- Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),- ),+) {+ const logLevel = yield* GlobalFlag.LogLevel;+ const config = yield* resolveCliAuthConfig(flags, logLevel);+ const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;+ return yield* Effect.gen(function* () {+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;+ return yield* run(environmentAuth);+ }).pipe(+ Effect.provide(+ Layer.mergeAll(EnvironmentAuth.layerRuntime).pipe(+ Layer.provide(ServerConfig.layer(config)),+ Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),),- );- });+ ),+ );+});const ttlFlag = Flag.String("ttl").pipe(Flag.withSchema(DurationFromString),diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.tsindex 0ee42f76dec..c7271b795b5 100644--- a/apps/server/src/cli/config.ts+++ b/apps/server/src/cli/config.ts@@ -249,7 +249,7 @@ const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: streturn parsePersistedServerObservabilitySettings(raw);});-export const resolveServerConfig = (+export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(function* (flags: CliServerFlags,cliLogLevel: Option.Option<LogLevel.LogLevel>,options?: {@@ -257,235 +257,234 @@ export const resolveServerConfig = (readonly forceAutoBootstrapProjectFromCwd?: boolean;readonly rejectRunningServer?: boolean;},-) =>- Effect.gen(function* () {- const { findAvailablePort } = yield* NetService.NetService;- const path = yield* Path.Path;- const fs = yield* FileSystem.FileSystem;- const env = yield* EnvServerConfig;- const normalizedFlags = {- mode: flags.mode ?? Option.none(),- port: flags.port ?? Option.none(),- host: flags.host ?? Option.none(),- baseDir: flags.baseDir ?? Option.none(),- cwd: flags.cwd ?? Option.none(),- devUrl: flags.devUrl ?? Option.none(),- noBrowser: flags.noBrowser ?? Option.none(),- bootstrapFd: flags.bootstrapFd ?? Option.none(),- autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),- logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),- tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),- tailscaleServePort: flags.tailscaleServePort ?? Option.none(),- } satisfies CliServerFlags;- const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;- const bootstrapEnvelope =- bootstrapFd !== undefined- ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)- : Option.none();- const bootstrap = Option.getOrUndefined(bootstrapEnvelope);+) {+ const { findAvailablePort } = yield* NetService.NetService;+ const path = yield* Path.Path;+ const fs = yield* FileSystem.FileSystem;+ const env = yield* EnvServerConfig;+ const normalizedFlags = {+ mode: flags.mode ?? Option.none(),+ port: flags.port ?? Option.none(),+ host: flags.host ?? Option.none(),+ baseDir: flags.baseDir ?? Option.none(),+ cwd: flags.cwd ?? Option.none(),+ devUrl: flags.devUrl ?? Option.none(),+ noBrowser: flags.noBrowser ?? Option.none(),+ bootstrapFd: flags.bootstrapFd ?? Option.none(),+ autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),+ logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),+ tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),+ tailscaleServePort: flags.tailscaleServePort ?? Option.none(),+ } satisfies CliServerFlags;+ const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;+ const bootstrapEnvelope =+ bootstrapFd !== undefined+ ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)+ : Option.none();+ const bootstrap = Option.getOrUndefined(bootstrapEnvelope);- const mode: ServerConfig.RuntimeMode = Option.getOrElse(- resolveOptionPrecedence(- normalizedFlags.mode,- Option.fromUndefinedOr(env.mode),- Option.fromUndefinedOr(bootstrap?.mode),- ),- () => "web",- );+ const mode: ServerConfig.RuntimeMode = Option.getOrElse(+ resolveOptionPrecedence(+ normalizedFlags.mode,+ Option.fromUndefinedOr(env.mode),+ Option.fromUndefinedOr(bootstrap?.mode),+ ),+ () => "web",+ );- const port = yield* Option.match(- resolveOptionPrecedence(- normalizedFlags.port,- Option.fromUndefinedOr(env.port),- Option.fromUndefinedOr(bootstrap?.port),- ),- {- onSome: (value) => Effect.succeed(value),- onNone: () => {- if (mode === "desktop") {- return Effect.succeed(ServerConfig.DEFAULT_PORT);- }- return findAvailablePort(ServerConfig.DEFAULT_PORT);- },+ const port = yield* Option.match(+ resolveOptionPrecedence(+ normalizedFlags.port,+ Option.fromUndefinedOr(env.port),+ Option.fromUndefinedOr(bootstrap?.port),+ ),+ {+ onSome: (value) => Effect.succeed(value),+ onNone: () => {+ if (mode === "desktop") {+ return Effect.succeed(ServerConfig.DEFAULT_PORT);+ }+ return findAvailablePort(ServerConfig.DEFAULT_PORT);},- );- const devUrl = Option.getOrElse(- resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),- () => undefined,- );- const devAuthToken =- mode === "web" && devUrl !== undefined ? yield* DevAuthTokenConfig : undefined;- const explicitBaseDir = resolveOptionPrecedence(- normalizedFlags.baseDir,- Option.fromUndefinedOr(env.t3Home),- ).pipe(Option.filter((value) => value.trim().length > 0));- const baseDir = yield* resolveBaseDir(- Option.getOrUndefined(- resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),- ),- );- const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());- const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));- const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {- baseDirIsExplicit: Option.isSome(explicitBaseDir),- });- // An interactive CLI must not start over a discovered server. Lifetime locking- // and supervisor handoff are separate; this preflight cannot arbitrate two starts.- if (options?.rejectRunningServer && mode === "web") {- const runtime = yield* readPersistedServerRuntimeState(derivedPaths.serverRuntimeStatePath);- // A killed container can leave a record with the new server's own PID.- if (- Option.isSome(runtime) &&- runtime.value.pid > 0 &&- runtime.value.pid !== process.pid &&- isProcessAlive(runtime.value.pid)- ) {- return yield* new CliError.UserError({- cause: `A T3 Code server is already running for ${baseDir} (pid ${runtime.value.pid}, ${runtime.value.origin}). Connect to that server, stop it before starting another, or use a different --base-dir.`,- });- }+ },+ );+ const devUrl = Option.getOrElse(+ resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),+ () => undefined,+ );+ const devAuthToken =+ mode === "web" && devUrl !== undefined ? yield* DevAuthTokenConfig : undefined;+ const explicitBaseDir = resolveOptionPrecedence(+ normalizedFlags.baseDir,+ Option.fromUndefinedOr(env.t3Home),+ ).pipe(Option.filter((value) => value.trim().length > 0));+ const baseDir = yield* resolveBaseDir(+ Option.getOrUndefined(+ resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),+ ),+ );+ const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());+ const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));+ const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {+ baseDirIsExplicit: Option.isSome(explicitBaseDir),+ });+ // An interactive CLI must not start over a discovered server. Lifetime locking+ // and supervisor handoff are separate; this preflight cannot arbitrate two starts.+ if (options?.rejectRunningServer && mode === "web") {+ const runtime = yield* readPersistedServerRuntimeState(derivedPaths.serverRuntimeStatePath);+ // A killed container can leave a record with the new server's own PID.+ if (+ Option.isSome(runtime) &&+ runtime.value.pid > 0 &&+ runtime.value.pid !== process.pid &&+ isProcessAlive(runtime.value.pid)+ ) {+ return yield* new CliError.UserError({+ cause: `A T3 Code server is already running for ${baseDir} (pid ${runtime.value.pid}, ${runtime.value.origin}). Connect to that server, stop it before starting another, or use a different --base-dir.`,+ });}- yield* fs.makeDirectory(cwd, { recursive: true });- yield* ServerConfig.ensureServerDirectories(derivedPaths);- const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(- derivedPaths.settingsPath,- );- const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;- yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });- const startupPresentation = options?.startupPresentation ?? "browser";- const isHeadlessStartup = startupPresentation === "headless";- const noBrowser = Option.getOrElse(- resolveOptionPrecedence(- isHeadlessStartup ? Option.some(true) : Option.none(),- normalizedFlags.noBrowser,- Option.fromUndefinedOr(env.noBrowser),- Option.fromUndefinedOr(bootstrap?.noBrowser),- ),- () => mode === "desktop",- );- const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;- const desktopBootstrapSecret = bootstrap?.desktopBootstrapSecret;- const shellEnvironmentPrepared = bootstrap?.shellEnvironmentPrepared;- const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;- const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;- const desktopBrowserFd = bootstrap?.desktopBrowserFd;- const desktopBrowserControlFd = bootstrap?.desktopBrowserControlFd;- const resourceMonitorPath = bootstrap?.resourceMonitorPath;- const autoBootstrapProjectFromCwd = Option.getOrElse(- resolveOptionPrecedence(- Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),- isHeadlessStartup ? Option.some(false) : Option.none(),- normalizedFlags.autoBootstrapProjectFromCwd,- Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),- ),- () => mode === "web",- );- const logWebSocketEvents = Option.getOrElse(- resolveOptionPrecedence(- normalizedFlags.logWebSocketEvents,- Option.fromUndefinedOr(env.logWebSocketEvents),- ),- () => Boolean(devUrl),- );- const tailscaleServeEnabled = Option.getOrElse(- resolveOptionPrecedence(- normalizedFlags.tailscaleServeEnabled,- Option.fromUndefinedOr(env.tailscaleServeEnabled),- Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),- ),- () => false,- );- const tailscaleServePort = Option.getOrElse(- resolveOptionPrecedence(- normalizedFlags.tailscaleServePort,- Option.fromUndefinedOr(env.tailscaleServePort),- Option.fromUndefinedOr(bootstrap?.tailscaleServePort),- ),- () => 443,- );- const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();- const host = Option.getOrElse(- resolveOptionPrecedence(- normalizedFlags.host,- Option.fromUndefinedOr(env.host),- Option.fromUndefinedOr(bootstrap?.host),- ),- () => (mode === "desktop" ? "127.0.0.1" : undefined),- );- const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);+ }+ yield* fs.makeDirectory(cwd, { recursive: true });+ yield* ServerConfig.ensureServerDirectories(derivedPaths);+ const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(+ derivedPaths.settingsPath,+ );+ const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;+ yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });+ const startupPresentation = options?.startupPresentation ?? "browser";+ const isHeadlessStartup = startupPresentation === "headless";+ const noBrowser = Option.getOrElse(+ resolveOptionPrecedence(+ isHeadlessStartup ? Option.some(true) : Option.none(),+ normalizedFlags.noBrowser,+ Option.fromUndefinedOr(env.noBrowser),+ Option.fromUndefinedOr(bootstrap?.noBrowser),+ ),+ () => mode === "desktop",+ );+ const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;+ const desktopBootstrapSecret = bootstrap?.desktopBootstrapSecret;+ const shellEnvironmentPrepared = bootstrap?.shellEnvironmentPrepared;+ const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;+ const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;+ const desktopBrowserFd = bootstrap?.desktopBrowserFd;+ const desktopBrowserControlFd = bootstrap?.desktopBrowserControlFd;+ const resourceMonitorPath = bootstrap?.resourceMonitorPath;+ const autoBootstrapProjectFromCwd = Option.getOrElse(+ resolveOptionPrecedence(+ Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),+ isHeadlessStartup ? Option.some(false) : Option.none(),+ normalizedFlags.autoBootstrapProjectFromCwd,+ Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),+ ),+ () => mode === "web",+ );+ const logWebSocketEvents = Option.getOrElse(+ resolveOptionPrecedence(+ normalizedFlags.logWebSocketEvents,+ Option.fromUndefinedOr(env.logWebSocketEvents),+ ),+ () => Boolean(devUrl),+ );+ const tailscaleServeEnabled = Option.getOrElse(+ resolveOptionPrecedence(+ normalizedFlags.tailscaleServeEnabled,+ Option.fromUndefinedOr(env.tailscaleServeEnabled),+ Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),+ ),+ () => false,+ );+ const tailscaleServePort = Option.getOrElse(+ resolveOptionPrecedence(+ normalizedFlags.tailscaleServePort,+ Option.fromUndefinedOr(env.tailscaleServePort),+ Option.fromUndefinedOr(bootstrap?.tailscaleServePort),+ ),+ () => 443,+ );+ const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();+ const host = Option.getOrElse(+ resolveOptionPrecedence(+ normalizedFlags.host,+ Option.fromUndefinedOr(env.host),+ Option.fromUndefinedOr(bootstrap?.host),+ ),+ () => (mode === "desktop" ? "127.0.0.1" : undefined),+ );+ const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);- const otel = yield* OtelEnvironment.load;+ const otel = yield* OtelEnvironment.load;- const signalExport: SignalExport = {- protocol: env.otlpProtocol,- headers: env.otlpHeaders,- exportIntervalMs: env.otlpExportIntervalMs,- };- const traces = OtelEnvironment.resolveSignalEndpoint(- otel,- "traces",- { url: env.otlpTracesUrl, export: signalExport },- bootstrap?.otlpTracesUrl,- persistedObservabilitySettings.otlpTracesUrl,- );- const metrics = OtelEnvironment.resolveSignalEndpoint(- otel,- "metrics",- { url: env.otlpMetricsUrl, export: signalExport },- bootstrap?.otlpMetricsUrl,- persistedObservabilitySettings.otlpMetricsUrl,- );- const logs = OtelEnvironment.resolveSignalEndpoint(- otel,- "logs",- { url: env.otlpLogsUrl, export: signalExport },- bootstrap?.otlpLogsUrl,- persistedObservabilitySettings.otlpLogsUrl,- );+ const signalExport: SignalExport = {+ protocol: env.otlpProtocol,+ headers: env.otlpHeaders,+ exportIntervalMs: env.otlpExportIntervalMs,+ };+ const traces = OtelEnvironment.resolveSignalEndpoint(+ otel,+ "traces",+ { url: env.otlpTracesUrl, export: signalExport },+ bootstrap?.otlpTracesUrl,+ persistedObservabilitySettings.otlpTracesUrl,+ );+ const metrics = OtelEnvironment.resolveSignalEndpoint(+ otel,+ "metrics",+ { url: env.otlpMetricsUrl, export: signalExport },+ bootstrap?.otlpMetricsUrl,+ persistedObservabilitySettings.otlpMetricsUrl,+ );+ const logs = OtelEnvironment.resolveSignalEndpoint(+ otel,+ "logs",+ { url: env.otlpLogsUrl, export: signalExport },+ bootstrap?.otlpLogsUrl,+ persistedObservabilitySettings.otlpLogsUrl,+ );- const config: ServerConfig.ServerConfig["Service"] = {- logLevel,- traceMinLevel: env.traceMinLevel,- traceTimingEnabled: env.traceTimingEnabled,- traceBatchWindowMs: env.traceBatchWindowMs,- traceMaxBytes: env.traceMaxBytes,- traceMaxFiles: env.traceMaxFiles,- otlpTracesUrl: traces?.url,- otlpMetricsUrl: metrics?.url,- otlpLogsUrl: logs?.url,- otlpTracesExport: traces?.export ?? signalExport,- otlpMetricsExport: metrics?.export ?? signalExport,- otlpLogsExport: logs?.export ?? signalExport,- otelEnvironment: otel,- mode,- port,- cwd,- baseDir,- ...derivedPaths,- serverTracePath,- host,- staticDir,- devUrl,- ...(devAuthToken === undefined ? {} : { devAuthToken }),- devAllowedOrigins: env.devAllowedOrigins,- noBrowser,- startupPresentation,- desktopBootstrapToken,- ...(desktopBootstrapSecret === undefined ? {} : { desktopBootstrapSecret }),- ...(shellEnvironmentPrepared === undefined ? {} : { shellEnvironmentPrepared }),- desktopTelemetryFd,- desktopTelemetryControlFd,- desktopBrowserFd,- desktopBrowserControlFd,- resourceMonitorPath,- autoBootstrapProjectFromCwd,- logWebSocketEvents,- tailscaleServeEnabled,- tailscaleServePort,- };+ const config: ServerConfig.ServerConfig["Service"] = {+ logLevel,+ traceMinLevel: env.traceMinLevel,+ traceTimingEnabled: env.traceTimingEnabled,+ traceBatchWindowMs: env.traceBatchWindowMs,+ traceMaxBytes: env.traceMaxBytes,+ traceMaxFiles: env.traceMaxFiles,+ otlpTracesUrl: traces?.url,+ otlpMetricsUrl: metrics?.url,+ otlpLogsUrl: logs?.url,+ otlpTracesExport: traces?.export ?? signalExport,+ otlpMetricsExport: metrics?.export ?? signalExport,+ otlpLogsExport: logs?.export ?? signalExport,+ otelEnvironment: otel,+ mode,+ port,+ cwd,+ baseDir,+ ...derivedPaths,+ serverTracePath,+ host,+ staticDir,+ devUrl,+ ...(devAuthToken === undefined ? {} : { devAuthToken }),+ devAllowedOrigins: env.devAllowedOrigins,+ noBrowser,+ startupPresentation,+ desktopBootstrapToken,+ ...(desktopBootstrapSecret === undefined ? {} : { desktopBootstrapSecret }),+ ...(shellEnvironmentPrepared === undefined ? {} : { shellEnvironmentPrepared }),+ desktopTelemetryFd,+ desktopTelemetryControlFd,+ desktopBrowserFd,+ desktopBrowserControlFd,+ resourceMonitorPath,+ autoBootstrapProjectFromCwd,+ logWebSocketEvents,+ tailscaleServeEnabled,+ tailscaleServePort,+ };- return config;- });+ return config;+});export const resolveCliAuthConfig = (flags: CliAuthLocationFlags,diff --git a/apps/server/src/cli/invocation.ts b/apps/server/src/cli/invocation.tsindex 6fe0304307b..4be566c10e9 100644--- a/apps/server/src/cli/invocation.ts+++ b/apps/server/src/cli/invocation.ts@@ -170,21 +170,23 @@ const resolveInstallLauncher = Effect.gen(function* () {* installs. `args` are quoted for the host's shell: POSIX, or PowerShell on* Windows.*/-export const resolveHostCliCommand = (subcommand: string, args: ReadonlyArray<string> = []) =>- Effect.gen(function* () {- const platform = yield* HostProcess.Platform;- const withArgs = (prefix: string) =>- [prefix, ...args.map((arg) => hostShellWord(platform, arg))].join(" ");- const command = yield* resolveCliCommand(subcommand);- if (command !== `t3 ${subcommand}`) return { command: withArgs(command), launcher: false };- if (yield* isCommandAvailable("t3")) return { command: withArgs(command), launcher: false };- const launcher = yield* resolveInstallLauncher;- if (Option.isNone(launcher)) return { command: withArgs(command), launcher: false };- // PowerShell runs a quoted path only through the call operator.- const quoted = hostShellWord(platform, launcher.value);- const call = platform === "win32" ? `& ${quoted}` : quoted;- return { command: withArgs(`${call} ${subcommand}`), launcher: true };- });+export const resolveHostCliCommand = Effect.fn("invocation.resolveHostCliCommand")(function* (+ subcommand: string,+ args: ReadonlyArray<string> = [],+) {+ const platform = yield* HostProcess.Platform;+ const withArgs = (prefix: string) =>+ [prefix, ...args.map((arg) => hostShellWord(platform, arg))].join(" ");+ const command = yield* resolveCliCommand(subcommand);+ if (command !== `t3 ${subcommand}`) return { command: withArgs(command), launcher: false };+ if (yield* isCommandAvailable("t3")) return { command: withArgs(command), launcher: false };+ const launcher = yield* resolveInstallLauncher;+ if (Option.isNone(launcher)) return { command: withArgs(command), launcher: false };+ // PowerShell runs a quoted path only through the call operator.+ const quoted = hostShellWord(platform, launcher.value);+ const call = platform === "win32" ? `& ${quoted}` : quoted;+ return { command: withArgs(`${call} ${subcommand}`), launcher: true };+});/*** `sudo` resets PATH on most distributions, which drops a user-installed Node@@ -192,16 +194,17 @@ export const resolveHostCliCommand = (subcommand: string, args: ReadonlyArray<st* carries PATH through unless Node is on root's PATH too. An absolute launcher* needs neither.*/-export const resolveRootCliCommand = (subcommand: string) =>- Effect.gen(function* () {- const { command, launcher } = yield* resolveHostCliCommand(subcommand);- if (launcher) return `sudo ${command}`;- const executablePath = yield* HostProcess.ExecutablePath;- const systemNode = ROOT_PATH_DIRECTORIES.some((directory) =>- executablePath.startsWith(`${directory}/`),- );- return systemNode ? `sudo ${command}` : `sudo env "PATH=$PATH" ${command}`;- });+export const resolveRootCliCommand = Effect.fn("invocation.resolveRootCliCommand")(function* (+ subcommand: string,+) {+ const { command, launcher } = yield* resolveHostCliCommand(subcommand);+ if (launcher) return `sudo ${command}`;+ const executablePath = yield* HostProcess.ExecutablePath;+ const systemNode = ROOT_PATH_DIRECTORIES.some((directory) =>+ executablePath.startsWith(`${directory}/`),+ );+ return systemNode ? `sudo ${command}` : `sudo env "PATH=$PATH" ${command}`;+});const ROOT_PATH_DIRECTORIES = ["/usr/local/sbin",diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.tsindex 723e77144ef..073606bf637 100644--- a/apps/server/src/cli/pair.ts+++ b/apps/server/src/cli/pair.ts@@ -180,10 +180,12 @@ type EnvironmentProbeResult =| { readonly _tag: "unreachable" }| { readonly _tag: "not-a-t3-server" };-const probeEnvironmentDescriptor = (+const probeEnvironmentDescriptor: (baseUrl: string,-): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>- Effect.gen(function* () {+) => Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> = Effect.fn(+ "pair.probeEnvironmentDescriptor",+)(+ function* (baseUrl: string) {const client = yield* HttpClient.HttpClient;const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());const response = yield* client.execute(request).pipe(@@ -202,7 +204,9 @@ const probeEnvironmentDescriptor = (Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),);return { _tag: "descriptor", descriptor } as const;- }).pipe(Effect.catch((outcome) => Effect.succeed(outcome)));+ },+ Effect.catch((outcome) => Effect.succeed(outcome)),+);interface DiscoveredPairTarget {readonly baseDir: string;diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.tsindex 8f352489b88..b567a7d4d3d 100644--- a/apps/server/src/cli/project.ts+++ b/apps/server/src/cli/project.ts@@ -316,32 +316,34 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (} satisfies ProjectMutationTarget;});-const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>- Effect.gen(function* () {+const fetchLiveOrchestrationSnapshot = Effect.fn("project.fetchLiveOrchestrationSnapshot")(+ function* (origin: string, bearerToken: string) {const client = yield* makeLiveServerClient(origin);return yield* client.projects.snapshot({headers: { authorization: `Bearer ${bearerToken}` },});- }).pipe(- withProjectCliLiveServerTimeout,- Effect.mapError(projectCommandErrorFromLiveServerRequest),- );+ },+ (effect, _origin, _bearerToken) =>+ effect.pipe(+ withProjectCliLiveServerTimeout,+ Effect.mapError(projectCommandErrorFromLiveServerRequest),+ ),+);-const dispatchLiveOrchestrationCommand = (- origin: string,- bearerToken: string,- command: ProjectCliDispatchCommand,-) =>- Effect.gen(function* () {+const dispatchLiveOrchestrationCommand = Effect.fn("project.dispatchLiveOrchestrationCommand")(+ function* (origin: string, bearerToken: string, command: ProjectCliDispatchCommand) {const client = yield* makeLiveServerClient(origin);yield* client.projects.mutate({headers: { authorization: `Bearer ${bearerToken}` },payload: command,} as Parameters<typeof client.projects.mutate>[0]);- }).pipe(- withProjectCliLiveServerTimeout,- Effect.mapError(projectCommandErrorFromLiveServerRequest),- );+ },+ (effect, _origin, _bearerToken, _command) =>+ effect.pipe(+ withProjectCliLiveServerTimeout,+ Effect.mapError(projectCommandErrorFromLiveServerRequest),+ ),+);const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {const projects = yield* ProjectService.ProjectService;diff --git a/apps/server/src/cli/server.ts b/apps/server/src/cli/server.tsindex b43201cd296..e9f0d7e19ae 100644--- a/apps/server/src/cli/server.ts+++ b/apps/server/src/cli/server.ts@@ -13,52 +13,49 @@ import { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } frconst encodeCommand = Schema.encodeEffect(Schema.fromJsonString(Schema.String));-const runServerCommand = (+const runServerCommand = Effect.fn("server.runServerCommand")(function* (flags: CliServerFlags,options?: {readonly startupPresentation?: ServerConfig.StartupPresentation;readonly forceAutoBootstrapProjectFromCwd?: boolean;readonly rejectRunningServer?: boolean;},-) =>- Effect.gen(function* () {- const logLevel = yield* GlobalFlag.LogLevel;- const config = yield* resolveServerConfig(flags, logLevel, options);- const run = runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config));- if (config.mode !== "desktop" || config.desktopBootstrapToken === undefined) return yield* run;- return yield* Effect.raceFirst(- run,- awaitLauncherLoss().pipe(- // End like SIGTERM does (interrupt-only exit, so the runtime forces process exit).- Effect.andThen(Effect.interrupt),- ),- );- });+) {+ const logLevel = yield* GlobalFlag.LogLevel;+ const config = yield* resolveServerConfig(flags, logLevel, options);+ const run = runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config));+ if (config.mode !== "desktop" || config.desktopBootstrapToken === undefined) return yield* run;+ return yield* Effect.raceFirst(+ run,+ awaitLauncherLoss().pipe(+ // End like SIGTERM does (interrupt-only exit, so the runtime forces process exit).+ Effect.andThen(Effect.interrupt),+ ),+ );+});-export const runDefaultServerCommand = (flags: CliServerFlags) =>- Effect.gen(function* () {- if (Option.isSome(flags.cwd)) {- const cwd = flags.cwd.value.trim();- const fs = yield* FileSystem.FileSystem;- const platform = yield* HostProcess.Platform;- const explicitPath =- cwd === "." ||- cwd === ".." ||- cwd === "~" ||- /[/\\]/.test(cwd) ||- (platform === "win32" && /^[a-z]:/i.test(cwd));- if (- !explicitPath &&- (!(yield* fs.exists(cwd)) || (yield* fs.stat(cwd)).type !== "Directory")- ) {- return yield* new CliError.UserError({- cause: cwd,- userMessage: `Unknown command ${yield* encodeCommand(cwd)}. Use "t3 --help" for commands or an explicit path such as "t3 ./my-project" for a new directory.`,- });- }+export const runDefaultServerCommand = Effect.fn("server.runDefaultServerCommand")(function* (+ flags: CliServerFlags,+) {+ if (Option.isSome(flags.cwd)) {+ const cwd = flags.cwd.value.trim();+ const fs = yield* FileSystem.FileSystem;+ const platform = yield* HostProcess.Platform;+ const explicitPath =+ cwd === "." ||+ cwd === ".." ||+ cwd === "~" ||+ /[/\\]/.test(cwd) ||+ (platform === "win32" && /^[a-z]:/i.test(cwd));+ if (!explicitPath && (!(yield* fs.exists(cwd)) || (yield* fs.stat(cwd)).type !== "Directory")) {+ return yield* new CliError.UserError({+ cause: cwd,+ userMessage: `Unknown command ${yield* encodeCommand(cwd)}. Use "t3 --help" for commands or an explicit path such as "t3 ./my-project" for a new directory.`,+ });}- return yield* runServerCommand(flags, { rejectRunningServer: true });- });+ }+ return yield* runServerCommand(flags, { rejectRunningServer: true });+});export const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(Command.withDescription("Run the T3 Code server."),diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.ts b/apps/server/src/cloud/ManagedEndpointRuntime.tsindex 1302b2167d0..03fc9def012 100644--- a/apps/server/src/cloud/ManagedEndpointRuntime.ts+++ b/apps/server/src/cloud/ManagedEndpointRuntime.ts@@ -185,8 +185,9 @@ export const make = Effect.gen(function* () {yield* stopConnector(active);});- const superviseConnector = (connector: ActiveConnector) =>- Effect.gen(function* () {+ // Lives until connector exit and starts replacements; avoid nested lifetime spans.+ const superviseConnector = Effect.fnUntraced(+ function* (connector: ActiveConnector) {const result = yield* Effect.result(connector.child.exitCode);const activeAtExit = yield* Ref.get(activeRef);if (@@ -253,9 +254,9 @@ export const make = Effect.gen(function* () {yield* reconcileConfig(desiredConfig);}),);- }).pipe(- Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),- );+ },+ Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),+ );// The new connector starts next to the old one on the same tunnel, and the// old one stops only once the new one registers, so clients never see the@@ -370,8 +371,9 @@ export const make = Effect.gen(function* () {yield* Effect.forkIn(retryPinnedRelayClientInstall, runtimeScope);});- const watchConnectorRegistration = (connector: ActiveConnector) =>- Effect.gen(function* () {+ // Registration retries can last for the connector lifetime; keep this loop untraced.+ const watchConnectorRegistration = Effect.fnUntraced(+ function* (connector: ActiveConnector) {yield* Effect.sleep(CONNECTOR_REGISTRATION_TIMEOUT);if (yield* Deferred.isDone(connector.registered)) return true;yield* Effect.logWarning(@@ -384,46 +386,48 @@ export const make = Effect.gen(function* () {);yield* Queue.offer(recoveryRequests, connector.config);return false;- }).pipe(Effect.repeat({ until: (connected) => connected }));+ },+ Effect.repeat({ until: (connected) => connected }),+ );// Only an explicit 503 counts: a failed request says nothing about the- const watchConnectorReadiness = (connector: ActiveConnector) =>- Effect.gen(function* () {- const readyUrl = `http://${yield* Deferred.await(connector.metricsAddress)}/ready`;- let notReadyChecks = 0;- while (true) {- yield* Effect.sleep(CONNECTOR_READINESS_INTERVAL);- const status = yield* httpClient.get(readyUrl).pipe(- Effect.map((response) => response.status),- Effect.scoped,- Effect.withTracerEnabled(false),- Effect.timeoutOption(CONNECTOR_READINESS_REQUEST_TIMEOUT),- Effect.orElseSucceed(() => Option.none<number>()),- );- if (Option.isNone(status)) continue;- if (status.value === 200) {- notReadyChecks = 0;- yield* Ref.set(notReadyChecksBeforeRestartRef, CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART);- continue;- }- if (status.value !== 503) continue;- notReadyChecks += 1;- const threshold = yield* Ref.get(notReadyChecksBeforeRestartRef);- if (notReadyChecks < threshold) continue;+ // Readiness polling runs for the connector lifetime; keep this loop untraced.+ const watchConnectorReadiness = Effect.fnUntraced(function* (connector: ActiveConnector) {+ const readyUrl = `http://${yield* Deferred.await(connector.metricsAddress)}/ready`;+ let notReadyChecks = 0;+ while (true) {+ yield* Effect.sleep(CONNECTOR_READINESS_INTERVAL);+ const status = yield* httpClient.get(readyUrl).pipe(+ Effect.map((response) => response.status),+ Effect.scoped,+ Effect.withTracerEnabled(false),+ Effect.timeoutOption(CONNECTOR_READINESS_REQUEST_TIMEOUT),+ Effect.orElseSucceed(() => Option.none<number>()),+ );+ if (Option.isNone(status)) continue;+ if (status.value === 200) {notReadyChecks = 0;- yield* Ref.set(- notReadyChecksBeforeRestartRef,- Math.min(threshold * 2, CONNECTOR_NOT_READY_CHECKS_MAX),- );- yield* Effect.logWarning("Relay client has no tunnel connection; restarting it", {- pid: Number(connector.child.pid),- notReadyChecks: threshold,- tunnelId: connector.config.tunnelId,- tunnelName: connector.config.tunnelName,- });- yield* connector.child.kill().pipe(Effect.ignore);+ yield* Ref.set(notReadyChecksBeforeRestartRef, CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART);+ continue;}- });+ if (status.value !== 503) continue;+ notReadyChecks += 1;+ const threshold = yield* Ref.get(notReadyChecksBeforeRestartRef);+ if (notReadyChecks < threshold) continue;+ notReadyChecks = 0;+ yield* Ref.set(+ notReadyChecksBeforeRestartRef,+ Math.min(threshold * 2, CONNECTOR_NOT_READY_CHECKS_MAX),+ );+ yield* Effect.logWarning("Relay client has no tunnel connection; restarting it", {+ pid: Number(connector.child.pid),+ notReadyChecks: threshold,+ tunnelId: connector.config.tunnelId,+ tunnelName: connector.config.tunnelName,+ });+ yield* connector.child.kill().pipe(Effect.ignore);+ }+ });const observeConnectorOutput = (connector: ActiveConnector) => {let rejectedRegistrations = 0;diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.tsindex 8820fc9d442..00ab464bea4 100644--- a/apps/server/src/cloud/bootService.ts+++ b/apps/server/src/cloud/bootService.ts@@ -877,60 +877,59 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {Effect.withSpan("cloud.boot_service.restart"),);- const withStopped = <A, E, R>(+ const withStopped = Effect.fn("cloud.boot_service.with_stopped")(function* <A, E, R>(operation: Effect.Effect<A, E, R>,- ): Effect.Effect<A, E | BootServiceError, R> =>- Effect.gen(function* () {- if (detectedManager === undefined) return yield* operation;- const manager = detectedManager;- const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);- if (Option.isNone(unit)) return yield* operation;- const installedBaseDir = bootServiceBaseDirOf(unit.value);- if (- installedBaseDir === undefined ||- path.resolve(installedBaseDir) !== path.resolve(input.baseDir)- ) {- return yield* operation;- }- // `is-active` fails while a crash-looping unit sits in `activating- // (auto-restart)`, and a throttled launchd job is loaded without a pid;- // both would start the server mid-repair. So the unit is always- // stopped, and started again when it was active, enabled or loaded- // before; a disabled unit caught crash-looping stays stopped.- const restore =- manager.kind === "systemd"- ? yield* Effect.map(- Effect.all(- [- probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),- probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),- ],- { concurrency: "unbounded" },- ),- ([enabled, active]) => succeeded(active) || succeeded(enabled),- )- : succeeded(- yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),- );- return yield* Effect.acquireUseRelease(- // Every stop step is required when the service is to be restored: a- // step that was fine to skip during uninstall would leave the server- // holding the database. A stop that fails (a timeout, say) may still- // have stopped the service, so the restore below runs either way.- // Nothing to restore means nothing is expected to be loaded, and the- // stop is best-effort (launchd's bootout fails on an unloaded job).- runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),- (stopped): Effect.Effect<A, E | BootServiceError, R> =>- Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),- (_, exit) => {- if (!restore) return Effect.void;- // Start only: `activate` would also enable a unit the user disabled.- // When the operation itself failed, its error is the one worth reporting.- const start = runSteps(manager.restart);- return Exit.isFailure(exit) ? Effect.ignore(start) : start;- },- );- }).pipe(Effect.withSpan("cloud.boot_service.with_stopped"));+ ): Effect.fn.Return<A, E | BootServiceError, R> {+ if (detectedManager === undefined) return yield* operation;+ const manager = detectedManager;+ const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);+ if (Option.isNone(unit)) return yield* operation;+ const installedBaseDir = bootServiceBaseDirOf(unit.value);+ if (+ installedBaseDir === undefined ||+ path.resolve(installedBaseDir) !== path.resolve(input.baseDir)+ ) {+ return yield* operation;+ }+ // `is-active` fails while a crash-looping unit sits in `activating+ // (auto-restart)`, and a throttled launchd job is loaded without a pid;+ // both would start the server mid-repair. So the unit is always+ // stopped, and started again when it was active, enabled or loaded+ // before; a disabled unit caught crash-looping stays stopped.+ const restore =+ manager.kind === "systemd"+ ? yield* Effect.map(+ Effect.all(+ [+ probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),+ probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),+ ],+ { concurrency: "unbounded" },+ ),+ ([enabled, active]) => succeeded(active) || succeeded(enabled),+ )+ : succeeded(+ yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),+ );+ return yield* Effect.acquireUseRelease(+ // Every stop step is required when the service is to be restored: a+ // step that was fine to skip during uninstall would leave the server+ // holding the database. A stop that fails (a timeout, say) may still+ // have stopped the service, so the restore below runs either way.+ // Nothing to restore means nothing is expected to be loaded, and the+ // stop is best-effort (launchd's bootout fails on an unloaded job).+ runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),+ (stopped): Effect.Effect<A, E | BootServiceError, R> =>+ Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),+ (_, exit) => {+ if (!restore) return Effect.void;+ // Start only: `activate` would also enable a unit the user disabled.+ // When the operation itself failed, its error is the one worth reporting.+ const start = runSteps(manager.restart);+ return Exit.isFailure(exit) ? Effect.ignore(start) : start;+ },+ );+ });const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {const manager = yield* requireManager;diff --git a/apps/server/src/cloud/config.ts b/apps/server/src/cloud/config.tsindex acee5760952..90713806b7c 100644--- a/apps/server/src/cloud/config.ts+++ b/apps/server/src/cloud/config.ts@@ -48,10 +48,10 @@ export function isAgentActivityPublishingEnabledValue(value: string | null): boo* Mirrors the per-publish gate in AgentAwarenessRelay, so the descriptorcapability never advertises publishing that the publisher would skip.*/-export const readAgentActivityPublishingActive = (+export const readAgentActivityPublishingActive: (secrets: ServerSecretStore.ServerSecretStore["Service"],-): Effect.Effect<boolean> =>- Effect.gen(function* () {+) => Effect.Effect<boolean> = Effect.fn("config.readAgentActivityPublishingActive")(+ function* (secrets: ServerSecretStore.ServerSecretStore["Service"]) {const readSecretString = (name: string) =>secrets.get(name)@@ -74,7 +74,9 @@ export const readAgentActivityPublishingActive = (environmentCredential !== null &&environmentCredential !== "");- }).pipe(Effect.orElseSucceed(() => false));+ },+ Effect.orElseSucceed(() => false),+);const readSecretString = (name: string) =>ServerSecretStore.ServerSecretStore.pipe(diff --git a/apps/server/src/cloud/selfUpdate.ts b/apps/server/src/cloud/selfUpdate.tsindex df683f814de..4180d7ece6b 100644--- a/apps/server/src/cloud/selfUpdate.ts+++ b/apps/server/src/cloud/selfUpdate.ts@@ -141,34 +141,33 @@ export const withRunningThreadContinuation = Effect.fn(return ServerSelfUpdate.of({update,- commitDesktopUpdate: (requestId) =>- Effect.gen(function* () {- const shouldContinue = yield* Ref.modify(desktopContinuationTokens, (tokens) => [- HashSet.has(tokens, requestId),- HashSet.remove(tokens, requestId),- ]);- let handoffAccepted = false;- let continuationThreadIds: ReadonlyArray<ThreadId> = [];- return yield* clearOnError(- Effect.gen(function* () {- continuationThreadIds = shouldContinue ? yield* input.prepare : [];- return yield* input.selfUpdate.commitDesktopUpdate(requestId, () =>- Effect.sync(() => {- handoffAccepted = true;- }),- );- }),- () => continuationThreadIds,- () => handoffAccepted,- ).pipe(- Effect.catchCause((cause) =>- (shouldContinue && !handoffAccepted- ? Ref.update(desktopContinuationTokens, HashSet.add(requestId))- : Effect.void- ).pipe(Effect.andThen(Effect.failCause(cause))),- ),- );- }),+ commitDesktopUpdate: Effect.fn("selfUpdate.commitDesktopUpdate")(function* (requestId) {+ const shouldContinue = yield* Ref.modify(desktopContinuationTokens, (tokens) => [+ HashSet.has(tokens, requestId),+ HashSet.remove(tokens, requestId),+ ]);+ let handoffAccepted = false;+ let continuationThreadIds: ReadonlyArray<ThreadId> = [];+ return yield* clearOnError(+ Effect.gen(function* () {+ continuationThreadIds = shouldContinue ? yield* input.prepare : [];+ return yield* input.selfUpdate.commitDesktopUpdate(requestId, () =>+ Effect.sync(() => {+ handoffAccepted = true;+ }),+ );+ }),+ () => continuationThreadIds,+ () => handoffAccepted,+ ).pipe(+ Effect.catchCause((cause) =>+ (shouldContinue && !handoffAccepted+ ? Ref.update(desktopContinuationTokens, HashSet.add(requestId))+ : Effect.void+ ).pipe(Effect.andThen(Effect.failCause(cause))),+ ),+ );+ }),});});diff --git a/apps/server/src/http.ts b/apps/server/src/http.tsindex f623d3441c7..3b8ba8055ee 100644--- a/apps/server/src/http.ts+++ b/apps/server/src/http.ts@@ -291,10 +291,11 @@ export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {return redirectUrl.toString();}-const authenticateRawRouteWithScope = (- scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,-) =>- Effect.gen(function* () {+const authenticateRawRouteWithScope =+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (+ scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,+ ) {const request = yield* HttpServerRequest.HttpServerRequest;const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;const session = yield* serverAuth.authenticateHttpRequest(request).pipe(diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.tsindex 82a3aaa16eb..f61d20b2cfd 100644--- a/apps/server/src/mcp/AcpMcpStdioBridge.ts+++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts@@ -74,36 +74,37 @@ export function callAcpMcpTool(let sessionId: string | null = null;let protocolVersion: string | null = null;- const send = (message: unknown): Effect.Effect<ReadonlyArray<unknown>, AcpMcpBridgeError> =>- Effect.gen(function* () {- const response = yield* Effect.tryPromise({- try: () =>- fetchImplementation(options.endpoint, {- method: "POST",- headers: {- "content-type": "application/json",- accept: "application/json, text/event-stream",- authorization: options.authorization,- ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),- ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),- },- body: JSON.stringify(message),- }),- catch: bridgeError,- });- sessionId = response.headers.get("mcp-session-id") ?? sessionId;- if (!response.ok) {- yield* discardResponseBody(response);- return yield* Effect.fail(- new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),- );- }- const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));- for (const payload of payloads) {- protocolVersion = protocolVersionOf(payload) ?? protocolVersion;- }- return payloads;+ const send = Effect.fn("AcpMcpStdioBridge.send")(function* (+ message: unknown,+ ): Effect.fn.Return<ReadonlyArray<unknown>, AcpMcpBridgeError> {+ const response = yield* Effect.tryPromise({+ try: () =>+ fetchImplementation(options.endpoint, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ accept: "application/json, text/event-stream",+ authorization: options.authorization,+ ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),+ ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),+ },+ body: JSON.stringify(message),+ }),+ catch: bridgeError,});+ sessionId = response.headers.get("mcp-session-id") ?? sessionId;+ if (!response.ok) {+ yield* discardResponseBody(response);+ return yield* Effect.fail(+ new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),+ );+ }+ const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));+ for (const payload of payloads) {+ protocolVersion = protocolVersionOf(payload) ?? protocolVersion;+ }+ return payloads;+ });const initializeId = "t3-acp-cli-initialize";const initialized = yield* send({@@ -156,13 +157,14 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.options.output.write(`${JSON.stringify(message)}\n`);});- const handleServerPayload = (payload: unknown): Effect.Effect<void> =>- Effect.gen(function* () {- for (const entry of Array.isArray(payload) ? payload : [payload]) {- protocolVersion = protocolVersionOf(entry) ?? protocolVersion;- yield* writeMessage(entry);- }- });+ const handleServerPayload = Effect.fn("AcpMcpStdioBridge.handleServerPayload")(function* (+ payload: unknown,+ ): Effect.fn.Return<void> {+ for (const entry of Array.isArray(payload) ? payload : [payload]) {+ protocolVersion = protocolVersionOf(entry) ?? protocolVersion;+ yield* writeMessage(entry);+ }+ });const respondWithError = (requestId: unknown,@@ -175,8 +177,10 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.error: { code, message },});- const forward = (line: string, envelope: JsonRpcEnvelope): Effect.Effect<void> =>- Effect.gen(function* () {+ const forward: (line: string, envelope: JsonRpcEnvelope) => Effect.Effect<void> = Effect.fn(+ "AcpMcpStdioBridge.forward",+ )(+ function* (line: string, envelope: JsonRpcEnvelope) {const response = yield* Effect.tryPromise({try: () =>fetchImplementation(options.endpoint, {@@ -203,16 +207,19 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.return yield* discardResponseBody(response);}yield* Stream.runForEach(responsePayloads(response, bridgeError), handleServerPayload);- }).pipe(- Effect.catchCause((cause) => {- if (envelope.id === undefined) return Effect.void;- const error = Cause.squash(cause);- return respondWithError(- envelope.id,- `T3 Code MCP bridge request failed: ${error instanceof Error ? error.message : String(error)}`,- );- }),- );+ },+ (effect, _line, envelope) =>+ effect.pipe(+ Effect.catchCause((cause) => {+ if (envelope.id === undefined) return Effect.void;+ const error = Cause.squash(cause);+ return respondWithError(+ envelope.id,+ `T3 Code MCP bridge request failed: ${error instanceof Error ? error.message : String(error)}`,+ );+ }),+ ),+ );// Only session establishment is ordered; client responses to// server-initiated SSE requests must bypass the barrier or they would@@ -221,65 +228,64 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.let sessionBarrier: Effect.Effect<void> = Effect.void;let sessionBarrierPending = false;- const launch = (task: Effect.Effect<void>): Effect.Effect<void> =>- Effect.gen(function* () {- const fiber = yield* Effect.forkChild(task);+ const launch = Effect.fn("AcpMcpStdioBridge.launch")(function* (+ task: Effect.Effect<void>,+ ): Effect.fn.Return<void> {+ const fiber = yield* Effect.forkChild(task);+ running.add(fiber);+ yield* Effect.forkChild(+ Fiber.await(fiber).pipe(+ Effect.andThen(+ Effect.sync(() => {+ running.delete(fiber);+ }),+ ),+ ),+ );+ });++ const dispatch = Effect.fn("AcpMcpStdioBridge.dispatch")(function* (+ line: string,+ ): Effect.fn.Return<void> {+ if (line.trim().length === 0) return;+ let parsed: unknown;+ try {+ parsed = JSON.parse(line);+ } catch {+ return yield* respondWithError(null, "Parse error", -32700);+ }+ const envelope = asEnvelope(parsed);+ if (envelope === null) return;+ const isResponse = envelope.id !== undefined && ("result" in envelope || "error" in envelope);+ const isSessionHandshake =+ envelope.method === "initialize" || envelope.method === "notifications/initialized";+ if (isResponse) {+ return yield* launch(forward(line, envelope));+ }+ if (isSessionHandshake) {+ const prior = sessionBarrier;+ const fiber = yield* Effect.forkChild(prior.pipe(Effect.andThen(forward(line, envelope))));running.add(fiber);+ const barrier = Fiber.await(fiber).pipe(Effect.asVoid);+ sessionBarrier = barrier;+ sessionBarrierPending = true;yield* Effect.forkChild(Fiber.await(fiber).pipe(Effect.andThen(Effect.sync(() => {running.delete(fiber);+ if (sessionBarrier === barrier) sessionBarrierPending = false;}),),),);- });-- const dispatch = (line: string): Effect.Effect<void> =>- Effect.gen(function* () {- if (line.trim().length === 0) return;- let parsed: unknown;- try {- parsed = JSON.parse(line);- } catch {- return yield* respondWithError(null, "Parse error", -32700);- }- const envelope = asEnvelope(parsed);- if (envelope === null) return;- const isResponse =- envelope.id !== undefined && ("result" in envelope || "error" in envelope);- const isSessionHandshake =- envelope.method === "initialize" || envelope.method === "notifications/initialized";- if (isResponse) {- return yield* launch(forward(line, envelope));- }- if (isSessionHandshake) {- const prior = sessionBarrier;- const fiber = yield* Effect.forkChild(- prior.pipe(Effect.andThen(forward(line, envelope))),- );- running.add(fiber);- const barrier = Fiber.await(fiber).pipe(Effect.asVoid);- sessionBarrier = barrier;- sessionBarrierPending = true;- yield* Effect.forkChild(- Fiber.await(fiber).pipe(- Effect.andThen(- Effect.sync(() => {- running.delete(fiber);- if (sessionBarrier === barrier) sessionBarrierPending = false;- }),- ),- ),- );- return;- }- const task = sessionBarrierPending- ? sessionBarrier.pipe(Effect.andThen(forward(line, envelope)))- : forward(line, envelope);- return yield* launch(task);- });+ return;+ }+ const task = sessionBarrierPending+ ? sessionBarrier.pipe(Effect.andThen(forward(line, envelope)))+ : forward(line, envelope);+ return yield* launch(task);+ });const reader = NodeReadline.createInterface({ input: options.input });yield* Stream.runForEach(Stream.fromAsyncIterable(reader, bridgeError), dispatch).pipe(diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.tsindex dbca27b8eb9..2f19cc8cecf 100644--- a/apps/server/src/mcp/McpHttpServer.ts+++ b/apps/server/src/mcp/McpHttpServer.ts@@ -634,7 +634,11 @@ const imageToolFailure =* `McpServer.toolkit` serializes every result as JSON text, which is the wrong* shape for a screenshot: the model needs image content.*/-const registerImageTool = <T extends Tool.Any, E, R>(+const registerImageTool = Effect.fn("McpHttpServer.registerImageTool")(function* <+ T extends Tool.Any,+ E,+ R,+>(tool: T,handle: (payload: Tool.Parameters<T>) => Effect.Effect<{ readonly encodedResult: unknown }, E, R>,provide: (@@ -646,73 +650,72 @@ const registerImageTool = <T extends Tool.Any, E, R>(>,operation: string,failureText: string | ((error: E) => string),-) =>- Effect.gen(function* () {- const server = yield* McpServer.McpServer;- yield* server.addTool({- tool: new McpSchema.Tool({- name: tool.name,- description: Tool.getDescription(tool),- inputSchema: Tool.getJsonSchema(tool),- annotations: {- ...Context.getOption(tool.annotations, Tool.Title).pipe(- Option.map((title) => ({ title })),- Option.getOrUndefined,- ),- readOnlyHint: Context.get(tool.annotations, Tool.Readonly),- destructiveHint: Context.get(tool.annotations, Tool.Destructive),- idempotentHint: Context.get(tool.annotations, Tool.Idempotent),- openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),- },+) {+ const server = yield* McpServer.McpServer;+ yield* server.addTool({+ tool: new McpSchema.Tool({+ name: tool.name,+ description: Tool.getDescription(tool),+ inputSchema: Tool.getJsonSchema(tool),+ annotations: {+ ...Context.getOption(tool.annotations, Tool.Title).pipe(+ Option.map((title) => ({ title })),+ Option.getOrUndefined,+ ),+ readOnlyHint: Context.get(tool.annotations, Tool.Readonly),+ destructiveHint: Context.get(tool.annotations, Tool.Destructive),+ idempotentHint: Context.get(tool.annotations, Tool.Idempotent),+ openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),+ },+ }),+ annotations: tool.annotations,+ handle: (payload) =>+ Effect.withFiber((fiber) => {+ const invocation = Context.getUnsafe(+ fiber.context,+ McpInvocationContext.McpInvocationContext,+ );+ return provide(handle(payload as Tool.Parameters<T>)).pipe(+ Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),+ Effect.matchCauseEffect({+ onFailure: imageToolFailure(tool.name, operation, failureText),+ onSuccess: ({ encodedResult }) => {+ const { screenshot, ...rest } = encodedResult as ImageToolResult;+ const includeImage =+ (payload as { readonly includeImage?: boolean } | undefined)?.includeImage !==+ false;+ const metadata = {+ ...rest,+ screenshot: {+ mimeType: screenshot.mimeType,+ width: screenshot.width,+ height: screenshot.height,+ },+ };+ return Effect.succeed(+ new McpSchema.CallToolResult({+ isError: false,+ structuredContent: metadata,+ content: [+ { type: "text", text: JSON.stringify(metadata) },+ ...(includeImage+ ? [+ {+ type: "image" as const,+ data: new Uint8Array(Buffer.from(screenshot.data, "base64")),+ mimeType: screenshot.mimeType,+ },+ ]+ : []),+ ],+ }),+ );+ },+ }),+ );}),- annotations: tool.annotations,- handle: (payload) =>- Effect.withFiber((fiber) => {- const invocation = Context.getUnsafe(- fiber.context,- McpInvocationContext.McpInvocationContext,- );- return provide(handle(payload as Tool.Parameters<T>)).pipe(- Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),- Effect.matchCauseEffect({- onFailure: imageToolFailure(tool.name, operation, failureText),- onSuccess: ({ encodedResult }) => {- const { screenshot, ...rest } = encodedResult as ImageToolResult;- const includeImage =- (payload as { readonly includeImage?: boolean } | undefined)?.includeImage !==- false;- const metadata = {- ...rest,- screenshot: {- mimeType: screenshot.mimeType,- width: screenshot.width,- height: screenshot.height,- },- };- return Effect.succeed(- new McpSchema.CallToolResult({- isError: false,- structuredContent: metadata,- content: [- { type: "text", text: JSON.stringify(metadata) },- ...(includeImage- ? [- {- type: "image" as const,- data: new Uint8Array(Buffer.from(screenshot.data, "base64")),- mimeType: screenshot.mimeType,- },- ]- : []),- ],- }),- );- },- }),- );- }),- });});+});const registerDeviceScreenshot = Effect.fn("McpHttpServer.registerDeviceScreenshot")(function* () {const devices = yield* DeviceService.DeviceService;@@ -820,8 +823,9 @@ const handoffTargetIds = (* agent chose, and the provider, model, and modes of each thread that received* the work. Ids, prompts, and free text are never recorded.*/-const withToolAnalytics = <A, E, R>(registration: Effect.Effect<A, E, R>) =>- Effect.gen(function* () {+const withToolAnalytics =+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* <A, E, R>(registration: Effect.Effect<A, E, R>) {const server = yield* McpServer.McpServer;const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);if (Option.isNone(analytics)) return yield* registration;@@ -834,8 +838,9 @@ const withToolAnalytics = <A, E, R>(registration: Effect.Effect<A, E, R>) =>.getThreadShell(ThreadId.make(threadId)).pipe(Effect.orElseSucceed(() => null));// Delegation depth: parents walked from the caller, capped.- const depthOf = (thread: AgentThread) =>- Effect.gen(function* () {+ const depthOf =+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (thread: AgentThread) {let depth = 0;let parentId =thread.lineage.relationshipToParent === "subagent" ? thread.lineage.parentThreadId : null;@@ -868,59 +873,69 @@ const withToolAnalytics = <A, E, R>(registration: Effect.Effect<A, E, R>) =>}),Effect.orElseSucceed(() => false),);- const record = (- tool: string,- args: unknown,- result: McpSchema.CallToolResult | undefined,- durationMs: number,- ) =>- Effect.gen(function* () {- // Client credentials (no calling thread) report an unknown caller.- const invocation = Option.getOrUndefined(- yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext),- )?.thread;- const providers = Option.isSome(registry) ? yield* registry.value.getProviders : [];- // Only handoff tools pay for thread lookups; the rest report the- // caller's provider from the credential.- const handoff = HANDOFF_TOOLS.has(tool);- const caller =- handoff && invocation !== undefined- ? ((yield* shellOf(invocation.threadId)) ?? undefined)- : undefined;- const targetIds = handoff- ? [...new Set(handoffTargetIds(tool, args, result))].filter(- (threadId) => threadId !== invocation?.threadId,- )- : [];- const targets = yield* Effect.forEach(targetIds, shellOf);- for (const properties of agentToolProperties({- tool,- providers,- caller,- ...(invocation === undefined- ? {}- : { callerProviderInstanceId: invocation.providerInstanceId }),- ...(caller === undefined || invocation === undefined- ? {}- : {- callerDepth: yield* depthOf(caller),- callerScheduledRun: yield* scheduledRunOf(invocation.threadId, caller.activeRunId),- }),- targets: targets.filter((thread) => thread !== null),- outcome: toolOutcome(result),- ...(handoff ? { settings: handoffSettings(tool, args, result?.structuredContent) } : {}),- durationMs,- })) {- yield* analytics.value.record("mcp.tool.invoked", properties);- }- }).pipe(Effect.ignoreCause);+ const record =+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(+ function* (+ tool: string,+ args: unknown,+ result: McpSchema.CallToolResult | undefined,+ durationMs: number,+ ) {+ // Client credentials (no calling thread) report an unknown caller.+ const invocation = Option.getOrUndefined(+ yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext),+ )?.thread;+ const providers = Option.isSome(registry) ? yield* registry.value.getProviders : [];+ // Only handoff tools pay for thread lookups; the rest report the+ // caller's provider from the credential.+ const handoff = HANDOFF_TOOLS.has(tool);+ const caller =+ handoff && invocation !== undefined+ ? ((yield* shellOf(invocation.threadId)) ?? undefined)+ : undefined;+ const targetIds = handoff+ ? [...new Set(handoffTargetIds(tool, args, result))].filter(+ (threadId) => threadId !== invocation?.threadId,+ )+ : [];+ const targets = yield* Effect.forEach(targetIds, shellOf);+ for (const properties of agentToolProperties({+ tool,+ providers,+ caller,+ ...(invocation === undefined+ ? {}+ : { callerProviderInstanceId: invocation.providerInstanceId }),+ ...(caller === undefined || invocation === undefined+ ? {}+ : {+ callerDepth: yield* depthOf(caller),+ callerScheduledRun: yield* scheduledRunOf(+ invocation.threadId,+ caller.activeRunId,+ ),+ }),+ targets: targets.filter((thread) => thread !== null),+ outcome: toolOutcome(result),+ ...(handoff+ ? { settings: handoffSettings(tool, args, result?.structuredContent) }+ : {}),+ durationMs,+ })) {+ yield* analytics.value.record("mcp.tool.invoked", properties);+ }+ },+ (effect, _tool, _args, _result, _durationMs) => effect.pipe(Effect.ignoreCause),+ );const recordingServer = McpServer.McpServer.of({...server,addTool: (options) =>server.addTool({...options,- handle: (payload) =>- Effect.gen(function* () {+ handle:+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (payload) {const startedAt = yield* Clock.currentTimeMillis;return yield* options.handle(payload).pipe(Effect.onExit((exit) => {diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.tsindex 5cc1fe4f128..9e300aa23d2 100644--- a/apps/server/src/mcp/OrchestratorMcpService.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.ts@@ -1020,35 +1020,38 @@ const make = Effect.gen(function* () {).pipe(Effect.mapError(threadManagementFailure));- const loadCaller = (scope: McpInvocationScope) =>- Effect.gen(function* () {- yield* requireCapability(scope);- if (scope.thread === undefined) {- return {- parent: undefined,- limits: {- runtimeMode: clientRuntimeModeCeiling(scope.client),- interactionMode: "default",- } satisfies { runtimeMode: RuntimeMode; interactionMode: ProviderInteractionMode },- } as const;- }- const parent = yield* loadProjection(scope.thread.threadId);+ const loadCaller = Effect.fn("OrchestratorMcpService.loadCaller")(function* (+ scope: McpInvocationScope,+ ) {+ yield* requireCapability(scope);+ if (scope.thread === undefined) {return {- parent,+ parent: undefined,limits: {- runtimeMode: parent.thread.runtimeMode,- interactionMode: parent.thread.interactionMode,- },+ runtimeMode: clientRuntimeModeCeiling(scope.client),+ interactionMode: "default",+ } satisfies { runtimeMode: RuntimeMode; interactionMode: ProviderInteractionMode },} as const;- });+ }+ const parent = yield* loadProjection(scope.thread.threadId);+ return {+ parent,+ limits: {+ runtimeMode: parent.thread.runtimeMode,+ interactionMode: parent.thread.interactionMode,+ },+ } as const;+ });- const loadThreadCaller = (scope: McpInvocationScope, operation: string) =>- Effect.gen(function* () {- yield* requireCapability(scope);- const threadScope = yield* requireThreadScope(scope, operation);- const parent = yield* loadProjection(threadScope.thread.threadId);- return { scope: threadScope, parent } as const;- });+ const loadThreadCaller = Effect.fn("OrchestratorMcpService.loadThreadCaller")(function* (+ scope: McpInvocationScope,+ operation: string,+ ) {+ yield* requireCapability(scope);+ const threadScope = yield* requireThreadScope(scope, operation);+ const parent = yield* loadProjection(threadScope.thread.threadId);+ return { scope: threadScope, parent } as const;+ });const resolveProjectTarget = (parent: Pick<OrchestrationV2ThreadProjection, "thread"> | undefined,@@ -1065,26 +1068,29 @@ const make = Effect.gen(function* () {),);- const loadTargetThread = (threadId: ThreadId) =>- Effect.gen(function* () {- const shell = yield* threadManagement- .getThreadShell(threadId)- .pipe(Effect.mapError(threadManagementFailure));- if (shell === null || shell.deletedAt !== null) {- return yield* failure("thread_not_found", `Thread ${threadId} was not found.`);- }- return yield* loadProjectThread(shell.projectId, threadId);- });-- const loadScopedThread = (scope: McpInvocationScope, threadId: ThreadId) =>- Effect.gen(function* () {- const caller = yield* loadCaller(scope);- const target =- caller.parent !== undefined && threadId === caller.parent.thread.id- ? caller.parent- : yield* loadTargetThread(threadId);- return { ...caller, target } as const;- });+ const loadTargetThread = Effect.fn("OrchestratorMcpService.loadTargetThread")(function* (+ threadId: ThreadId,+ ) {+ const shell = yield* threadManagement+ .getThreadShell(threadId)+ .pipe(Effect.mapError(threadManagementFailure));+ if (shell === null || shell.deletedAt !== null) {+ return yield* failure("thread_not_found", `Thread ${threadId} was not found.`);+ }+ return yield* loadProjectThread(shell.projectId, threadId);+ });++ const loadScopedThread = Effect.fn("OrchestratorMcpService.loadScopedThread")(function* (+ scope: McpInvocationScope,+ threadId: ThreadId,+ ) {+ const caller = yield* loadCaller(scope);+ const target =+ caller.parent !== undefined && threadId === caller.parent.thread.id+ ? caller.parent+ : yield* loadTargetThread(threadId);+ return { ...caller, target } as const;+ });/*** A thread caller writes to another thread only while its own run is live,@@ -1135,24 +1141,26 @@ const make = Effect.gen(function* () {: Effect.void;};- const loadReadableThread = (scope: McpInvocationScope, threadId: ThreadId) =>- Effect.gen(function* () {- const { parent } = yield* loadCaller(scope);- const shell = yield* threadManagement- .getThreadShell(threadId)- .pipe(Effect.mapError(threadManagementFailure));- if (shell === null || shell.deletedAt !== null) {- return yield* failure("thread_not_found", `Thread ${threadId} is no longer available.`);- }- const target = yield* threadManagement- .getProjectThreadRecords({ projectId: shell.projectId, threadId }, [- "runs",- "runtimeRequests",- "contextTransfers",- ])- .pipe(Effect.mapError(threadManagementFailure));- return { parent, target, shell } as const;- });+ const loadReadableThread = Effect.fn("OrchestratorMcpService.loadReadableThread")(function* (+ scope: McpInvocationScope,+ threadId: ThreadId,+ ) {+ const { parent } = yield* loadCaller(scope);+ const shell = yield* threadManagement+ .getThreadShell(threadId)+ .pipe(Effect.mapError(threadManagementFailure));+ if (shell === null || shell.deletedAt !== null) {+ return yield* failure("thread_not_found", `Thread ${threadId} is no longer available.`);+ }+ const target = yield* threadManagement+ .getProjectThreadRecords({ projectId: shell.projectId, threadId }, [+ "runs",+ "runtimeRequests",+ "contextTransfers",+ ])+ .pipe(Effect.mapError(threadManagementFailure));+ return { parent, target, shell } as const;+ });const loadProviders = providerRegistry.getProviders;@@ -1196,7 +1204,7 @@ const make = Effect.gen(function* () {);};- const resolveTarget = (input: {+ const resolveTarget = Effect.fn("OrchestratorMcpService.resolveTarget")(function* (input: {readonly parent: Pick<OrchestrationV2ThreadProjection, "thread">;readonly target: OrchestratorMcpTarget | undefined;readonly providers: ReadonlyArray<ServerProvider>;@@ -1208,327 +1216,317 @@ const make = Effect.gen(function* () {* one checked for a receipt.*/readonly skipProjectEnablementFilter?: boolean;- }): Effect.Effect<ResolvedTarget, OrchestratorMcpFailure> =>- Effect.gen(function* () {- const requestedInstanceId = input.target?.providerInstanceId;- const requestedDriver = input.target?.driverKind;- const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds();- let instanceId = requestedInstanceId;-- if (instanceId === undefined && requestedDriver !== undefined) {- const candidates = input.providers.filter(- (provider) =>- provider.driver === requestedDriver &&- orchestrationCapableInstanceIds.has(provider.instanceId),- );- if (candidates.length === 0) {- return yield* failure(- "provider_unavailable",- `No V2 provider adapter is registered for driver ${requestedDriver}.`,- );- }- const healthyCandidates = candidates.filter(- (candidate) => providerConstraints(candidate, true).length === 0,- );- const inheritedCandidate = healthyCandidates.find(- (candidate) => candidate.instanceId === input.parent.thread.modelSelection.instanceId,- );- const orderedCandidates = [- ...(inheritedCandidate === undefined ? [] : [inheritedCandidate]),- ...healthyCandidates.filter((candidate) => candidate !== inheritedCandidate),- ];- for (const candidate of orderedCandidates) {- const enabledForProject =- input.skipProjectEnablementFilter === true ||- (yield* threadManagement.isProviderInstanceEnabledForProject({- projectId: input.parent.thread.projectId,- instanceId: candidate.instanceId,- }));- if (enabledForProject) {- instanceId = candidate.instanceId;- break;- }- }- if (instanceId === undefined) {- return yield* failure(- "provider_unavailable",- healthyCandidates.length === 0- ? `No available V2 provider instance for driver ${requestedDriver}.`- : `No instance of driver ${requestedDriver} is enabled for this project.`,- );- }- }- instanceId ??= input.parent.thread.modelSelection.instanceId;-- const provider = input.providers.find((candidate) => candidate.instanceId === instanceId);- if (provider === undefined) {+ }): Effect.fn.Return<ResolvedTarget, OrchestratorMcpFailure> {+ const requestedInstanceId = input.target?.providerInstanceId;+ const requestedDriver = input.target?.driverKind;+ const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds();+ let instanceId = requestedInstanceId;++ if (instanceId === undefined && requestedDriver !== undefined) {+ const candidates = input.providers.filter(+ (provider) =>+ provider.driver === requestedDriver &&+ orchestrationCapableInstanceIds.has(provider.instanceId),+ );+ if (candidates.length === 0) {return yield* failure("provider_unavailable",- `Provider instance ${instanceId} is not registered.`,- );- }- if (requestedDriver !== undefined && provider.driver !== requestedDriver) {- return yield* failure(- "invalid_request",- `Provider instance ${instanceId} uses driver ${provider.driver}, not ${requestedDriver}.`,+ `No V2 provider adapter is registered for driver ${requestedDriver}.`,);}- const constraints = providerConstraints(- provider,- orchestrationCapableInstanceIds.has(provider.instanceId),+ const healthyCandidates = candidates.filter(+ (candidate) => providerConstraints(candidate, true).length === 0,);- if (constraints.length > 0) {+ const inheritedCandidate = healthyCandidates.find(+ (candidate) => candidate.instanceId === input.parent.thread.modelSelection.instanceId,+ );+ const orderedCandidates = [+ ...(inheritedCandidate === undefined ? [] : [inheritedCandidate]),+ ...healthyCandidates.filter((candidate) => candidate !== inheritedCandidate),+ ];+ for (const candidate of orderedCandidates) {+ const enabledForProject =+ input.skipProjectEnablementFilter === true ||+ (yield* threadManagement.isProviderInstanceEnabledForProject({+ projectId: input.parent.thread.projectId,+ instanceId: candidate.instanceId,+ }));+ if (enabledForProject) {+ instanceId = candidate.instanceId;+ break;+ }+ }+ if (instanceId === undefined) {return yield* failure("provider_unavailable",- `Provider ${instanceId} cannot run a child task: ${constraints.join(" ")}`,+ healthyCandidates.length === 0+ ? `No available V2 provider instance for driver ${requestedDriver}.`+ : `No instance of driver ${requestedDriver} is enabled for this project.`,);}+ }+ instanceId ??= input.parent.thread.modelSelection.instanceId;- const inheritedSelection = input.parent.thread.modelSelection;- const requestedModel = input.target?.model;- const model =- requestedModel ??- (instanceId === inheritedSelection.instanceId- ? inheritedSelection.model- : provider?.models[0]?.slug);- if (model === undefined) {- return yield* failure(- "model_unavailable",- `Provider ${instanceId} has no model available for inheritance.`,- );- }- if (- requestedModel !== undefined &&- provider !== undefined &&- provider.models.length > 0 &&- !provider.models.some((candidate) => candidate.slug === requestedModel)- ) {+ const provider = input.providers.find((candidate) => candidate.instanceId === instanceId);+ if (provider === undefined) {+ return yield* failure(+ "provider_unavailable",+ `Provider instance ${instanceId} is not registered.`,+ );+ }+ if (requestedDriver !== undefined && provider.driver !== requestedDriver) {+ return yield* failure(+ "invalid_request",+ `Provider instance ${instanceId} uses driver ${provider.driver}, not ${requestedDriver}.`,+ );+ }+ const constraints = providerConstraints(+ provider,+ orchestrationCapableInstanceIds.has(provider.instanceId),+ );+ if (constraints.length > 0) {+ return yield* failure(+ "provider_unavailable",+ `Provider ${instanceId} cannot run a child task: ${constraints.join(" ")}`,+ );+ }++ const inheritedSelection = input.parent.thread.modelSelection;+ const requestedModel = input.target?.model;+ const model =+ requestedModel ??+ (instanceId === inheritedSelection.instanceId+ ? inheritedSelection.model+ : provider?.models[0]?.slug);+ if (model === undefined) {+ return yield* failure(+ "model_unavailable",+ `Provider ${instanceId} has no model available for inheritance.`,+ );+ }+ if (+ requestedModel !== undefined &&+ provider !== undefined &&+ provider.models.length > 0 &&+ !provider.models.some((candidate) => candidate.slug === requestedModel)+ ) {+ return yield* failure(+ "model_unavailable",+ `Model ${requestedModel} is not advertised by provider ${instanceId}.`,+ );+ }++ const requestedOptions = input.target?.options;+ if (requestedOptions !== undefined) {+ const descriptors = provider.models.find((candidate) => candidate.slug === model)+ ?.capabilities?.optionDescriptors;+ const invalid = invalidOptionSelections(requestedOptions, descriptors);+ if (invalid.length > 0) {return yield* failure(- "model_unavailable",- `Model ${requestedModel} is not advertised by provider ${instanceId}.`,+ "invalid_request",+ `Model ${model} on provider ${instanceId} rejected options: ${invalid.join(" ")}`,);}+ }- const requestedOptions = input.target?.options;- if (requestedOptions !== undefined) {- const descriptors = provider.models.find((candidate) => candidate.slug === model)- ?.capabilities?.optionDescriptors;- const invalid = invalidOptionSelections(requestedOptions, descriptors);- if (invalid.length > 0) {- return yield* failure(- "invalid_request",- `Model ${model} on provider ${instanceId} rejected options: ${invalid.join(" ")}`,- );- }- }-- return {- modelSelection:- instanceId === inheritedSelection.instanceId &&- model === inheritedSelection.model &&- requestedOptions === undefined- ? inheritedSelection- : requestedOptions === undefined- ? { instanceId, model }- : { instanceId, model, options: requestedOptions },- supportedRuntimeModes: provider.supportedRuntimeModes,- };- });+ return {+ modelSelection:+ instanceId === inheritedSelection.instanceId &&+ model === inheritedSelection.model &&+ requestedOptions === undefined+ ? inheritedSelection+ : requestedOptions === undefined+ ? { instanceId, model }+ : { instanceId, model, options: requestedOptions },+ supportedRuntimeModes: provider.supportedRuntimeModes,+ };+ });const requestKey = (clientRequestId: string | undefined): Effect.Effect<string> =>clientRequestId === undefined? crypto.randomUUIDv4().pipe(Effect.orDie): Effect.succeed(clientRequestId);- const readTask = (+ const readTask = Effect.fn("OrchestratorMcpService.readTask")(function* (scope: McpThreadInvocationScope,taskId: NodeId,waitTimedOut = false,acknowledgeTerminal = false,acknowledgementOperation = "task-status-acknowledge",- ): Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> =>- Effect.gen(function* () {- yield* requireCapability(scope);- const parentProjection = yield* loadProjection(scope.thread.threadId);- const task = parentProjection.subagents.find(- (candidate) =>- candidate.id === taskId &&- candidate.origin === "app_owned" &&- candidate.threadId === scope.thread.threadId,+ ): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {+ yield* requireCapability(scope);+ const parentProjection = yield* loadProjection(scope.thread.threadId);+ const task = parentProjection.subagents.find(+ (candidate) =>+ candidate.id === taskId &&+ candidate.origin === "app_owned" &&+ candidate.threadId === scope.thread.threadId,+ );+ if (task === undefined || task.childThreadId === null) {+ return yield* failure(+ "task_not_found",+ `Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`,);- if (task === undefined || task.childThreadId === null) {- return yield* failure(- "task_not_found",- `Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`,- );- }- const childControls = yield* threadManagement- .getThreadRecords(- task.childThreadId,- [- "runs",- "messages",- "contextTransfers",- "subagents",- "providerThreads",- "runtimeRequests",- ],- { messageRoles: ["user"] },- )- .pipe(Effect.mapError(threadManagementFailure));- const childRun = delegatedTaskRun(childControls, task);- const terminalRun = latestTerminalResultRun(childControls, childRun);- const progress = delegatedTaskProgress(childControls);- const taskResultRun =- childRun?.delegatedTaskId === task.id- ? childControls.runs- .filter((run) => run.delegatedTaskId === task.id)- .toSorted((a, b) => b.ordinal - a.ordinal)[0]- : progress.resultRun;- const taskWorkState =- childRun?.delegatedTaskId === task.id- ? isTerminalTaskStatus(taskStatusForRun(taskResultRun))- ? "result_available"- : "working"- : progress.state;- const resultRunIds = [- ...new Set(- [taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined),+ }+ const childControls = yield* threadManagement+ .getThreadRecords(+ task.childThreadId,+ ["runs", "messages", "contextTransfers", "subagents", "providerThreads", "runtimeRequests"],+ { messageRoles: ["user"] },+ )+ .pipe(Effect.mapError(threadManagementFailure));+ const childRun = delegatedTaskRun(childControls, task);+ const terminalRun = latestTerminalResultRun(childControls, childRun);+ const progress = delegatedTaskProgress(childControls);+ const taskResultRun =+ childRun?.delegatedTaskId === task.id+ ? childControls.runs+ .filter((run) => run.delegatedTaskId === task.id)+ .toSorted((a, b) => b.ordinal - a.ordinal)[0]+ : progress.resultRun;+ const taskWorkState =+ childRun?.delegatedTaskId === task.id+ ? isTerminalTaskStatus(taskStatusForRun(taskResultRun))+ ? "result_available"+ : "working"+ : progress.state;+ const resultRunIds = [+ ...new Set(+ [taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined),+ ),+ ];+ const resultRecords = yield* threadManagement+ .getThreadRecords(task.childThreadId, ["messages", "turnItems"], {+ messageRoles: ["assistant"],+ messageRunIds: resultRunIds,+ turnItemRunIds: resultRunIds,+ turnItemTypes: ["assistant_message", "error"],+ })+ .pipe(Effect.mapError(threadManagementFailure));+ const childProjection = {+ ...childControls,+ messages: [...childControls.messages, ...resultRecords.messages],+ turnItems: resultRecords.turnItems,+ };+ const heldForRestart =+ task.result === null &&+ taskWorkState === "result_available" &&+ (yield* threadManagement+ .delegatedTaskResultPending(task.childThreadId, childRun?.delegatedTaskId)+ .pipe(Effect.mapError(threadManagementFailure)));+ const workState =+ task.result !== null ? "result_available" : heldForRestart ? "working" : taskWorkState;+ const status =+ task.result !== null+ ? taskStatusForRun(+ task.status === "completed" ||+ task.status === "failed" ||+ task.status === "cancelled" ||+ task.status === "interrupted"+ ? { status: task.status }+ : childRun,+ )+ : workState === "result_available"+ ? taskStatusForRun(taskResultRun ?? childRun)+ : taskStatusForRun(taskResultRun ?? childRun) === "queued"+ ? "queued"+ : "running";+ const derivedResult =+ task.result !== null+ ? task.result+ : taskResultRun !== undefined && isTerminalTaskStatus(status)+ ? subagentResultForRun(childProjection, taskResultRun).text+ : null;+ const resultTransfers = parentProjection.contextTransfers.filter(+ (transfer) =>+ transfer.type === "subagent_result" &&+ transfer.sourceThreadId === task.childThreadId &&+ transfer.targetThreadId === scope.thread.threadId,+ );+ const resultTransferForRun = (run: OrchestrationV2Run | undefined) =>+ !canExposeTaskRunResult(run)+ ? null+ : (resultTransfers.find((transfer) => transfer.sourcePoint.runId === run.id) ??+ (run.id === childRun?.id+ ? resultTransfers.find((transfer) => transfer.sourcePoint.runId === undefined)+ : undefined) ??+ null);+ const resultTransfer = taskResultTransfer(parentProjection, childProjection, task) ?? null;+ const terminalStatus = terminalRun === undefined ? null : taskStatusForRun(terminalRun);+ const latestTerminalSummary = canExposeTaskRunResult(terminalRun)+ ? terminalRun.id === childRun?.id+ ? derivedResult+ : subagentResultForRun(childProjection, terminalRun).text+ : null;+ const resultContextTransferId = resultTransfer?.id ?? null;+ const latestTerminalResultContextTransferId = resultTransferForRun(terminalRun)?.id ?? null;+ const response = {+ taskId: task.id,+ childThreadId: task.childThreadId,+ childRunId: childRun?.id ?? null,+ childNodeId: task.id,+ status,+ workState,+ hasPendingChildRuns: hasPendingChildRuns(childProjection, childRun),+ providerInstanceId: task.providerInstanceId,+ model: task.model,+ summary: derivedResult,+ resultContextTransferId,+ latestTerminalRunId: terminalRun?.id ?? null,+ latestTerminalStatus:+ terminalStatus !== null && isTerminalTaskStatus(terminalStatus) ? terminalStatus : null,+ latestTerminalSummary: latestTerminalSummary === derivedResult ? null : latestTerminalSummary,+ latestTerminalResultContextTransferId:+ latestTerminalResultContextTransferId === resultContextTransferId+ ? null+ : latestTerminalResultContextTransferId,+ hasPendingQuestion:+ !isTerminalTaskStatus(status) &&+ childControls.runtimeRequests.some(+ (request) =>+ request.kind === "user_input" &&+ request.status === "pending" &&+ request.responseCapability.type === "live",),- ];- const resultRecords = yield* threadManagement- .getThreadRecords(task.childThreadId, ["messages", "turnItems"], {- messageRoles: ["assistant"],- messageRunIds: resultRunIds,- turnItemRunIds: resultRunIds,- turnItemTypes: ["assistant_message", "error"],+ waitTimedOut,+ } satisfies OrchestratorMcpDelegateTaskResult;+ if (+ acknowledgeTerminal &&+ isTerminalTaskStatus(status) &&+ task.completionDelivery?.state !== "acknowledged" &&+ task.completionDelivery?.state !== "disposed"+ ) {+ const observingRun = ThreadManagementService.latestActiveRun(parentProjection);+ const acknowledgementRequestKey = yield* requestKey(undefined);+ yield* threadManagement+ .dispatch({+ type: "delegated_task.completion-delivery.acknowledge",+ commandId: stableCommandId({+ scope,+ requestKey: acknowledgementRequestKey,+ operation: acknowledgementOperation,+ }),+ parentThreadId: scope.thread.threadId,+ taskId,+ observedByRunId:+ observingRun?.providerInstanceId === scope.thread.providerInstanceId+ ? observingRun.id+ : null,})- .pipe(Effect.mapError(threadManagementFailure));- const childProjection = {- ...childControls,- messages: [...childControls.messages, ...resultRecords.messages],- turnItems: resultRecords.turnItems,- };- const heldForRestart =- task.result === null &&- taskWorkState === "result_available" &&- (yield* threadManagement- .delegatedTaskResultPending(task.childThreadId, childRun?.delegatedTaskId)- .pipe(Effect.mapError(threadManagementFailure)));- const workState =- task.result !== null ? "result_available" : heldForRestart ? "working" : taskWorkState;- const status =- task.result !== null- ? taskStatusForRun(- task.status === "completed" ||- task.status === "failed" ||- task.status === "cancelled" ||- task.status === "interrupted"- ? { status: task.status }- : childRun,- )- : workState === "result_available"- ? taskStatusForRun(taskResultRun ?? childRun)- : taskStatusForRun(taskResultRun ?? childRun) === "queued"- ? "queued"- : "running";- const derivedResult =- task.result !== null- ? task.result- : taskResultRun !== undefined && isTerminalTaskStatus(status)- ? subagentResultForRun(childProjection, taskResultRun).text- : null;- const resultTransfers = parentProjection.contextTransfers.filter(- (transfer) =>- transfer.type === "subagent_result" &&- transfer.sourceThreadId === task.childThreadId &&- transfer.targetThreadId === scope.thread.threadId,- );- const resultTransferForRun = (run: OrchestrationV2Run | undefined) =>- !canExposeTaskRunResult(run)- ? null- : (resultTransfers.find((transfer) => transfer.sourcePoint.runId === run.id) ??- (run.id === childRun?.id- ? resultTransfers.find((transfer) => transfer.sourcePoint.runId === undefined)- : undefined) ??- null);- const resultTransfer = taskResultTransfer(parentProjection, childProjection, task) ?? null;- const terminalStatus = terminalRun === undefined ? null : taskStatusForRun(terminalRun);- const latestTerminalSummary = canExposeTaskRunResult(terminalRun)- ? terminalRun.id === childRun?.id- ? derivedResult- : subagentResultForRun(childProjection, terminalRun).text- : null;- const resultContextTransferId = resultTransfer?.id ?? null;- const latestTerminalResultContextTransferId = resultTransferForRun(terminalRun)?.id ?? null;- const response = {- taskId: task.id,- childThreadId: task.childThreadId,- childRunId: childRun?.id ?? null,- childNodeId: task.id,- status,- workState,- hasPendingChildRuns: hasPendingChildRuns(childProjection, childRun),- providerInstanceId: task.providerInstanceId,- model: task.model,- summary: derivedResult,- resultContextTransferId,- latestTerminalRunId: terminalRun?.id ?? null,- latestTerminalStatus:- terminalStatus !== null && isTerminalTaskStatus(terminalStatus) ? terminalStatus : null,- latestTerminalSummary:- latestTerminalSummary === derivedResult ? null : latestTerminalSummary,- latestTerminalResultContextTransferId:- latestTerminalResultContextTransferId === resultContextTransferId- ? null- : latestTerminalResultContextTransferId,- hasPendingQuestion:- !isTerminalTaskStatus(status) &&- childControls.runtimeRequests.some(- (request) =>- request.kind === "user_input" &&- request.status === "pending" &&- request.responseCapability.type === "live",- ),- waitTimedOut,- } satisfies OrchestratorMcpDelegateTaskResult;- if (- acknowledgeTerminal &&- isTerminalTaskStatus(status) &&- task.completionDelivery?.state !== "acknowledged" &&- task.completionDelivery?.state !== "disposed"- ) {- const observingRun = ThreadManagementService.latestActiveRun(parentProjection);- const acknowledgementRequestKey = yield* requestKey(undefined);- yield* threadManagement- .dispatch({- type: "delegated_task.completion-delivery.acknowledge",- commandId: stableCommandId({- scope,- requestKey: acknowledgementRequestKey,- operation: acknowledgementOperation,- }),- parentThreadId: scope.thread.threadId,- taskId,- observedByRunId:- observingRun?.providerInstanceId === scope.thread.providerInstanceId- ? observingRun.id- : null,- })- .pipe(- Effect.mapError((error) =>- failure(- "orchestration_error",- `Unable to acknowledge delegated task ${taskId}: ${errorMessage(error)}`,- ),+ .pipe(+ Effect.mapError((error) =>+ failure(+ "orchestration_error",+ `Unable to acknowledge delegated task ${taskId}: ${errorMessage(error)}`,),- );- }- return response;- });+ ),+ );+ }+ return response;+ });- const waitForTask = (scope: McpThreadInvocationScope, taskId: NodeId, timeoutMs: number) =>- Effect.gen(function* () {+ const waitForTask = Effect.fn("OrchestratorMcpService.waitForTask")(+ function* (scope: McpThreadInvocationScope, taskId: NodeId, _timeoutMs: number) {const streamError = (error: unknown) =>failure("orchestration_error",@@ -1559,17 +1557,21 @@ const make = Effect.gen(function* () {Stream.filter((result) => result.hasPendingQuestion || isTerminalTaskStatus(result.status)),Stream.runHead,);- }).pipe(Effect.timeoutOption(Duration.millis(timeoutMs)), Effect.map(Option.flatten));+ },+ (effect, _scope, _taskId, timeoutMs) =>+ effect.pipe(Effect.timeoutOption(Duration.millis(timeoutMs)), Effect.map(Option.flatten)),+ );- const scheduledTaskRunModes = (task: ScheduledTask) =>- Effect.gen(function* () {+ const scheduledTaskRunModes = Effect.fn("OrchestratorMcpService.scheduledTaskRunModes")(+ function* (task: ScheduledTask) {const modes = [{ runtimeMode: task.runtimeMode, interactionMode: task.interactionMode }];if (task.threadId === null) return modes;const bound = yield* threadManagement.getThreadShell(task.threadId).pipe(Effect.mapError(threadManagementFailure));return bound === null || bound.deletedAt !== null ? modes : [...modes, bound];- });+ },+ );const withinLimits = (limits: {@@ -1586,18 +1588,18 @@ const make = Effect.gen(function* () {* approved for read-only access, and a thread caller only with a live turn, at modes covering* every mode the task runs at.*/- const summarizeScheduledTask = (- scope: McpInvocationScope,- caller: {- readonly parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs"> | undefined;- readonly limits: {- readonly runtimeMode: RuntimeMode;- readonly interactionMode: ProviderInteractionMode;- };- },- task: ScheduledTask,- ) =>- Effect.gen(function* () {+ const summarizeScheduledTask = Effect.fn("OrchestratorMcpService.summarizeScheduledTask")(+ function* (+ scope: McpInvocationScope,+ caller: {+ readonly parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs"> | undefined;+ readonly limits: {+ readonly runtimeMode: RuntimeMode;+ readonly interactionMode: ProviderInteractionMode;+ };+ },+ task: ScheduledTask,+ ) {const live =caller.parent === undefined? scope.client?.access !== "read-only"@@ -1609,101 +1611,97 @@ const make = Effect.gen(function* () {Option.isSome(modes) &&modes.value.every((mode) => withinLimits(caller.limits, mode)),);- });+ },+ );/*** A scheduled task the caller may change: one whose runs execute at modes no* broader than the caller's own, so editing its prompt cannot run work above* the caller's limits.*/- const loadScheduledTask = (+ const loadScheduledTask = Effect.fn("OrchestratorMcpService.loadScheduledTask")(function* (scheduledTaskId: ScheduledTask["id"],limits: {readonly runtimeMode: RuntimeMode;readonly interactionMode: ProviderInteractionMode;},- ): Effect.Effect<ScheduledTask, OrchestratorMcpFailure> =>- Effect.gen(function* () {- const { tasks } = yield* scheduledTasks- .list()+ ): Effect.fn.Return<ScheduledTask, OrchestratorMcpFailure> {+ const { tasks } = yield* scheduledTasks+ .list()+ .pipe(+ Effect.mapError((error) =>+ failure("orchestration_error", `Could not load scheduled task: ${error.message}`),+ ),+ );+ const task = tasks.find((candidate) => candidate.id === scheduledTaskId);+ if (task === undefined) {+ return yield* failure("task_not_found", `Scheduled task ${scheduledTaskId} was not found.`);+ }+ for (const modes of yield* scheduledTaskRunModes(task)) {+ yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode);+ yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode);+ }+ return task;+ });++ return OrchestratorMcpService.of({+ scheduleTask: Effect.fn("OrchestratorMcpService.scheduleTask")(function* (scope, input) {+ const { parent, limits } = yield* loadCaller(scope);+ const projectId = yield* resolveProjectTarget(parent, input.projectId);+ yield* assertLiveCallerForOtherProject(scope, parent, projectId);+ const project = yield* requireProject(projectId);+ const bindToCurrentThread =+ input.bindToCurrentThread ??+ (parent !== undefined && parent.thread.projectId === projectId);+ if (bindToCurrentThread && (parent === undefined || parent.thread.projectId !== projectId)) {+ return yield* failure(+ "invalid_request",+ parent === undefined+ ? "bindToCurrentThread needs an agent running inside a T3 thread."+ : "bindToCurrentThread binds to this thread, which belongs to a different project.",+ );+ }+ const modelSelection =+ parent?.thread.modelSelection ?? (yield* projectDefaultModelSelection(project));+ const derivedTitle = input.prompt.split("\n")[0]?.trim() ?? "";+ const title =+ input.title ?? (derivedTitle.length > 0 ? derivedTitle.slice(0, 80) : "Scheduled task");+ const upsertInput: ScheduledTaskUpsertInput = {+ title,+ prompt: input.prompt,+ enabled: input.enabled ?? true,+ schedule: input.schedule,+ projectId,+ threadId: bindToCurrentThread && parent !== undefined ? parent.thread.id : null,+ workspaceStrategy: scheduledTaskWorkspaceStrategy(bindToCurrentThread),+ modelSelection,+ runtimeMode: limits.runtimeMode,+ interactionMode: limits.interactionMode,+ createdBy: "agent",+ creationSource: "mcp",+ // Scope the idempotency key by provider session so two callers+ // reusing the same clientRequestId cannot collide on one task row.+ ...(input.clientRequestId === undefined+ ? {}+ : {+ commandId: stableCommandId({+ scope,+ requestKey: input.clientRequestId,+ operation: "schedule-task",+ }),+ }),+ };+ const { task } = yield* scheduledTasks+ .upsert(upsertInput).pipe(Effect.mapError((error) =>- failure("orchestration_error", `Could not load scheduled task: ${error.message}`),+ failure("orchestration_error", `Could not schedule task: ${error.message}`),),);- const task = tasks.find((candidate) => candidate.id === scheduledTaskId);- if (task === undefined) {- return yield* failure("task_not_found", `Scheduled task ${scheduledTaskId} was not found.`);- }- for (const modes of yield* scheduledTaskRunModes(task)) {- yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode);- yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode);- }- return task;- });-- return OrchestratorMcpService.of({- scheduleTask: (scope, input) =>- Effect.gen(function* () {- const { parent, limits } = yield* loadCaller(scope);- const projectId = yield* resolveProjectTarget(parent, input.projectId);- yield* assertLiveCallerForOtherProject(scope, parent, projectId);- const project = yield* requireProject(projectId);- const bindToCurrentThread =- input.bindToCurrentThread ??- (parent !== undefined && parent.thread.projectId === projectId);- if (- bindToCurrentThread &&- (parent === undefined || parent.thread.projectId !== projectId)- ) {- return yield* failure(- "invalid_request",- parent === undefined- ? "bindToCurrentThread needs an agent running inside a T3 thread."- : "bindToCurrentThread binds to this thread, which belongs to a different project.",- );- }- const modelSelection =- parent?.thread.modelSelection ?? (yield* projectDefaultModelSelection(project));- const derivedTitle = input.prompt.split("\n")[0]?.trim() ?? "";- const title =- input.title ?? (derivedTitle.length > 0 ? derivedTitle.slice(0, 80) : "Scheduled task");- const upsertInput: ScheduledTaskUpsertInput = {- title,- prompt: input.prompt,- enabled: input.enabled ?? true,- schedule: input.schedule,- projectId,- threadId: bindToCurrentThread && parent !== undefined ? parent.thread.id : null,- workspaceStrategy: scheduledTaskWorkspaceStrategy(bindToCurrentThread),- modelSelection,- runtimeMode: limits.runtimeMode,- interactionMode: limits.interactionMode,- createdBy: "agent",- creationSource: "mcp",- // Scope the idempotency key by provider session so two callers- // reusing the same clientRequestId cannot collide on one task row.- ...(input.clientRequestId === undefined- ? {}- : {- commandId: stableCommandId({- scope,- requestKey: input.clientRequestId,- operation: "schedule-task",- }),- }),- };- const { task } = yield* scheduledTasks- .upsert(upsertInput)- .pipe(- Effect.mapError((error) =>- failure("orchestration_error", `Could not schedule task: ${error.message}`),- ),- );- return yield* summarizeScheduledTask(scope, { parent, limits }, task);- }),- listScheduledTasks: (scope, input) =>- Effect.gen(function* () {+ return yield* summarizeScheduledTask(scope, { parent, limits }, task);+ }),+ listScheduledTasks: Effect.fn("OrchestratorMcpService.listScheduledTasks")(+ function* (scope, input) {const { parent, limits } = yield* loadCaller(scope);const projectId = input.projectId ?? parent?.thread.projectId;const { tasks } = yield* scheduledTasks@@ -1719,9 +1717,10 @@ const make = Effect.gen(function* () {(task) => summarizeScheduledTask(scope, { parent, limits }, task),),};- }),- updateScheduledTask: (scope, input) =>- Effect.gen(function* () {+ },+ ),+ updateScheduledTask: Effect.fn("OrchestratorMcpService.updateScheduledTask")(+ function* (scope, input) {const { parent, limits } = yield* loadCaller(scope);const existing = yield* loadScheduledTask(input.scheduledTaskId, limits);yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId);@@ -1772,9 +1771,10 @@ const make = Effect.gen(function* () {),);return yield* summarizeScheduledTask(scope, { parent, limits }, task);- }),- deleteScheduledTask: (scope, input) =>- Effect.gen(function* () {+ },+ ),+ deleteScheduledTask: Effect.fn("OrchestratorMcpService.deleteScheduledTask")(+ function* (scope, input) {const { parent, limits } = yield* loadCaller(scope);const existing = yield* loadScheduledTask(input.scheduledTaskId, limits);yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId);@@ -1786,545 +1786,541 @@ const make = Effect.gen(function* () {),);return { scheduledTaskId: existing.id, deleted: true };- }),- requestSecret: (scope, input) =>- Effect.gen(function* () {- const { scope: threadScope, parent } = yield* loadThreadCaller(scope, "request_secret");- const threadId = threadScope.thread.threadId;- const run = ThreadManagementService.latestActiveRun(parent);- if (- run === undefined ||- run.rootNodeId === null ||- run.providerInstanceId !== threadScope.thread.providerInstanceId- ) {- return yield* failure(- "parent_not_active",- "Asking for a secret requires an active run owned by this MCP provider session.",- );- }- const runId = run.id;- const nodeId = run.rootNodeId;- const key = yield* requestKey(input.clientRequestId);- const turnItemId = TurnItemId.make(- `turn-item:secret-request:${stablePart(threadId)}:${stablePart(key)}`,+ },+ ),+ requestSecret: Effect.fn("OrchestratorMcpService.requestSecret")(function* (scope, input) {+ const { scope: threadScope, parent } = yield* loadThreadCaller(scope, "request_secret");+ const threadId = threadScope.thread.threadId;+ const run = ThreadManagementService.latestActiveRun(parent);+ if (+ run === undefined ||+ run.rootNodeId === null ||+ run.providerInstanceId !== threadScope.thread.providerInstanceId+ ) {+ return yield* failure(+ "parent_not_active",+ "Asking for a secret requires an active run owned by this MCP provider session.",);- const record = (secretStatus: "pending" | "cancelled") =>- threadManagement- .dispatch({- type: "secret_request.record",- commandId: stableCommandId({- scope,- requestKey: key,- operation: `secret-${secretStatus}`,- }),- threadId: threadId,- runId,- nodeId,- turnItemId,- label: input.label,- reason: input.reason,- ...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }),- secretStatus,+ }+ const runId = run.id;+ const nodeId = run.rootNodeId;+ const key = yield* requestKey(input.clientRequestId);+ const turnItemId = TurnItemId.make(+ `turn-item:secret-request:${stablePart(threadId)}:${stablePart(key)}`,+ );+ const record = (secretStatus: "pending" | "cancelled") =>+ threadManagement+ .dispatch({+ type: "secret_request.record",+ commandId: stableCommandId({+ scope,+ requestKey: key,+ operation: `secret-${secretStatus}`,+ }),+ threadId: threadId,+ runId,+ nodeId,+ turnItemId,+ label: input.label,+ reason: input.reason,+ ...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }),+ secretStatus,+ })+ .pipe(+ Effect.mapError((error) =>+ failure(+ "orchestration_error",+ `Could not record the secret request: ${errorMessage(error)}`,+ ),+ ),+ );+ yield* record("pending");+ // Only this call can hand the agent its ref, so the card must not+ // outlive it: a timeout, a failed wait or an aborted call closes it as+ // cancelled.+ const closeCard = record("cancelled").pipe(+ Effect.catch((error) =>+ Effect.logWarning("Could not close a secret request card", { error: error.message }),+ ),+ );++ const answered = yield* Effect.gen(function* () {+ while (true) {+ const projection = yield* threadManagement+ .getThreadRecords(threadId, ["runs", "turnItems"], {+ turnItemTypes: ["secret_request"],+ messageRoles: [],}).pipe(Effect.mapError((error) =>failure("orchestration_error",- `Could not record the secret request: ${errorMessage(error)}`,+ `Unable to read the secret request: ${errorMessage(error)}`,),),);- yield* record("pending");- // Only this call can hand the agent its ref, so the card must not- // outlive it: a timeout, a failed wait or an aborted call closes it as- // cancelled.- const closeCard = record("cancelled").pipe(- Effect.catch((error) =>- Effect.logWarning("Could not close a secret request card", { error: error.message }),+ const item = projection.turnItems.find((candidate) => candidate.id === turnItemId);+ if (item?.type === "secret_request" && item.secretStatus !== "pending") {+ return item.secretStatus;+ }+ const current = projection.runs.find((candidate) => candidate.id === runId);+ if (+ current === undefined ||+ ThreadManagementService.isTerminalRunStatus(current.status)+ ) {+ yield* record("cancelled");+ return "cancelled" as const;+ }+ yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS));+ }+ }).pipe(+ Effect.timeoutOption(+ Duration.millis(+ Math.min(input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS),),+ ),+ Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : closeCard)),+ );+ if (Option.isNone(answered)) yield* closeCard;+ const status = Option.isSome(answered)+ ? answered.value+ : yield* threadManagement+ .getThreadRecords(threadId, ["turnItems"], {+ turnItemTypes: ["secret_request"],+ messageRoles: [],+ })+ .pipe(+ Effect.map((records) => {+ const item = records.turnItems.find((candidate) => candidate.id === turnItemId);+ return item?.type === "secret_request" &&+ (item.secretStatus === "saved" || item.secretStatus === "declined")+ ? item.secretStatus+ : ("timed_out" as const);+ }),+ Effect.orElseSucceed(() => "timed_out" as const),+ );+ yield* Effect.annotateCurrentSpan({ "secret_request.status": status });+ yield* Metrics.increment(Metrics.secretRequestsTotal, { status });+ if (status !== "saved") return { status };+ const secretRef = yield* secretRequests.savedRef({ threadId: threadId, turnItemId });+ if (Option.isNone(secretRef)) {+ return yield* failure(+ "orchestration_error",+ "The user saved the secret, but it could not be read. Ask again with a new clientRequestId.",);+ }+ return { status, secretRef: secretRef.value };+ }),- const answered = yield* Effect.gen(function* () {- while (true) {- const projection = yield* threadManagement- .getThreadRecords(threadId, ["runs", "turnItems"], {- turnItemTypes: ["secret_request"],- messageRoles: [],- })- .pipe(- Effect.mapError((error) =>- failure(- "orchestration_error",- `Unable to read the secret request: ${errorMessage(error)}`,- ),- ),- );- const item = projection.turnItems.find((candidate) => candidate.id === turnItemId);- if (item?.type === "secret_request" && item.secretStatus !== "pending") {- return item.secretStatus;- }- const current = projection.runs.find((candidate) => candidate.id === runId);- if (- current === undefined ||- ThreadManagementService.isTerminalRunStatus(current.status)- ) {- yield* record("cancelled");- return "cancelled" as const;- }- yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS));- }- }).pipe(- Effect.timeoutOption(- Duration.millis(- Math.min(input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS),- ),- ),- Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : closeCard)),- );- if (Option.isNone(answered)) yield* closeCard;- const status = Option.isSome(answered)- ? answered.value- : yield* threadManagement- .getThreadRecords(threadId, ["turnItems"], {- turnItemTypes: ["secret_request"],- messageRoles: [],- })- .pipe(- Effect.map((records) => {- const item = records.turnItems.find((candidate) => candidate.id === turnItemId);- return item?.type === "secret_request" &&- (item.secretStatus === "saved" || item.secretStatus === "declined")- ? item.secretStatus- : ("timed_out" as const);- }),- Effect.orElseSucceed(() => "timed_out" as const),- );- yield* Effect.annotateCurrentSpan({ "secret_request.status": status });- yield* Metrics.increment(Metrics.secretRequestsTotal, { status });- if (status !== "saved") return { status };- const secretRef = yield* secretRequests.savedRef({ threadId: threadId, turnItemId });- if (Option.isNone(secretRef)) {- return yield* failure(- "orchestration_error",- "The user saved the secret, but it could not be read. Ask again with a new clientRequestId.",+ capabilities: Effect.fn("OrchestratorMcpService.capabilities")(function* (scope) {+ const { parent, limits } = yield* loadCaller(scope);+ const providers = yield* loadProviders;+ const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds();+ const modelPreferences = yield* serverSettings.getSettings.pipe(+ Effect.map((settings) => settings.providerModelPreferences ?? {}),+ Effect.mapError(() => failure("orchestration_error", "Unable to read server settings.")),+ );+ return {+ parentThreadId: parent?.thread.id ?? null,+ inheritedProviderInstanceId: parent?.thread.modelSelection.instanceId ?? null,+ inheritedModel: parent?.thread.modelSelection.model ?? null,+ runtimeMode: limits.runtimeMode,+ interactionMode: limits.interactionMode,+ providers: providers.map((provider) => {+ const constraints = providerConstraints(+ provider,+ orchestrationCapableInstanceIds.has(provider.instanceId),);- }- return { status, secretRef: secretRef.value };- }).pipe(Effect.withSpan("OrchestratorMcpService.requestSecret")),-- capabilities: (scope) =>- Effect.gen(function* () {- const { parent, limits } = yield* loadCaller(scope);- const providers = yield* loadProviders;- const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds();- const modelPreferences = yield* serverSettings.getSettings.pipe(- Effect.map((settings) => settings.providerModelPreferences ?? {}),- Effect.mapError(() => failure("orchestration_error", "Unable to read server settings.")),+ return {+ providerInstanceId: provider.instanceId,+ driverKind: provider.driver,+ displayName: provider?.displayName ?? null,+ models:+ provider?.models+ .filter(+ (model) =>+ model.isCustom ||+ !modelPreferences[provider.instanceId]?.hiddenModels.includes(model.slug),+ )+ .map((model) => ({+ id: model.slug,+ label: model.name ?? null,+ ...(model.capabilities?.optionDescriptors === undefined+ ? {}+ : { options: model.capabilities.optionDescriptors }),+ })) ?? [],+ ...(provider.supportedRuntimeModes === undefined ||+ provider.supportedRuntimeModes.length === 0+ ? {}+ : { runtimeModes: [...provider.supportedRuntimeModes] }),+ canRunChildTask: constraints.length === 0,+ canRunCrossProviderChildTask: constraints.length === 0,+ constraints: [...constraints],+ };+ }),+ features: {+ appOwnedSubagents: true,+ asyncPolling: true,+ cancellation: true,+ batchThreadCreation: true,+ threadManagement: true,+ incrementalThreadRead: true,+ scheduledTasks: true,+ maxBatchThreads: 20,+ },+ };+ }),+ delegateTask: Effect.fn("OrchestratorMcpService.delegateTask")(function* (callerScope, input) {+ const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task");+ const parentRun = parent.runs+ .filter(ThreadManagementService.isActiveRun)+ .toSorted((left, right) => right.ordinal - left.ordinal)[0];+ if (+ parentRun === undefined ||+ parentRun.rootNodeId === null ||+ parentRun.providerInstanceId !== scope.thread.providerInstanceId+ ) {+ return yield* failure(+ "parent_not_active",+ "Delegated tasks require an active run owned by this MCP provider session.",);- return {- parentThreadId: parent?.thread.id ?? null,- inheritedProviderInstanceId: parent?.thread.modelSelection.instanceId ?? null,- inheritedModel: parent?.thread.modelSelection.model ?? null,- runtimeMode: limits.runtimeMode,- interactionMode: limits.interactionMode,- providers: providers.map((provider) => {- const constraints = providerConstraints(- provider,- orchestrationCapableInstanceIds.has(provider.instanceId),- );- return {- providerInstanceId: provider.instanceId,- driverKind: provider.driver,- displayName: provider?.displayName ?? null,- models:- provider?.models- .filter(- (model) =>- model.isCustom ||- !modelPreferences[provider.instanceId]?.hiddenModels.includes(model.slug),- )- .map((model) => ({- id: model.slug,- label: model.name ?? null,- ...(model.capabilities?.optionDescriptors === undefined- ? {}- : { options: model.capabilities.optionDescriptors }),- })) ?? [],- ...(provider.supportedRuntimeModes === undefined ||- provider.supportedRuntimeModes.length === 0- ? {}- : { runtimeModes: [...provider.supportedRuntimeModes] }),- canRunChildTask: constraints.length === 0,- canRunCrossProviderChildTask: constraints.length === 0,- constraints: [...constraints],- };- }),- features: {- appOwnedSubagents: true,- asyncPolling: true,- cancellation: true,- batchThreadCreation: true,- threadManagement: true,- incrementalThreadRead: true,- scheduledTasks: true,- maxBatchThreads: 20,- },- };- }),- delegateTask: (callerScope, input) =>- Effect.gen(function* () {- const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task");- const parentRun = parent.runs- .filter(ThreadManagementService.isActiveRun)- .toSorted((left, right) => right.ordinal - left.ordinal)[0];- if (- parentRun === undefined ||- parentRun.rootNodeId === null ||- parentRun.providerInstanceId !== scope.thread.providerInstanceId- ) {- return yield* failure(- "parent_not_active",- "Delegated tasks require an active run owned by this MCP provider session.",+ }+ const providers = yield* loadProviders;+ const key = yield* requestKey(input.clientRequestId);+ const commandId = stableCommandId({+ scope,+ requestKey: key,+ operation: "delegate-task",+ });+ const isRetryOfAcceptedDelegation = yield* threadManagement.hasReceipt(commandId);+ const target = yield* resolveTargetRechecking({+ parent,+ target: input.target,+ providers,+ skipProjectEnablementFilter: isRetryOfAcceptedDelegation,+ });+ const runtimeMode = yield* resolveRuntimeMode(+ parent.thread.runtimeMode,+ input.runtimeMode,+ target,+ );+ const interactionMode = yield* resolveInteractionMode(+ parent.thread.interactionMode,+ input.interactionMode,+ );+ let workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined;+ if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) {+ const project = yield* requireProject(parent.thread.projectId);+ const base = yield* gitDriver+ .resolveCommit({+ cwd: parent.thread.worktreePath ?? project.workspaceRoot,+ revision: "HEAD",+ })+ .pipe(+ Effect.mapError(() =>+ failure("invalid_request", "Unable to resolve the parent checkout commit."),+ ),);- }- const providers = yield* loadProviders;- const key = yield* requestKey(input.clientRequestId);- const commandId = stableCommandId({- scope,- requestKey: key,- operation: "delegate-task",- });- const isRetryOfAcceptedDelegation = yield* threadManagement.hasReceipt(commandId);- const target = yield* resolveTargetRechecking({- parent,- target: input.target,- providers,- skipProjectEnablementFilter: isRetryOfAcceptedDelegation,- });- const runtimeMode = yield* resolveRuntimeMode(- parent.thread.runtimeMode,- input.runtimeMode,- target,- );- const interactionMode = yield* resolveInteractionMode(- parent.thread.interactionMode,- input.interactionMode,- );- let workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined;- if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) {- const project = yield* requireProject(parent.thread.projectId);- const base = yield* gitDriver- .resolveCommit({- cwd: parent.thread.worktreePath ?? project.workspaceRoot,- revision: "HEAD",- })+ // Launch preparation creates the worktree from the project root, so a+ // parent checkout in another repository (such as a Git folder inside+ // Scratch) would hand it a commit it cannot find.+ if (parent.thread.worktreePath !== null) {+ yield* gitDriver+ .resolveCommit({ cwd: project.workspaceRoot, revision: base.commitSha }).pipe(Effect.mapError(() =>- failure("invalid_request", "Unable to resolve the parent checkout commit."),+ failure(+ "invalid_request",+ `Isolation "worktree" creates the child checkout in project "${project.title}" (${project.workspaceRoot}), which does not contain the parent checkout's commit. Use isolation "shared" to work in the parent's checkout.`,+ ),),);- // Launch preparation creates the worktree from the project root, so a- // parent checkout in another repository (such as a Git folder inside- // Scratch) would hand it a commit it cannot find.- if (parent.thread.worktreePath !== null) {- yield* gitDriver- .resolveCommit({ cwd: project.workspaceRoot, revision: base.commitSha })+ }+ workspaceStrategy = { type: "worktree", baseRef: base.commitSha, startFromOrigin: false };+ }+ // ThreadManagementService.dispatch is the chokepoint for this command+ // type's own enablement check, using the same command id and its+ // receipt-replay exemption, so no separate assert runs here.+ const result = yield* threadManagement+ .dispatch({+ type: "delegated_task.request",+ createdBy: "agent",+ creationSource: "mcp",+ commandId,+ parentThreadId: scope.thread.threadId,+ parentRunId: parentRun.id,+ parentNodeId: parentRun.rootNodeId,+ task: taskPrompt(input),+ ...(input.title === undefined ? {} : { title: input.title }),+ modelSelection: target.modelSelection,+ runtimeMode,+ interactionMode,+ ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),+ // Async delegations wake the parent on every child terminal; wait+ // delegations deliver through the blocking tool call, so a wake is+ // only needed if the parent settled first (timeout, disconnect).+ completionWake: input.mode === "wait" ? "settled_only" : "always",+ })+ .pipe(+ Effect.mapError((error) =>+ error._tag === "ThreadManagementProviderInstanceDisabledError"+ ? threadManagementFailure(error)+ : failure(+ "orchestration_error",+ `Unable to create delegated task: ${errorMessage(error)}`,+ ),+ ),+ );+ const taskEvent = result.storedEvents.find(+ (stored) =>+ stored.event.type === "subagent.updated" && stored.event.payload.origin === "app_owned",+ );+ if (taskEvent?.event.type !== "subagent.updated") {+ return yield* failure(+ "orchestration_error",+ "Delegated task command did not produce a task projection.",+ );+ }+ const taskId = taskEvent.event.payload.id;+ const childThreadId = taskEvent.event.payload.childThreadId;+ const childRunEvent = result.storedEvents.find(+ (stored) => stored.event.type === "run.created" && stored.event.threadId === childThreadId,+ );+ if (+ childThreadId !== null &&+ childRunEvent?.event.type === "run.created" &&+ childRunEvent.event.payload.workspacePreparation !== undefined+ ) {+ yield* threadLaunch.prepareRun({+ commandId,+ threadId: childThreadId,+ runId: childRunEvent.event.payload.id,+ });+ }++ if (input.mode !== "wait") {+ return yield* readTask(scope, taskId, false, true);+ }+ const timeoutMs = Math.min(+ MAX_WAIT_TIMEOUT_MS,+ Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),+ );+ const waited = yield* waitForTask(scope, taskId, timeoutMs);+ if (Option.isSome(waited) && isTerminalTaskStatus(waited.value.status)) {+ return waited.value;+ }+ // An incomplete wait gives up delivery: upgrade so a later terminal+ // wakes the parent even mid-turn.+ yield* threadManagement+ .dispatch({+ type: "delegated_task.wake-policy",+ commandId: stableCommandId({+ scope,+ requestKey: key,+ operation: "delegate-task-wake-policy",+ }),+ parentThreadId: scope.thread.threadId,+ taskId,+ completionWake: "always",+ })+ .pipe(+ Effect.catch((error) =>+ Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {+ taskId,+ outcome:+ error._tag === "OrchestratorCommandPreviouslyRejectedError"+ ? "previously_rejected"+ : "dispatch_failed",+ error,+ }),+ ),+ Effect.catchCause((cause) =>+ Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {+ taskId,+ outcome: "defect",+ cause,+ }),+ ),+ );+ return yield* readTask(scope, taskId, Option.isNone(waited), true);+ }),+ taskStatus: Effect.fn("OrchestratorMcpService.taskStatus")(function* (callerScope, taskId) {+ const scope = yield* requireThreadScope(callerScope, "task_status");+ return yield* readTask(scope, taskId, false, true);+ }),+ cancelTask: Effect.fn("OrchestratorMcpService.cancelTask")(function* (callerScope, input) {+ const scope = yield* requireThreadScope(callerScope, "task_cancel");+ const current = yield* readTask(scope, input.taskId);+ const key = yield* requestKey(input.clientRequestId);+ const parentProjection = yield* loadProjection(scope.thread.threadId);+ // Cancelling stops the child and every task under it, each a write to a+ // thread its user may have raised above the parent's modes since it was+ // delegated. All of them are checked before anything is stopped.+ const assertStoppable = Effect.fn("OrchestratorMcpService.assertStoppable")(function* (+ threadId: ThreadId,+ ): Effect.fn.Return<void, OrchestratorMcpFailure> {+ const shell = yield* threadManagement+ .getThreadShell(threadId)+ .pipe(Effect.mapError(threadManagementFailure));+ if (shell !== null && shell.deletedAt === null) {+ yield* resolveRuntimeMode(parentProjection.thread.runtimeMode, shell.runtimeMode);+ yield* resolveInteractionMode(+ parentProjection.thread.interactionMode,+ shell.interactionMode,+ );+ }+ const { subagents } = yield* threadManagement+ .getThreadRecords(threadId, ["subagents"])+ .pipe(Effect.mapError(threadManagementFailure));+ for (const task of subagents) {+ if (task.origin === "app_owned" && task.childThreadId !== null) {+ yield* assertStoppable(task.childThreadId);+ }+ }+ });+ yield* assertStoppable(current.childThreadId);+ const parentTask = parentProjection.subagents.find(+ (task) => task.id === input.taskId && task.origin === "app_owned",+ );+ const disposeCompletionDelivery =+ parentTask?.completionDelivery?.state === "disposed"+ ? Effect.void+ : threadManagement+ .dispatch({+ type: "delegated_task.completion-delivery.dispose",+ commandId: stableCommandId({+ scope,+ requestKey: key,+ operation: "cancel-task-completion-delivery",+ }),+ parentThreadId: scope.thread.threadId,+ taskId: input.taskId,+ }).pipe(- Effect.mapError(() =>+ Effect.asVoid,+ Effect.mapError((error) =>failure(- "invalid_request",- `Isolation "worktree" creates the child checkout in project "${project.title}" (${project.workspaceRoot}), which does not contain the parent checkout's commit. Use isolation "shared" to work in the parent's checkout.`,+ "orchestration_error",+ `Unable to dispose delegated task ${input.taskId} completion delivery: ${errorMessage(error)}`,),),);- }- workspaceStrategy = { type: "worktree", baseRef: base.commitSha, startFromOrigin: false };- }- // ThreadManagementService.dispatch is the chokepoint for this command- // type's own enablement check, using the same command id and its- // receipt-replay exemption, so no separate assert runs here.- const result = yield* threadManagement+ const stopChild = Effect.gen(function* () {+ const commandId = stableCommandId({ scope, requestKey: key, operation: "cancel-task" });+ const reason = input.reason;+ yield* threadManagement.dispatch({- type: "delegated_task.request",- createdBy: "agent",- creationSource: "mcp",+ type: "thread.stop",commandId,- parentThreadId: scope.thread.threadId,- parentRunId: parentRun.id,- parentNodeId: parentRun.rootNodeId,- task: taskPrompt(input),- ...(input.title === undefined ? {} : { title: input.title }),- modelSelection: target.modelSelection,- runtimeMode,- interactionMode,- ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),- // Async delegations wake the parent on every child terminal; wait- // delegations deliver through the blocking tool call, so a wake is- // only needed if the parent settled first (timeout, disconnect).- completionWake: input.mode === "wait" ? "settled_only" : "always",+ threadId: current.childThreadId,+ ...(reason === undefined ? {} : { reason }),}).pipe(Effect.mapError((error) =>- error._tag === "ThreadManagementProviderInstanceDisabledError"- ? threadManagementFailure(error)- : failure(- "orchestration_error",- `Unable to create delegated task: ${errorMessage(error)}`,- ),+ failure(+ "task_not_cancellable",+ `Unable to stop delegated task ${input.taskId}: ${errorMessage(error)}`,+ ),),);- const taskEvent = result.storedEvents.find(- (stored) =>- stored.event.type === "subagent.updated" && stored.event.payload.origin === "app_owned",- );- if (taskEvent?.event.type !== "subagent.updated") {- return yield* failure(- "orchestration_error",- "Delegated task command did not produce a task projection.",- );- }- const taskId = taskEvent.event.payload.id;- const childThreadId = taskEvent.event.payload.childThreadId;- const childRunEvent = result.storedEvents.find(- (stored) =>- stored.event.type === "run.created" && stored.event.threadId === childThreadId,- );- if (- childThreadId !== null &&- childRunEvent?.event.type === "run.created" &&- childRunEvent.event.payload.workspacePreparation !== undefined- ) {- yield* threadLaunch.prepareRun({- commandId,- threadId: childThreadId,- runId: childRunEvent.event.payload.id,- });- }-- if (input.mode !== "wait") {- return yield* readTask(scope, taskId, false, true);- }- const timeoutMs = Math.min(- MAX_WAIT_TIMEOUT_MS,- Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),- );- const waited = yield* waitForTask(scope, taskId, timeoutMs);- if (Option.isSome(waited) && isTerminalTaskStatus(waited.value.status)) {- return waited.value;- }- // An incomplete wait gives up delivery: upgrade so a later terminal- // wakes the parent even mid-turn.yield* threadManagement- .dispatch({- type: "delegated_task.wake-policy",- commandId: stableCommandId({- scope,- requestKey: key,- operation: "delegate-task-wake-policy",- }),- parentThreadId: scope.thread.threadId,- taskId,- completionWake: "always",- })+ .stopDelegatedTasks({ threadId: current.childThreadId, commandId, reason }).pipe(- Effect.catch((error) =>- Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {- taskId,- outcome:- error._tag === "OrchestratorCommandPreviouslyRejectedError"- ? "previously_rejected"- : "dispatch_failed",- error,- }),- ),- Effect.catchCause((cause) =>- Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {- taskId,- outcome: "defect",- cause,- }),+ Effect.mapError((error) =>+ failure(+ "task_not_cancellable",+ `Stopped delegated task ${input.taskId}, but not every task it delegated: ${errorMessage(error)}`,+ ),),);- return yield* readTask(scope, taskId, Option.isNone(waited), true);- }),- taskStatus: (callerScope, taskId) =>- Effect.gen(function* () {- const scope = yield* requireThreadScope(callerScope, "task_status");- return yield* readTask(scope, taskId, false, true);- }),- cancelTask: (callerScope, input) =>- Effect.gen(function* () {- const scope = yield* requireThreadScope(callerScope, "task_cancel");- const current = yield* readTask(scope, input.taskId);- const key = yield* requestKey(input.clientRequestId);- const parentProjection = yield* loadProjection(scope.thread.threadId);- // Cancelling stops the child and every task under it, each a write to a- // thread its user may have raised above the parent's modes since it was- // delegated. All of them are checked before anything is stopped.- const assertStoppable = (threadId: ThreadId): Effect.Effect<void, OrchestratorMcpFailure> =>- Effect.gen(function* () {- const shell = yield* threadManagement- .getThreadShell(threadId)- .pipe(Effect.mapError(threadManagementFailure));- if (shell !== null && shell.deletedAt === null) {- yield* resolveRuntimeMode(parentProjection.thread.runtimeMode, shell.runtimeMode);- yield* resolveInteractionMode(- parentProjection.thread.interactionMode,- shell.interactionMode,- );- }- const { subagents } = yield* threadManagement- .getThreadRecords(threadId, ["subagents"])- .pipe(Effect.mapError(threadManagementFailure));- for (const task of subagents) {- if (task.origin === "app_owned" && task.childThreadId !== null) {- yield* assertStoppable(task.childThreadId);- }- }- });- yield* assertStoppable(current.childThreadId);- const parentTask = parentProjection.subagents.find(- (task) => task.id === input.taskId && task.origin === "app_owned",- );- const disposeCompletionDelivery =- parentTask?.completionDelivery?.state === "disposed"- ? Effect.void- : threadManagement- .dispatch({- type: "delegated_task.completion-delivery.dispose",- commandId: stableCommandId({- scope,- requestKey: key,- operation: "cancel-task-completion-delivery",- }),- parentThreadId: scope.thread.threadId,- taskId: input.taskId,- })- .pipe(- Effect.asVoid,- Effect.mapError((error) =>- failure(- "orchestration_error",- `Unable to dispose delegated task ${input.taskId} completion delivery: ${errorMessage(error)}`,- ),- ),- );- const stopChild = Effect.gen(function* () {- const commandId = stableCommandId({ scope, requestKey: key, operation: "cancel-task" });- const reason = input.reason;+ const stopped = yield* threadManagement+ .getThreadRecords(current.childThreadId, ["runs"])+ .pipe(Effect.mapError(threadManagementFailure));+ for (const run of stopped.runs) {+ if (+ run.status !== "queued" ||+ (run.delegatedTaskId !== input.taskId && run.id !== current.childRunId)+ )+ continue;+ // Stop preserves the queue for Resume. Cancelling a task must also+ // remove that task's queued turn, including a previously held one.yield* threadManagement.dispatch({- type: "thread.stop",- commandId,+ type: "queued-run.cancel",+ commandId: stableCommandId({+ scope,+ requestKey: key,+ operation: `cancel-task-queued-run:${run.id}`,+ }),threadId: current.childThreadId,- ...(reason === undefined ? {} : { reason }),+ runId: run.id,})- .pipe(- Effect.mapError((error) =>- failure(- "task_not_cancellable",- `Unable to stop delegated task ${input.taskId}: ${errorMessage(error)}`,- ),- ),- );- yield* threadManagement- .stopDelegatedTasks({ threadId: current.childThreadId, commandId, reason })- .pipe(- Effect.mapError((error) =>- failure(- "task_not_cancellable",- `Stopped delegated task ${input.taskId}, but not every task it delegated: ${errorMessage(error)}`,- ),- ),- );- const stopped = yield* threadManagement- .getThreadRecords(current.childThreadId, ["runs"]).pipe(Effect.mapError(threadManagementFailure));- for (const run of stopped.runs) {- if (- run.status !== "queued" ||- (run.delegatedTaskId !== input.taskId && run.id !== current.childRunId)- )- continue;- // Stop preserves the queue for Resume. Cancelling a task must also- // remove that task's queued turn, including a previously held one.- yield* threadManagement- .dispatch({- type: "queued-run.cancel",- commandId: stableCommandId({- scope,- requestKey: key,- operation: `cancel-task-queued-run:${run.id}`,- }),- threadId: current.childThreadId,- runId: run.id,- })- .pipe(Effect.mapError(threadManagementFailure));- }- });- // Checked above; a user raising one of these threads meanwhile is- // caught again under that thread's lock, which leaves it running.- const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);- const stopWithinLimit = stopChild.pipe(- Effect.provideService(DispatchModeLimit, {- runtimeMode: parentProjection.thread.runtimeMode,- interactionMode: parentProjection.thread.interactionMode,- refused,- }),- Effect.catch((error) =>- Effect.flatMap(Ref.get(refused), (refusal) =>- Effect.fail(- refusal === undefined- ? error- : failure(- refusal.mode === "runtime"- ? "runtime_mode_escalation_denied"- : "interaction_mode_escalation_denied",- `Thread ${refusal.threadId} now runs in ${refusal.runtimeMode}/${refusal.interactionMode} mode, above this thread's; its user changed it while the task was being cancelled.`,- ),- ),+ }+ });+ // Checked above; a user raising one of these threads meanwhile is+ // caught again under that thread's lock, which leaves it running.+ const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);+ const stopWithinLimit = stopChild.pipe(+ Effect.provideService(DispatchModeLimit, {+ runtimeMode: parentProjection.thread.runtimeMode,+ interactionMode: parentProjection.thread.interactionMode,+ refused,+ }),+ Effect.catch((error) =>+ Effect.flatMap(Ref.get(refused), (refusal) =>+ Effect.fail(+ refusal === undefined+ ? error+ : failure(+ refusal.mode === "runtime"+ ? "runtime_mode_escalation_denied"+ : "interaction_mode_escalation_denied",+ `Thread ${refusal.threadId} now runs in ${refusal.runtimeMode}/${refusal.interactionMode} mode, above this thread's; its user changed it while the task was being cancelled.`,+ ),),),- );- if (isTerminalTaskStatus(current.status)) {- yield* stopWithinLimit;- yield* disposeCompletionDelivery;- return {- taskId: input.taskId,- status: current.status,- } satisfies OrchestratorMcpTaskCancelResult;- }- const child = yield* loadProjection(current.childThreadId);- if (- current.workState !== "waiting_for_children" &&- ThreadManagementService.latestActiveRun(child) === undefined &&- !child.runs.some(- (run) =>- run.status === "queued" &&- (run.delegatedTaskId === input.taskId || run.id === current.childRunId),- )- ) {- return yield* failure(- "task_not_cancellable",- `Delegated task ${input.taskId} has no interruptible child run.`,- );- }+ ),+ );+ if (isTerminalTaskStatus(current.status)) {yield* stopWithinLimit;- yield* disposeCompletionDelivery.pipe(- Effect.catchCause((cause) =>- Effect.logWarning("orchestrator-mcp.cancel-task.delivery-dispose-failed", {- taskId: input.taskId,- cause,- }),- ),- );+ yield* disposeCompletionDelivery;return {taskId: input.taskId,- status: "cancel_requested",- };- }),- createThreads: (callerScope, input) =>- Effect.gen(function* () {+ status: current.status,+ } satisfies OrchestratorMcpTaskCancelResult;+ }+ const child = yield* loadProjection(current.childThreadId);+ if (+ current.workState !== "waiting_for_children" &&+ ThreadManagementService.latestActiveRun(child) === undefined &&+ !child.runs.some(+ (run) =>+ run.status === "queued" &&+ (run.delegatedTaskId === input.taskId || run.id === current.childRunId),+ )+ ) {+ return yield* failure(+ "task_not_cancellable",+ `Delegated task ${input.taskId} has no interruptible child run.`,+ );+ }+ yield* stopWithinLimit;+ yield* disposeCompletionDelivery.pipe(+ Effect.catchCause((cause) =>+ Effect.logWarning("orchestrator-mcp.cancel-task.delivery-dispose-failed", {+ taskId: input.taskId,+ cause,+ }),+ ),+ );+ return {+ taskId: input.taskId,+ status: "cancel_requested",+ };+ }),+ createThreads: Effect.fn("OrchestratorMcpService.createThreads")(+ function* (callerScope, input) {const { scope, parent } = yield* loadThreadCaller(callerScope, "create_threads");const parentRun = ThreadManagementService.latestActiveRun(parent);if (@@ -2490,263 +2486,253 @@ const make = Effect.gen(function* () {{ concurrency: 1 },);return { threads: created };- }),- listThreads: (scope, input) =>- Effect.gen(function* () {- const { parent } = yield* loadCaller(scope);- const projectId = yield* resolveProjectTarget(parent, input.projectId);- const projectThreads = yield* threadManagement- .listProjectThreads({- projectId,- includeSubagents: input.includeSubagents !== false,- })- .pipe(- Effect.mapError((error) =>- failure("orchestration_error", `Unable to list threads: ${errorMessage(error)}`),- ),- );- const nowMs = yield* Clock.currentTimeMillis;- const statuses = input.statuses === undefined ? null : new Set(input.statuses);- const titleContains = input.titleContains?.toLocaleLowerCase();- const filtered = projectThreads- .filter(- (thread) =>- statuses === null || statuses.has(thread.activityRunStatus ?? thread.status),- )- .filter(- (thread) =>- input.settled === undefined || threadSettlement(thread).settled === input.settled,- )- .filter(- (thread) => input.snoozed === undefined || isSnoozed(thread, nowMs) === input.snoozed,- )- .filter(- (thread) =>- titleContains === undefined ||- thread.title.toLocaleLowerCase().includes(titleContains),- );- const cursor = input.cursor ?? 0;- const limit = input.limit ?? DEFAULT_THREAD_LIST_LIMIT;- const page = filtered.slice(cursor, cursor + limit);- const nextCursor = cursor + page.length < filtered.length ? cursor + page.length : null;- return {+ },+ ),+ listThreads: Effect.fn("OrchestratorMcpService.listThreads")(function* (scope, input) {+ const { parent } = yield* loadCaller(scope);+ const projectId = yield* resolveProjectTarget(parent, input.projectId);+ const projectThreads = yield* threadManagement+ .listProjectThreads({projectId,- currentThreadId: parent?.thread.id ?? null,- threads: page.map((shell) => listItemFromShell(shell, nowMs)),- nextCursor,- total: filtered.length,- } satisfies OrchestratorMcpThreadListResult;- }),- readThread: (scope, input) =>- Effect.gen(function* () {- const { parent, target, shell } = yield* loadReadableThread(scope, input.threadId);- const view = input.view ?? "messages";- const afterPosition = input.afterPosition ?? -1;- const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT;- const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS;- const timeline = yield* threadManagement- .getTimelinePage(input.threadId, {- afterPosition,- limit,- view,- ...(input.itemId === undefined ? {} : { itemId: input.itemId }),- })- .pipe(Effect.mapError(threadManagementFailure));- const page = timeline.items;- const messageIdsByThread = new Map<ThreadId, Array<MessageId>>();- for (const row of page) {- if (row.item.type !== "user_message" && row.item.type !== "assistant_message") continue;- const ids = messageIdsByThread.get(row.sourceThreadId) ?? [];- ids.push(row.item.messageId);- messageIdsByThread.set(row.sourceThreadId, ids);- }- const sourceMessages = yield* Effect.forEach(- [...messageIdsByThread],- ([threadId, messageIds]) =>- threadManagement.getThreadRecords(threadId, ["messages"], { messageIds }).pipe(- Effect.map((records) => [threadId, records.messages] as const),- Effect.mapError(threadManagementFailure),- ),- { concurrency: 1 },+ includeSubagents: input.includeSubagents !== false,+ })+ .pipe(+ Effect.mapError((error) =>+ failure("orchestration_error", `Unable to list threads: ${errorMessage(error)}`),+ ),);- const messagesByThreadId = new Map(sourceMessages);- const returnedRunIds = new Set(- page- .filter((row) => row.sourceThreadId === target.thread.id)- .map((row) => row.item.runId),+ const nowMs = yield* Clock.currentTimeMillis;+ const statuses = input.statuses === undefined ? null : new Set(input.statuses);+ const titleContains = input.titleContains?.toLocaleLowerCase();+ const filtered = projectThreads+ .filter(+ (thread) => statuses === null || statuses.has(thread.activityRunStatus ?? thread.status),+ )+ .filter(+ (thread) =>+ input.settled === undefined || threadSettlement(thread).settled === input.settled,+ )+ .filter(+ (thread) => input.snoozed === undefined || isSnoozed(thread, nowMs) === input.snoozed,+ )+ .filter(+ (thread) =>+ titleContains === undefined || thread.title.toLocaleLowerCase().includes(titleContains),);- const tasks =- parent === undefined ? [] : directAppOwnedChildTasks(parent, target, returnedRunIds);- if (- parent !== undefined &&- scope.thread !== undefined &&- tasks.length > 0 &&- (input.textOffset ?? 0) === 0- ) {- for (const task of tasks) {- const transfer = taskResultTransfer(parent, target, task);- const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id;- const resultRunIds = resultRunId === undefined ? [] : [resultRunId];- const resultRecords = yield* threadManagement- .getThreadRecords(target.thread.id, ["messages", "turnItems"], {- messageRoles: ["assistant"],- messageRunIds: resultRunIds,- turnItemRunIds: resultRunIds,- turnItemTypes: ["assistant_message", "error"],- })- .pipe(Effect.mapError(threadManagementFailure));- if (- pageIncludesTerminalTaskResult({- parent,- page,- task,- target: { ...target, ...resultRecords },- maxChars,- })- ) {- yield* readTask(- scope as McpThreadInvocationScope,- task.id,- false,- true,- "thread-read-acknowledge",- );- }+ const cursor = input.cursor ?? 0;+ const limit = input.limit ?? DEFAULT_THREAD_LIST_LIMIT;+ const page = filtered.slice(cursor, cursor + limit);+ const nextCursor = cursor + page.length < filtered.length ? cursor + page.length : null;+ return {+ projectId,+ currentThreadId: parent?.thread.id ?? null,+ threads: page.map((shell) => listItemFromShell(shell, nowMs)),+ nextCursor,+ total: filtered.length,+ } satisfies OrchestratorMcpThreadListResult;+ }),+ readThread: Effect.fn("OrchestratorMcpService.readThread")(function* (scope, input) {+ const { parent, target, shell } = yield* loadReadableThread(scope, input.threadId);+ const view = input.view ?? "messages";+ const afterPosition = input.afterPosition ?? -1;+ const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT;+ const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS;+ const timeline = yield* threadManagement+ .getTimelinePage(input.threadId, {+ afterPosition,+ limit,+ view,+ ...(input.itemId === undefined ? {} : { itemId: input.itemId }),+ })+ .pipe(Effect.mapError(threadManagementFailure));+ const page = timeline.items;+ const messageIdsByThread = new Map<ThreadId, Array<MessageId>>();+ for (const row of page) {+ if (row.item.type !== "user_message" && row.item.type !== "assistant_message") continue;+ const ids = messageIdsByThread.get(row.sourceThreadId) ?? [];+ ids.push(row.item.messageId);+ messageIdsByThread.set(row.sourceThreadId, ids);+ }+ const sourceMessages = yield* Effect.forEach(+ [...messageIdsByThread],+ ([threadId, messageIds]) =>+ threadManagement.getThreadRecords(threadId, ["messages"], { messageIds }).pipe(+ Effect.map((records) => [threadId, records.messages] as const),+ Effect.mapError(threadManagementFailure),+ ),+ { concurrency: 1 },+ );+ const messagesByThreadId = new Map(sourceMessages);+ const returnedRunIds = new Set(+ page.filter((row) => row.sourceThreadId === target.thread.id).map((row) => row.item.runId),+ );+ const tasks =+ parent === undefined ? [] : directAppOwnedChildTasks(parent, target, returnedRunIds);+ if (+ parent !== undefined &&+ scope.thread !== undefined &&+ tasks.length > 0 &&+ (input.textOffset ?? 0) === 0+ ) {+ for (const task of tasks) {+ const transfer = taskResultTransfer(parent, target, task);+ const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id;+ const resultRunIds = resultRunId === undefined ? [] : [resultRunId];+ const resultRecords = yield* threadManagement+ .getThreadRecords(target.thread.id, ["messages", "turnItems"], {+ messageRoles: ["assistant"],+ messageRunIds: resultRunIds,+ turnItemRunIds: resultRunIds,+ turnItemTypes: ["assistant_message", "error"],+ })+ .pipe(Effect.mapError(threadManagementFailure));+ if (+ pageIncludesTerminalTaskResult({+ parent,+ page,+ task,+ target: { ...target, ...resultRecords },+ maxChars,+ })+ ) {+ yield* readTask(+ scope as McpThreadInvocationScope,+ task.id,+ false,+ true,+ "thread-read-acknowledge",+ );}}- return {- thread: threadDetail(target, timeline.totalItems, shell, yield* Clock.currentTimeMillis),- recentRuns: target.runs- .toSorted((left, right) => right.ordinal - left.ordinal)- .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT)- .map(threadRun),- items: page.map((row) =>- timelineItem({- row,- maxChars,- messagesByThreadId,- ...(input.itemId === undefined ? {} : { textOffset: input.textOffset ?? 0 }),- }),- ),- nextPosition: page.at(-1)?.position ?? null,- hasMore: timeline.hasMore,- } satisfies OrchestratorMcpThreadReadResult;- }),- sendToThread: (scope, input) =>- Effect.gen(function* () {- const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId);- yield* assertLiveCallerForOtherThread(scope, parent, target);- yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode);- yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode);-- const mode = input.mode ?? "auto";- const key = yield* requestKey(input.clientRequestId);- const messageId = stableOperationMessageId({- scope,- requestKey: key,- operation: "thread-send",- });- const result = yield* threadManagement- .sendToThread({- projectId: target.thread.projectId,- commandId: stableCommandId({- scope,- requestKey: key,- operation: "thread-send",- }),- threadId: input.threadId,- ...(parent === undefined ? {} : { senderThreadId: parent.thread.id }),- messageId,- text: input.message,- attachments: [],- mode,- createdBy: "agent",- creationSource: "mcp",- })- .pipe(- Effect.mapError((error) =>- isThreadManagementError(error)- ? threadManagementFailure(error)- : failure(- "orchestration_error",- `Unable to send to thread ${input.threadId}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,- ),- ),- );- return {+ }+ return {+ thread: threadDetail(target, timeline.totalItems, shell, yield* Clock.currentTimeMillis),+ recentRuns: target.runs+ .toSorted((left, right) => right.ordinal - left.ordinal)+ .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT)+ .map(threadRun),+ items: page.map((row) =>+ timelineItem({+ row,+ maxChars,+ messagesByThreadId,+ ...(input.itemId === undefined ? {} : { textOffset: input.textOffset ?? 0 }),+ }),+ ),+ nextPosition: page.at(-1)?.position ?? null,+ hasMore: timeline.hasMore,+ } satisfies OrchestratorMcpThreadReadResult;+ }),+ sendToThread: Effect.fn("OrchestratorMcpService.sendToThread")(function* (scope, input) {+ const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId);+ yield* assertLiveCallerForOtherThread(scope, parent, target);+ yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode);+ yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode);++ const mode = input.mode ?? "auto";+ const key = yield* requestKey(input.clientRequestId);+ const messageId = stableOperationMessageId({+ scope,+ requestKey: key,+ operation: "thread-send",+ });+ const result = yield* threadManagement+ .sendToThread({+ projectId: target.thread.projectId,+ commandId: stableCommandId({+ scope,+ requestKey: key,+ operation: "thread-send",+ }),threadId: input.threadId,+ ...(parent === undefined ? {} : { senderThreadId: parent.thread.id }),messageId,- runId: result.run.id,- ...(result.run.delegatedTaskId === undefined- ? {}- : { taskId: result.run.delegatedTaskId }),- status: result.run.status,- delivery: result.delivery,- } satisfies OrchestratorMcpThreadSendResult;- }),- waitForThread: (scope, input) =>- Effect.gen(function* () {- const { target } = yield* loadScopedThread(scope, input.threadId);- const result = yield* threadManagement- .waitForThread({- projectId: target.thread.projectId,- threadId: input.threadId,- ...(input.runId === undefined ? {} : { runId: input.runId }),- timeoutMs: Math.min(- MAX_WAIT_TIMEOUT_MS,- Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),- ),- })- .pipe(Effect.mapError(threadManagementFailure));- return {+ text: input.message,+ attachments: [],+ mode,+ createdBy: "agent",+ creationSource: "mcp",+ })+ .pipe(+ Effect.mapError((error) =>+ isThreadManagementError(error)+ ? threadManagementFailure(error)+ : failure(+ "orchestration_error",+ `Unable to send to thread ${input.threadId}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,+ ),+ ),+ );+ return {+ threadId: input.threadId,+ messageId,+ runId: result.run.id,+ ...(result.run.delegatedTaskId === undefined ? {} : { taskId: result.run.delegatedTaskId }),+ status: result.run.status,+ delivery: result.delivery,+ } satisfies OrchestratorMcpThreadSendResult;+ }),+ waitForThread: Effect.fn("OrchestratorMcpService.waitForThread")(function* (scope, input) {+ const { target } = yield* loadScopedThread(scope, input.threadId);+ const result = yield* threadManagement+ .waitForThread({+ projectId: target.thread.projectId,threadId: input.threadId,- runId: result.run?.id ?? null,- status: result.run === null ? "idle" : runOutcome(result.run),- timedOut: result.timedOut,- } satisfies OrchestratorMcpThreadWaitResult;- }),- interruptThread: (scope, input) =>- Effect.gen(function* () {- const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId);- yield* assertLiveCallerForOtherThread(scope, parent, target);- yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode);- yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode);- const key = yield* requestKey(input.clientRequestId);- const result = yield* threadManagement- .interruptThread({- projectId: target.thread.projectId,- commandId: stableCommandId({- scope,- requestKey: key,- operation: "thread-interrupt",- }),- threadId: input.threadId,- ...(input.runId === undefined ? {} : { runId: input.runId }),- ...(input.reason === undefined ? {} : { reason: input.reason }),- })- .pipe(- Effect.mapError((error) =>- isThreadManagementError(error)- ? threadManagementFailure(error)- : failure(- "orchestration_error",- `Unable to interrupt thread ${input.threadId}: ${errorMessage(error)}`,- ),- ),- );- if (result.type === "no_active_run") {- return {- threadId: input.threadId,- runId: null,- status: "no_active_run",- } satisfies OrchestratorMcpThreadInterruptResult;- }+ ...(input.runId === undefined ? {} : { runId: input.runId }),+ timeoutMs: Math.min(+ MAX_WAIT_TIMEOUT_MS,+ Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),+ ),+ })+ .pipe(Effect.mapError(threadManagementFailure));+ return {+ threadId: input.threadId,+ runId: result.run?.id ?? null,+ status: result.run === null ? "idle" : runOutcome(result.run),+ timedOut: result.timedOut,+ } satisfies OrchestratorMcpThreadWaitResult;+ }),+ interruptThread: Effect.fn("OrchestratorMcpService.interruptThread")(function* (scope, input) {+ const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId);+ yield* assertLiveCallerForOtherThread(scope, parent, target);+ yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode);+ yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode);+ const key = yield* requestKey(input.clientRequestId);+ const result = yield* threadManagement+ .interruptThread({+ projectId: target.thread.projectId,+ commandId: stableCommandId({+ scope,+ requestKey: key,+ operation: "thread-interrupt",+ }),+ threadId: input.threadId,+ ...(input.runId === undefined ? {} : { runId: input.runId }),+ ...(input.reason === undefined ? {} : { reason: input.reason }),+ })+ .pipe(+ Effect.mapError((error) =>+ isThreadManagementError(error)+ ? threadManagementFailure(error)+ : failure(+ "orchestration_error",+ `Unable to interrupt thread ${input.threadId}: ${errorMessage(error)}`,+ ),+ ),+ );+ if (result.type === "no_active_run") {return {threadId: input.threadId,- runId: result.run.id,- status: result.type === "already_terminal" ? result.run.status : "interrupt_requested",+ runId: null,+ status: "no_active_run",} satisfies OrchestratorMcpThreadInterruptResult;- }),+ }+ return {+ threadId: input.threadId,+ runId: result.run.id,+ status: result.type === "already_terminal" ? result.run.status : "interrupt_requested",+ } satisfies OrchestratorMcpThreadInterruptResult;+ }),});});diff --git a/apps/server/src/mcp/toolkits/device/handlers.ts b/apps/server/src/mcp/toolkits/device/handlers.tsindex d42efd9168c..c4f3449a290 100644--- a/apps/server/src/mcp/toolkits/device/handlers.ts+++ b/apps/server/src/mcp/toolkits/device/handlers.ts@@ -69,46 +69,45 @@ const requireDeviceAccess = McpInvocationContext.requireThreadMcpCapability("dev),);-const pickDevice = (+const pickDevice = Effect.fn("handlers.pickDevice")(function* (devices: ReadonlyArray<DeviceSummary>,input: {readonly deviceId?: DeviceId | undefined;readonly platform?: DevicePlatform | undefined;readonly hostId?: DeviceHostId | undefined;},-): Effect.Effect<DeviceSummary, DeviceToolUnavailableError> =>- Effect.gen(function* () {- const hostId = input.hostId ?? LOCAL_DEVICE_HOST_ID;- if (input.deviceId !== undefined) {- const match = devices.find(- (device) => device.hostId === hostId && device.id === input.deviceId,- );- if (match) return match;- return yield* new DeviceToolUnavailableError({- reason: `No device ${input.deviceId} on host ${hostId}. Call device_list for current ids.`,- });- }- const candidates = devices.filter(- (device) =>- device.hostId === hostId &&- (input.platform === undefined || device.platform === input.platform),+): Effect.fn.Return<DeviceSummary, DeviceToolUnavailableError> {+ const hostId = input.hostId ?? LOCAL_DEVICE_HOST_ID;+ if (input.deviceId !== undefined) {+ const match = devices.find(+ (device) => device.hostId === hostId && device.id === input.deviceId,);- if (candidates.length === 0) {- return yield* new DeviceToolUnavailableError({- reason:- input.platform === undefined- ? "No simulators or emulators were found. Call device_list to see why."- : `No ${input.platform} devices were found on host ${hostId}. Call device_list to see why.`,- });- }- const platforms = new Set(candidates.map((device) => device.platform));- if (input.platform === undefined && platforms.size > 1) {- return yield* new DeviceToolUnavailableError({- reason: "Both iOS and Android devices are available; pass platform or deviceId.",- });- }- return candidates.find((device) => device.booted) ?? candidates[0]!;- });+ if (match) return match;+ return yield* new DeviceToolUnavailableError({+ reason: `No device ${input.deviceId} on host ${hostId}. Call device_list for current ids.`,+ });+ }+ const candidates = devices.filter(+ (device) =>+ device.hostId === hostId &&+ (input.platform === undefined || device.platform === input.platform),+ );+ if (candidates.length === 0) {+ return yield* new DeviceToolUnavailableError({+ reason:+ input.platform === undefined+ ? "No simulators or emulators were found. Call device_list to see why."+ : `No ${input.platform} devices were found on host ${hostId}. Call device_list to see why.`,+ });+ }+ const platforms = new Set(candidates.map((device) => device.platform));+ if (input.platform === undefined && platforms.size > 1) {+ return yield* new DeviceToolUnavailableError({+ reason: "Both iOS and Android devices are available; pass platform or deviceId.",+ });+ }+ return candidates.find((device) => device.booted) ?? candidates[0]!;+});const toolError = (error: DeviceError | DeviceToolUnavailableError) => error;diff --git a/apps/server/src/preview/DesktopBrowserChannel.ts b/apps/server/src/preview/DesktopBrowserChannel.tsindex 02ff6997397..0d1db856c1e 100644--- a/apps/server/src/preview/DesktopBrowserChannel.ts+++ b/apps/server/src/preview/DesktopBrowserChannel.ts@@ -130,65 +130,64 @@ const make = Effect.gen(function* () {Effect.forkScoped,);- const endpoint = (key: DesktopTabKey) =>- Effect.gen(function* () {- const id = keyOf(key);- const secret = NodeCrypto.randomBytes(24).toString("base64url");- const server = yield* NodeSocketServer.makeWebSocket({- host: "127.0.0.1",- port: 0,- path: `/${secret}`,- }).pipe(Effect.orDie);- const queue = yield* Queue.unbounded<string>();- inbound.set(id, queue);- // A detach before this registration shut down no queue, so check again.- if (!attachedTabs.has(id)) {- inbound.delete(id);- return yield* Effect.die("The desktop tab detached before the server connected.");- }- yield* Effect.addFinalizer(() =>+ const endpoint = Effect.fn("DesktopBrowserChannel.endpoint")(function* (key: DesktopTabKey) {+ const id = keyOf(key);+ const secret = NodeCrypto.randomBytes(24).toString("base64url");+ const server = yield* NodeSocketServer.makeWebSocket({+ host: "127.0.0.1",+ port: 0,+ path: `/${secret}`,+ }).pipe(Effect.orDie);+ const queue = yield* Queue.unbounded<string>();+ inbound.set(id, queue);+ // A detach before this registration shut down no queue, so check again.+ if (!attachedTabs.has(id)) {+ inbound.delete(id);+ return yield* Effect.die("The desktop tab detached before the server connected.");+ }+ yield* Effect.addFinalizer(() =>+ Effect.gen(function* () {+ if (inbound.get(id) === queue) inbound.delete(id);+ yield* Queue.shutdown(queue);+ yield* command({ type: "release", ...key });+ }),+ );+ // The relay serves one Playwright connection; a second would see the first's sessions.+ let connected = false;+ yield* server+ .run((socket) =>Effect.gen(function* () {- if (inbound.get(id) === queue) inbound.delete(id);- yield* Queue.shutdown(queue);- yield* command({ type: "release", ...key });- }),- );- // The relay serves one Playwright connection; a second would see the first's sessions.- let connected = false;- yield* server- .run((socket) =>- Effect.gen(function* () {- if (connected) return;- connected = true;- const writer = yield* socket.writer;- const reader = yield* socket.reader;- yield* Stream.fromQueue(queue).pipe(- Stream.runForEach((message) => writer.write(message)),- Effect.forkScoped,- );- const decoder = new TextDecoder();- return yield* reader.pull.pipe(- Effect.flatMap((frames) =>- Effect.forEach(- frames,- (frame) =>- command({- type: "cdp",- ...key,- message: typeof frame === "string" ? frame : decoder.decode(frame),- }),- { discard: true },- ),+ if (connected) return;+ connected = true;+ const writer = yield* socket.writer;+ const reader = yield* socket.reader;+ yield* Stream.fromQueue(queue).pipe(+ Stream.runForEach((message) => writer.write(message)),+ Effect.forkScoped,+ );+ const decoder = new TextDecoder();+ return yield* reader.pull.pipe(+ Effect.flatMap((frames) =>+ Effect.forEach(+ frames,+ (frame) =>+ command({+ type: "cdp",+ ...key,+ message: typeof frame === "string" ? frame : decoder.decode(frame),+ }),+ { discard: true },),- Effect.forever,- );- }).pipe(Effect.scoped, Effect.ignore),- )- .pipe(Effect.forkScoped);- const address = server.address;- if (address._tag !== "InetAddressV4") return yield* Effect.die("Unexpected relay address.");- return `ws://127.0.0.1:${address.port}/${secret}`;- });+ ),+ Effect.forever,+ );+ }).pipe(Effect.scoped, Effect.ignore),+ )+ .pipe(Effect.forkScoped);+ const address = server.address;+ if (address._tag !== "InetAddressV4") return yield* Effect.die("Unexpected relay address.");+ return `ws://127.0.0.1:${address.port}/${secret}`;+ });return DesktopBrowserChannel.of({available: true,diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.tsindex 03a9f76c415..d9626784c32 100644--- a/apps/server/src/preview/ServerBrowser.ts+++ b/apps/server/src/preview/ServerBrowser.ts@@ -1237,20 +1237,19 @@ const make = Effect.gen(function* () {return opening;};- const findTab = (threadId: string, tabId: string) =>- Effect.gen(function* () {- const existing = tabs.get(tabKey(threadId, tabId));- if (existing) return existing;- const { sessions } = yield* manager.list({ threadId: ThreadId.make(threadId) });- const snapshot = sessions.find(- (session) => session.tabId === tabId && session.runtime === "server",- );- if (!snapshot) return yield* new ServerBrowserTabNotFoundError({ threadId, tabId });- return yield* Effect.tryPromise({- try: () => ensureTab(snapshot),- catch: (cause) => (isTabNotFound(cause) ? cause : new ServerBrowserLaunchError({ cause })),- });+ const findTab = Effect.fn("ServerBrowser.findTab")(function* (threadId: string, tabId: string) {+ const existing = tabs.get(tabKey(threadId, tabId));+ if (existing) return existing;+ const { sessions } = yield* manager.list({ threadId: ThreadId.make(threadId) });+ const snapshot = sessions.find(+ (session) => session.tabId === tabId && session.runtime === "server",+ );+ if (!snapshot) return yield* new ServerBrowserTabNotFoundError({ threadId, tabId });+ return yield* Effect.tryPromise({+ try: () => ensureTab(snapshot),+ catch: (cause) => (isTabNotFound(cause) ? cause : new ServerBrowserLaunchError({ cause })),});+ });const atTabLimit = (agentSessionId: string) =>tabs.size + pendingTabs.size >= SERVER_TAB_LIMIT ||@@ -2220,209 +2219,209 @@ const make = Effect.gen(function* () {}};- const attachViewer: ServerBrowser["Service"]["attachViewer"] = (input) =>- Effect.gen(function* () {- const tab = yield* findTab(input.threadId, input.tabId);- const output = yield* Queue.make<ServerBrowserViewerOutput>({- capacity: VIEWER_OUTPUT_LIMIT,- strategy: "dropping",+ const attachViewer: ServerBrowser["Service"]["attachViewer"] = Effect.fn(+ "ServerBrowser.attachViewer",+ )(function* (input) {+ const tab = yield* findTab(input.threadId, input.tabId);+ const output = yield* Queue.make<ServerBrowserViewerOutput>({+ capacity: VIEWER_OUTPUT_LIMIT,+ strategy: "dropping",+ });+ const session = yield* Effect.acquireRelease(+ Effect.tryPromise({+ try: () => tab.page.context().newCDPSession(tab.page),+ catch: (cause) => new ServerBrowserLaunchError({ cause }),+ }),+ (session) =>+ Effect.promise(() =>+ session+ .send("Page.stopScreencast")+ .catch(constVoid)+ .then(() => session.detach())+ .catch(constVoid),+ ),+ );+ const quality = Math.min(100, Math.max(1, Math.round(input.quality)));+ // Chromium may drop the final frame during a burst; send a still when it settles.+ let framesInFlight = 0;+ let mayHaveDropped = false;+ let motion = false;+ const recentFrames: Array<number> = [];+ let screencastParams = Promise.resolve();+ let screencastScale = 1;+ const startScreencast = (scale: number) => {+ screencastScale = scale;+ screencastParams = screencastParams.then(async () => {+ if (tab.capturing > 0) return;+ await session.send("Page.stopScreencast").catch(constVoid);+ await session+ .send("Page.startScreencast", {+ format: "jpeg",+ quality: screencastScale < 1 ? Math.min(quality, SCREENCAST_MOTION_QUALITY) : quality,+ maxWidth: Math.max(1, Math.round(input.maxWidth * screencastScale)),+ maxHeight: Math.max(1, Math.round(input.maxHeight * screencastScale)),+ })+ .catch(constVoid);});- const session = yield* Effect.acquireRelease(- Effect.tryPromise({- try: () => tab.page.context().newCDPSession(tab.page),- catch: (cause) => new ServerBrowserLaunchError({ cause }),- }),- (session) =>- Effect.promise(() =>- session- .send("Page.stopScreencast")- .catch(constVoid)- .then(() => session.detach())- .catch(constVoid),- ),- );- const quality = Math.min(100, Math.max(1, Math.round(input.quality)));- // Chromium may drop the final frame during a burst; send a still when it settles.- let framesInFlight = 0;- let mayHaveDropped = false;- let motion = false;- const recentFrames: Array<number> = [];- let screencastParams = Promise.resolve();- let screencastScale = 1;- const startScreencast = (scale: number) => {- screencastScale = scale;- screencastParams = screencastParams.then(async () => {- if (tab.capturing > 0) return;- await session.send("Page.stopScreencast").catch(constVoid);- await session- .send("Page.startScreencast", {- format: "jpeg",- quality: screencastScale < 1 ? Math.min(quality, SCREENCAST_MOTION_QUALITY) : quality,- maxWidth: Math.max(1, Math.round(input.maxWidth * screencastScale)),- maxHeight: Math.max(1, Math.round(input.maxHeight * screencastScale)),- })- .catch(constVoid);- });+ return screencastParams;+ };+ const viewer: ViewerState = {+ id: NodeCrypto.randomUUID(),+ canOperate: input.canOperate,+ pressedKeys: new Map(),+ pressedButtons: new Map(),+ push: (next) => {+ // Dropped frames must still release Chromium.+ if (Queue.offerUnsafe(output, next)) return;+ if (next._tag === "frame") runFork(next.ack);+ // State a stalled viewer cannot miss replaces its backlog. It runs+ // synchronously so an older replacement can never land after a newer one.+ else if (next._tag === "gone" || next._tag === "control" || next._tag === "fileChooser") {+ const dropped = Effect.runSyncExit(Queue.clear(output));+ if (dropped._tag === "Failure") return;+ Queue.offerUnsafe(output, next);++ const chooser = next._tag === "control" ? fileChooserMessage(tab) : null;+ if (chooser && tab.control.controller === viewer.id) Queue.offerUnsafe(output, chooser);+ for (const item of dropped.value) if (item._tag === "frame") runFork(item.ack);+ }+ },+ pause: () => {+ screencastParams = screencastParams.then(() =>+ session.send("Page.stopScreencast").then(constVoid, constVoid),+ );return screencastParams;- };- const viewer: ViewerState = {- id: NodeCrypto.randomUUID(),- canOperate: input.canOperate,- pressedKeys: new Map(),- pressedButtons: new Map(),- push: (next) => {- // Dropped frames must still release Chromium.- if (Queue.offerUnsafe(output, next)) return;- if (next._tag === "frame") runFork(next.ack);- // State a stalled viewer cannot miss replaces its backlog. It runs- // synchronously so an older replacement can never land after a newer one.- else if (next._tag === "gone" || next._tag === "control" || next._tag === "fileChooser") {- const dropped = Effect.runSyncExit(Queue.clear(output));- if (dropped._tag === "Failure") return;- Queue.offerUnsafe(output, next);-- const chooser = next._tag === "control" ? fileChooserMessage(tab) : null;- if (chooser && tab.control.controller === viewer.id) Queue.offerUnsafe(output, chooser);- for (const item of dropped.value) if (item._tag === "frame") runFork(item.ack);- }- },- pause: () => {- screencastParams = screencastParams.then(() =>- session.send("Page.stopScreencast").then(constVoid, constVoid),- );- return screencastParams;- },- resume: () => startScreencast(screencastScale),- scrolledAt: 0,- requestedSize: null,- };- yield* Effect.acquireRelease(- Effect.sync(() => {- tab.viewers.add(viewer);+ },+ resume: () => startScreencast(screencastScale),+ scrolledAt: 0,+ requestedSize: null,+ };+ yield* Effect.acquireRelease(+ Effect.sync(() => {+ tab.viewers.add(viewer);+ reportLiveTabs();+ }),+ () =>+ Effect.promise(async () => {+ await tab.control.disconnect(viewer.id, () => releaseViewerInput(viewer, session));+ tab.viewers.delete(viewer);+ broadcastControl(tab);reportLiveTabs();}),- () =>- Effect.promise(async () => {- await tab.control.disconnect(viewer.id, () => releaseViewerInput(viewer, session));- tab.viewers.delete(viewer);- broadcastControl(tab);- reportLiveTabs();- }),- );- if (input.canOperate && tab.control.agentId === null && tab.control.controller === null) {- yield* Effect.promise(() => tab.control.take(viewer.id));- }- broadcastControl(tab);- pushFileChooser(tab);- // Full scale: a scaled capture would flash in every other viewer.- const pushStill = async () => {- const data = await withCaptureLock(tab, () =>- ServerBrowserPage.captureViewport(tab.page, session, {- format: "jpeg",- quality,- scale: 1,- }),- ).catch(() => null);- if (data)- viewer.push({ _tag: "frame", data: Buffer.from(data, "base64"), ack: Effect.void });- };- let settleTimer: ReturnType<typeof setTimeout> | null = null;- yield* Effect.addFinalizer(() =>- Effect.sync(() => {- if (settleTimer !== null) clearTimeout(settleTimer);+ );+ if (input.canOperate && tab.control.agentId === null && tab.control.controller === null) {+ yield* Effect.promise(() => tab.control.take(viewer.id));+ }+ broadcastControl(tab);+ pushFileChooser(tab);+ // Full scale: a scaled capture would flash in every other viewer.+ const pushStill = async () => {+ const data = await withCaptureLock(tab, () =>+ ServerBrowserPage.captureViewport(tab.page, session, {+ format: "jpeg",+ quality,+ scale: 1,}),- );- let screencastStarted = false;- session.on("Page.screencastFrame", (frame) => {- screencastStarted = true;- if (framesInFlight > 0) mayHaveDropped = true;- framesInFlight += 1;- const arrivedAt = Date.now();- recentFrames.push(arrivedAt);- while (recentFrames[0]! < arrivedAt - SCREENCAST_MOTION_WINDOW_MS) recentFrames.shift();- if (- !motion &&- recentFrames.length >= SCREENCAST_MOTION_FRAMES &&- arrivedAt - viewer.scrolledAt < SCREENCAST_MOTION_WINDOW_MS- ) {- motion = true;- void startScreencast(0.5);- } else if (motion && arrivedAt - viewer.scrolledAt > SCREENCAST_SETTLE_MS) {+ ).catch(() => null);+ if (data) viewer.push({ _tag: "frame", data: Buffer.from(data, "base64"), ack: Effect.void });+ };+ let settleTimer: ReturnType<typeof setTimeout> | null = null;+ yield* Effect.addFinalizer(() =>+ Effect.sync(() => {+ if (settleTimer !== null) clearTimeout(settleTimer);+ }),+ );+ let screencastStarted = false;+ session.on("Page.screencastFrame", (frame) => {+ screencastStarted = true;+ if (framesInFlight > 0) mayHaveDropped = true;+ framesInFlight += 1;+ const arrivedAt = Date.now();+ recentFrames.push(arrivedAt);+ while (recentFrames[0]! < arrivedAt - SCREENCAST_MOTION_WINDOW_MS) recentFrames.shift();+ if (+ !motion &&+ recentFrames.length >= SCREENCAST_MOTION_FRAMES &&+ arrivedAt - viewer.scrolledAt < SCREENCAST_MOTION_WINDOW_MS+ ) {+ motion = true;+ void startScreencast(0.5);+ } else if (motion && arrivedAt - viewer.scrolledAt > SCREENCAST_SETTLE_MS) {+ motion = false;+ recentFrames.length = 0;+ void startScreencast(1);+ }+ if (settleTimer !== null) clearTimeout(settleTimer);+ settleTimer = setTimeout(() => {+ settleTimer = null;+ if (!motion && !mayHaveDropped) return;+ mayHaveDropped = false;+ if (motion) {motion = false;recentFrames.length = 0;void startScreencast(1);}- if (settleTimer !== null) clearTimeout(settleTimer);- settleTimer = setTimeout(() => {- settleTimer = null;- if (!motion && !mayHaveDropped) return;- mayHaveDropped = false;- if (motion) {- motion = false;- recentFrames.length = 0;- void startScreencast(1);- }- void pushStill();- }, SCREENCAST_SETTLE_MS);- viewer.push({- _tag: "frame",- data: Buffer.from(frame.data, "base64"),- ack: Effect.promise(() =>- sleepUntil(arrivedAt + SCREENCAST_ACK_PACE_MS).then(() => {- framesInFlight -= 1;- return session- .send("Page.screencastFrameAck", { sessionId: frame.sessionId })- .catch(constVoid);- }),- ),- });+ void pushStill();+ }, SCREENCAST_SETTLE_MS);+ viewer.push({+ _tag: "frame",+ data: Buffer.from(frame.data, "base64"),+ ack: Effect.promise(() =>+ sleepUntil(arrivedAt + SCREENCAST_ACK_PACE_MS).then(() => {+ framesInFlight -= 1;+ return session+ .send("Page.screencastFrameAck", { sessionId: frame.sessionId })+ .catch(constVoid);+ }),+ ),});- broadcastViewport(tab);- yield* Effect.promise(() => startScreencast(1));- // An idle page does not repaint for a new screencast, so the viewer- // starts from a still unless a live frame beat it.- if (!screencastStarted) yield* Effect.promise(pushStill);- return {- output,- input: (raw: unknown) =>- Effect.promise(async () => {- if (!viewer.canOperate) return;- const message = asRecord(raw);- if (!message) return;- try {- if (message.type === "takeControl") {- const taking = tab.control.take(viewer.id);- broadcastControl(tab);- await taking;- pushFileChooser(tab);- } else if (message.type === "releaseControl") {- const releasing = tab.control.release(viewer.id, () =>- releaseViewerInput(viewer, session),- );- broadcastControl(tab);- await releasing;- } else if (- message.type === "dialog" &&- tab.control.controller === viewer.id &&- typeof message.accept === "boolean"- ) {- await resolveDialog(tab, {- accept: message.accept,- ...(typeof message.promptText === "string"- ? { promptText: message.promptText }- : {}),- });- } else {- await tab.control.human(viewer.id, () =>- dispatchViewerInput(tab, session, viewer, message),- );- }- } catch {+ });+ broadcastViewport(tab);+ yield* Effect.promise(() => startScreencast(1));+ // An idle page does not repaint for a new screencast, so the viewer+ // starts from a still unless a live frame beat it.+ if (!screencastStarted) yield* Effect.promise(pushStill);+ return {+ output,+ input: (raw: unknown) =>+ Effect.promise(async () => {+ if (!viewer.canOperate) return;+ const message = asRecord(raw);+ if (!message) return;+ try {+ if (message.type === "takeControl") {+ const taking = tab.control.take(viewer.id);+ broadcastControl(tab);+ await taking;+ pushFileChooser(tab);+ } else if (message.type === "releaseControl") {+ const releasing = tab.control.release(viewer.id, () =>+ releaseViewerInput(viewer, session),+ );broadcastControl(tab);+ await releasing;+ } else if (+ message.type === "dialog" &&+ tab.control.controller === viewer.id &&+ typeof message.accept === "boolean"+ ) {+ await resolveDialog(tab, {+ accept: message.accept,+ ...(typeof message.promptText === "string"+ ? { promptText: message.promptText }+ : {}),+ });+ } else {+ await tab.control.human(viewer.id, () =>+ dispatchViewerInput(tab, session, viewer, message),+ );}- }),- } satisfies ServerBrowserViewer;- });+ } catch {+ broadcastControl(tab);+ }+ }),+ } satisfies ServerBrowserViewer;+ });yield* manager.events.pipe(Stream.runForEach(mirrorManagerEvent), Effect.forkScoped);if (diff --git a/apps/server/src/preview/ServerBrowserStream.ts b/apps/server/src/preview/ServerBrowserStream.tsindex 536d3f2c192..ad42eaf5d72 100644--- a/apps/server/src/preview/ServerBrowserStream.ts+++ b/apps/server/src/preview/ServerBrowserStream.ts@@ -51,164 +51,164 @@ const parseMessage = (chunk: Uint8Array | string): unknown => {}};-const makeHandler = (browser: ServerBrowser.ServerBrowser["Service"]) =>- Effect.gen(function* () {- const request = yield* HttpServerRequest.HttpServerRequest;- const url = HttpServerRequest.toURL(request);- if (Option.isNone(url)) return HttpServerResponse.text("Bad Request", { status: 400 });- if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/download`) {- return yield* serveDownload(browser, url.value.searchParams);- }- if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/upload`) {- return request.method === "POST"- ? yield* receiveUpload(browser, url.value.searchParams)- : HttpServerResponse.text("Method Not Allowed", { status: 405 });- }- if (- url.value.pathname !== `${PREVIEW_STREAM_ROUTE_PREFIX}/ws` ||- request.headers.upgrade?.toLowerCase() !== "websocket"- ) {- return HttpServerResponse.text("Not Found", { status: 404 });- }- const session = yield* authenticateMediaRequest(AuthOrchestrationReadScope);- const params = url.value.searchParams;- const canOperate =- session.scopes.includes(AuthPreviewOperateScope) && params.get("interactive") !== "false";- const threadId = params.get("threadId") ?? "";- const tabId = params.get("tabId") ?? "";- if (threadId.length === 0 || tabId.length === 0) {- return HttpServerResponse.text("Not Found", { status: 404 });- }- return yield* Effect.scoped(- Effect.gen(function* () {- const attached = yield* browser- .attachViewer({- threadId,- tabId,- canOperate,- maxWidth: intParam(params, "maxWidth", 1280, 7680),- maxHeight: intParam(params, "maxHeight", 800, 4320),- quality: intParam(params, "quality", DEFAULT_QUALITY, 100),- })- .pipe(- Effect.map((viewer) => ({ _tag: "attached" as const, viewer })),- Effect.catchTags({- ServerBrowserTabNotFoundError: () => Effect.succeed({ _tag: "gone" as const }),- ServerBrowserLaunchError: (error) => {- const setup = hostSetup(error.cause);- return setup === undefined- ? Effect.fail(error)- : Effect.succeed({ _tag: "hostSetup" as const, reason: encodeHostSetup(setup) });- },- }),- );- const incoming = NodeHttpServerRequest.toIncomingMessage(request);- // JPEGs are already compressed. Disabling deflate also keeps all- // pending writes in the socket buffer we bound below, not a zlib queue.- delete incoming.headers["sec-websocket-extensions"];- const transport = incoming.socket;- const socket = yield* request.upgrade;- const reader = yield* socket.reader;- const writer = yield* socket.writer;- // A refused upgrade reads as an auth failure to ticket clients, so a- // missing tab is a close code they stop on.- const gone = writer.write(new Socket.CloseEvent(TAB_GONE_CODE, "tab closed"));- if (attached._tag === "gone") {- yield* gone;- return HttpServerResponse.empty();- }- if (attached._tag === "hostSetup") {- yield* writer.write(- new Socket.CloseEvent(PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE, attached.reason),- );- return HttpServerResponse.empty();- }- const viewer = attached.viewer;- // `write` returns once the frame is queued, so Chromium's ack for each- // frame waits for the viewer's `ack` message instead. Only one frame- // is on the wire and only the newest waits behind it, so replies never- // queue behind stale images on a slow link.- let inFlight: Effect.Effect<void> | null = null;- let pending: Frame | null = null;- const disconnectSlowViewer = Effect.sync(() => transport.destroy()).pipe(- Effect.andThen(Effect.interrupt),+// Request middleware owns tracing, including long-lived WebSocket sessions.+const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBrowser["Service"]) {+ const request = yield* HttpServerRequest.HttpServerRequest;+ const url = HttpServerRequest.toURL(request);+ if (Option.isNone(url)) return HttpServerResponse.text("Bad Request", { status: 400 });+ if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/download`) {+ return yield* serveDownload(browser, url.value.searchParams);+ }+ if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/upload`) {+ return request.method === "POST"+ ? yield* receiveUpload(browser, url.value.searchParams)+ : HttpServerResponse.text("Method Not Allowed", { status: 405 });+ }+ if (+ url.value.pathname !== `${PREVIEW_STREAM_ROUTE_PREFIX}/ws` ||+ request.headers.upgrade?.toLowerCase() !== "websocket"+ ) {+ return HttpServerResponse.text("Not Found", { status: 404 });+ }+ const session = yield* authenticateMediaRequest(AuthOrchestrationReadScope);+ const params = url.value.searchParams;+ const canOperate =+ session.scopes.includes(AuthPreviewOperateScope) && params.get("interactive") !== "false";+ const threadId = params.get("threadId") ?? "";+ const tabId = params.get("tabId") ?? "";+ if (threadId.length === 0 || tabId.length === 0) {+ return HttpServerResponse.text("Not Found", { status: 404 });+ }+ return yield* Effect.scoped(+ Effect.gen(function* () {+ const attached = yield* browser+ .attachViewer({+ threadId,+ tabId,+ canOperate,+ maxWidth: intParam(params, "maxWidth", 1280, 7680),+ maxHeight: intParam(params, "maxHeight", 800, 4320),+ quality: intParam(params, "quality", DEFAULT_QUALITY, 100),+ })+ .pipe(+ Effect.map((viewer) => ({ _tag: "attached" as const, viewer })),+ Effect.catchTags({+ ServerBrowserTabNotFoundError: () => Effect.succeed({ _tag: "gone" as const }),+ ServerBrowserLaunchError: (error) => {+ const setup = hostSetup(error.cause);+ return setup === undefined+ ? Effect.fail(error)+ : Effect.succeed({ _tag: "hostSetup" as const, reason: encodeHostSetup(setup) });+ },+ }),+ );+ const incoming = NodeHttpServerRequest.toIncomingMessage(request);+ // JPEGs are already compressed. Disabling deflate also keeps all+ // pending writes in the socket buffer we bound below, not a zlib queue.+ delete incoming.headers["sec-websocket-extensions"];+ const transport = incoming.socket;+ const socket = yield* request.upgrade;+ const reader = yield* socket.reader;+ const writer = yield* socket.writer;+ // A refused upgrade reads as an auth failure to ticket clients, so a+ // missing tab is a close code they stop on.+ const gone = writer.write(new Socket.CloseEvent(TAB_GONE_CODE, "tab closed"));+ if (attached._tag === "gone") {+ yield* gone;+ return HttpServerResponse.empty();+ }+ if (attached._tag === "hostSetup") {+ yield* writer.write(+ new Socket.CloseEvent(PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE, attached.reason),);- const write = (data: Uint8Array | string) =>- Effect.suspend(() => {- const bytes = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength;- if (transport.writableLength + bytes + 14 > MAX_SOCKET_BUFFER_BYTES) {- return disconnectSlowViewer;+ return HttpServerResponse.empty();+ }+ const viewer = attached.viewer;+ // `write` returns once the frame is queued, so Chromium's ack for each+ // frame waits for the viewer's `ack` message instead. Only one frame+ // is on the wire and only the newest waits behind it, so replies never+ // queue behind stale images on a slow link.+ let inFlight: Effect.Effect<void> | null = null;+ let pending: Frame | null = null;+ const disconnectSlowViewer = Effect.sync(() => transport.destroy()).pipe(+ Effect.andThen(Effect.interrupt),+ );+ const write = (data: Uint8Array | string) =>+ Effect.suspend(() => {+ const bytes = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength;+ if (transport.writableLength + bytes + 14 > MAX_SOCKET_BUFFER_BYTES) {+ return disconnectSlowViewer;+ }+ return writer.write(data);+ });+ const sendFrame = (frame: Frame) => {+ inFlight = frame.ack;+ return write(frame.data);+ };+ const sendOutput = Queue.take(viewer.output).pipe(+ Effect.flatMap((output) => {+ switch (output._tag) {+ case "frame": {+ if (inFlight === null) return sendFrame(output);+ const superseded = pending;+ pending = output;+ // Never sent, but Chromium still waits for its ack.+ return superseded ? Effect.forkScoped(superseded.ack) : Effect.void;}- return writer.write(data);- });- const sendFrame = (frame: Frame) => {- inFlight = frame.ack;- return write(frame.data);- };- const sendOutput = Queue.take(viewer.output).pipe(- Effect.flatMap((output) => {- switch (output._tag) {- case "frame": {- if (inFlight === null) return sendFrame(output);- const superseded = pending;- pending = output;- // Never sent, but Chromium still waits for its ack.- return superseded ? Effect.forkScoped(superseded.ack) : Effect.void;- }- case "viewport":- case "control":- case "clipboard":- case "download":- case "fileChooser":- case "fileChooserClosed":- case "popup":- case "pointer":- case "probe": {- const { _tag: type, ...data } = output;- return write(JSON.stringify({ type, ...data }));- }- case "gone":- return gone.pipe(Effect.andThen(Effect.interrupt));- case "reconnect":- return writer- .write(new Socket.CloseEvent(1012, "reconnect"))- .pipe(Effect.andThen(Effect.interrupt));+ case "viewport":+ case "control":+ case "clipboard":+ case "download":+ case "fileChooser":+ case "fileChooserClosed":+ case "popup":+ case "pointer":+ case "probe": {+ const { _tag: type, ...data } = output;+ return write(JSON.stringify({ type, ...data }));}- }),- );- const receive = (chunk: Uint8Array | string) => {- const message = parseMessage(chunk);- // Ownership serializes actions in the service. Keep reading so dialog- // replies and takeover can unblock an action already waiting on the page.- if (!isAck(message))- return canOperate- ? viewer.input(message).pipe(Effect.forkScoped, Effect.asVoid)- : Effect.void;- const ack = inFlight;- const next = pending;- inFlight = null;- pending = null;- // Forked: Chromium acks are paced and must not hold up input.- return Effect.andThen(- ack ? Effect.forkScoped(ack) : Effect.void,- next ? sendFrame(next) : Effect.void,- );- };- const receiveInput = reader.pull.pipe(- Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })),+ case "gone":+ return gone.pipe(Effect.andThen(Effect.interrupt));+ case "reconnect":+ return writer+ .write(new Socket.CloseEvent(1012, "reconnect"))+ .pipe(Effect.andThen(Effect.interrupt));+ }+ }),+ );+ const receive = (chunk: Uint8Array | string) => {+ const message = parseMessage(chunk);+ // Ownership serializes actions in the service. Keep reading so dialog+ // replies and takeover can unblock an action already waiting on the page.+ if (!isAck(message))+ return canOperate+ ? viewer.input(message).pipe(Effect.forkScoped, Effect.asVoid)+ : Effect.void;+ const ack = inFlight;+ const next = pending;+ inFlight = null;+ pending = null;+ // Forked: Chromium acks are paced and must not hold up input.+ return Effect.andThen(+ ack ? Effect.forkScoped(ack) : Effect.void,+ next ? sendFrame(next) : Effect.void,);- return yield* Effect.raceFirst(Effect.forever(sendOutput), Effect.forever(receiveInput));- }),- ).pipe(- Effect.catchTags({- ServerBrowserLaunchError: (error) =>- Effect.logWarning("server preview browser failed to start", { cause: error.cause }).pipe(- Effect.as(HttpServerResponse.text("Service Unavailable", { status: 503 })),- ),- }),- Effect.catch(() => Effect.succeed(HttpServerResponse.empty())),- );- });+ };+ const receiveInput = reader.pull.pipe(+ Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })),+ );+ return yield* Effect.raceFirst(Effect.forever(sendOutput), Effect.forever(receiveInput));+ }),+ ).pipe(+ Effect.catchTags({+ ServerBrowserLaunchError: (error) =>+ Effect.logWarning("server preview browser failed to start", { cause: error.cause }).pipe(+ Effect.as(HttpServerResponse.text("Service Unavailable", { status: 503 })),+ ),+ }),+ Effect.catch(() => Effect.succeed(HttpServerResponse.empty())),+ );+});const hostSetup = (cause: unknown): PreviewStreamHostSetup | undefined =>isSandboxError(cause)@@ -220,28 +220,32 @@ const isSandboxError = Schema.is(PreviewBrowserHost.PreviewBrowserSandboxError);const isLibrariesError = Schema.is(PreviewBrowserHost.PreviewBrowserLibrariesError);const encodeHostSetup = Schema.encodeSync(Schema.fromJsonString(PreviewStreamHostSetup));-const serveDownload = (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) =>- Effect.gen(function* () {- yield* authenticateMediaRequest(AuthOrchestrationReadScope);- const download = yield* browser.openDownload({- threadId: params.get("threadId") ?? "",- tabId: params.get("tabId") ?? "",- downloadId: params.get("id") ?? "",- });- if (Option.isNone(download)) return HttpServerResponse.text("Not Found", { status: 404 });- return yield* HttpServerResponse.file(download.value.path, {- headers: assetResponseHeaders(download.value.path, {- download: true,- fileName: download.value.fileName,- }),- });+// The request span already covers this download route.+const serveDownload = Effect.fnUntraced(function* (+ browser: ServerBrowser.ServerBrowser["Service"],+ params: URLSearchParams,+) {+ yield* authenticateMediaRequest(AuthOrchestrationReadScope);+ const download = yield* browser.openDownload({+ threadId: params.get("threadId") ?? "",+ tabId: params.get("tabId") ?? "",+ downloadId: params.get("id") ?? "",+ });+ if (Option.isNone(download)) return HttpServerResponse.text("Not Found", { status: 404 });+ return yield* HttpServerResponse.file(download.value.path, {+ headers: assetResponseHeaders(download.value.path, {+ download: true,+ fileName: download.value.fileName,+ }),});+});const UPLOAD_MAX_FILE_BYTES = 100 * 1024 * 1024;const UPLOAD_MAX_FILES = 20;-const receiveUpload = (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) =>- Effect.gen(function* () {+// The request span already covers this upload route.+const receiveUpload = Effect.fnUntraced(+ function* (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) {yield* authenticateMediaRequest(AuthPreviewOperateScope);const request = yield* HttpServerRequest.HttpServerRequest;const fs = yield* FileSystem.FileSystem;@@ -276,7 +280,9 @@ const receiveUpload = (browser: ServerBrowser.ServerBrowser["Service"], params:return answered? HttpServerResponse.empty({ status: 204 }): HttpServerResponse.text("The page's file picker is no longer open.", { status: 409 });- }).pipe(Effect.scoped);+ },+ (effect, _browser, _params) => effect.pipe(Effect.scoped),+);export const routeLayer = HttpRouter.use((router) =>Effect.gen(function* () {diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.tsindex c8e01230129..75b86b84f6b 100644--- a/apps/server/src/serverRuntimeStartup.ts+++ b/apps/server/src/serverRuntimeStartup.ts@@ -109,37 +109,39 @@ export const makeCommandGate = Effect.gen(function* () {);yield* Effect.forkScoped(commandWorker);+ const enqueueCommand = Effect.fn("serverRuntimeStartup.enqueueCommand")(function* <A, E>(+ effect: Effect.Effect<A, E>,+ ): Effect.fn.Return<A, E | ServerRuntimeStartupError> {+ const readinessState = yield* Ref.get(commandReadinessState);+ if (readinessState === "ready") {+ return yield* effect;+ }+ if (readinessState !== "pending") {+ return yield* readinessState;+ }++ const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();+ yield* Queue.offer(commandQueue, {+ run: Deferred.await(commandReady).pipe(+ Effect.flatMap(() => effect),+ Effect.exit,+ Effect.flatMap((exit) => settleQueuedCommand(result, exit)),+ ),+ });+ return yield* Deferred.await(result);+ });+return {awaitCommandReady: Deferred.await(commandReady),signalCommandReady: Effect.gen(function* () {yield* Ref.set(commandReadinessState, "ready");yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);}),- failCommandReady: (error) =>- Effect.gen(function* () {- yield* Ref.set(commandReadinessState, error);- yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);- }),- enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>- Effect.gen(function* () {- const readinessState = yield* Ref.get(commandReadinessState);- if (readinessState === "ready") {- return yield* effect;- }- if (readinessState !== "pending") {- return yield* readinessState;- }-- const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();- yield* Queue.offer(commandQueue, {- run: Deferred.await(commandReady).pipe(- Effect.flatMap(() => effect),- Effect.exit,- Effect.flatMap((exit) => settleQueuedCommand(result, exit)),- ),- });- return yield* Deferred.await(result);- }),+ failCommandReady: Effect.fn("serverRuntimeStartup.failCommandReady")(function* (error) {+ yield* Ref.set(commandReadinessState, error);+ yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);+ }),+ enqueueCommand,} satisfies CommandGate;});@@ -358,21 +360,22 @@ export const logBrowserAutoOpenUnavailable = Effect.logInfo("browser auto-open uhint: "Open the pairing URL above in your browser.",});-export const maybeOpenBrowser = (target: string) =>- Effect.gen(function* () {- const serverConfig = yield* ServerConfig.ServerConfig;- if (serverConfig.noBrowser) {- return;- }- const externalLauncher = yield* ExternalLauncher.ExternalLauncher;+export const maybeOpenBrowser = Effect.fn("serverRuntimeStartup.maybeOpenBrowser")(function* (+ target: string,+) {+ const serverConfig = yield* ServerConfig.ServerConfig;+ if (serverConfig.noBrowser) {+ return;+ }+ const externalLauncher = yield* ExternalLauncher.ExternalLauncher;- yield* externalLauncher.launchBrowser(target).pipe(- // The target carries the pairing token, and a failed launch records its- // command line on the span, so this call stays out of traces.- Effect.withTracerEnabled(false),- Effect.catch(() => logBrowserAutoOpenUnavailable),- );- });+ yield* externalLauncher.launchBrowser(target).pipe(+ // The target carries the pairing token, and a failed launch records its+ // command line on the span, so this call stays out of traces.+ Effect.withTracerEnabled(false),+ Effect.catch(() => logBrowserAutoOpenUnavailable),+ );+});const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>effect.pipe(@@ -413,7 +416,9 @@ export const startEffectWorkerWithRelay = Effect.fn();});-export function runOrderedV2StartupPhases<+export const runOrderedV2StartupPhases = Effect.fn(+ "serverRuntimeStartup.runOrderedV2StartupPhases",+)(function* <Import,Recovery,Bootstrap,@@ -434,292 +439,286 @@ export function runOrderedV2StartupPhases<readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;}) {- return Effect.gen(function* () {- yield* input.importLegacyShells;- const recovery = yield* input.recover;- yield* input.recoverDelegatedTasks;- yield* input.startEffectWorker;- const bootstrap = yield* input.autoBootstrap;- return { recovery, bootstrap } as const;- });-}+ yield* input.importLegacyShells;+ const recovery = yield* input.recover;+ yield* input.recoverDelegatedTasks;+ yield* input.startEffectWorker;+ const bootstrap = yield* input.autoBootstrap;+ return { recovery, bootstrap } as const;+});-const make = (options?: StartupOptions) =>- Effect.gen(function* () {- const serverConfig = yield* ServerConfig.ServerConfig;- const keybindings = yield* Keybindings.Keybindings;- const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;- const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;- const orchestrator = yield* Orchestrator.OrchestratorV2;- const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;- const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;- const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;- const serverSettings = yield* ServerSettings.ServerSettingsService;- const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;- const crypto = yield* Crypto.Crypto;- const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;-- const commandGate = yield* makeCommandGate;- const httpListening = yield* Deferred.make<void>();- const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);-- yield* Effect.addFinalizer(() =>- Effect.gen(function* () {- yield* commandGate.failCommandReady(- new ServerRuntimeStartupError({- mode: serverConfig.mode,- host: serverConfig.host ?? null,- port: serverConfig.port,- cause: "Server runtime is shutting down.",- }),- );- const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);- if (workerFiber !== null) {- yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);- }- yield* providerRuntimeRecovery.prepareForShutdown.pipe(- Effect.ensuring(providerSessions.shutdown),- );- const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");- yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);- }).pipe(- Effect.catchCause((cause) =>- Effect.logWarning("V2 orchestration shutdown reconciliation failed", {- cause: Cause.pretty(cause),+const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: StartupOptions) {+ const serverConfig = yield* ServerConfig.ServerConfig;+ const keybindings = yield* Keybindings.Keybindings;+ const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;+ const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;+ const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;+ const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;+ const serverSettings = yield* ServerSettings.ServerSettingsService;+ const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;+ const crypto = yield* Crypto.Crypto;+ const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;++ const commandGate = yield* makeCommandGate;+ const httpListening = yield* Deferred.make<void>();+ const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);++ yield* Effect.addFinalizer(() =>+ Effect.gen(function* () {+ yield* commandGate.failCommandReady(+ new ServerRuntimeStartupError({+ mode: serverConfig.mode,+ host: serverConfig.host ?? null,+ port: serverConfig.port,+ cause: "Server runtime is shutting down.",+ }),+ );+ const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);+ if (workerFiber !== null) {+ yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);+ }+ yield* providerRuntimeRecovery.prepareForShutdown.pipe(+ Effect.ensuring(providerSessions.shutdown),+ );+ const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");+ yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);+ }).pipe(+ Effect.catchCause((cause) =>+ Effect.logWarning("V2 orchestration shutdown reconciliation failed", {+ cause: Cause.pretty(cause),+ }),+ ),+ ),+ );++ const startup = Effect.gen(function* () {+ yield* Effect.logDebug("startup phase: starting keybindings runtime");+ yield* runStartupPhase(+ "keybindings.start",+ keybindings.start.pipe(+ Effect.catch((error) =>+ Effect.logWarning("failed to start keybindings runtime", {+ path: error.configPath,+ detail: error.detail,+ cause: error.cause,}),),),);- const startup = Effect.gen(function* () {- yield* Effect.logDebug("startup phase: starting keybindings runtime");- yield* runStartupPhase(- "keybindings.start",- keybindings.start.pipe(- Effect.catch((error) =>- Effect.logWarning("failed to start keybindings runtime", {- path: error.configPath,- detail: error.detail,- cause: error.cause,- }),- ),+ yield* Effect.logDebug("startup phase: starting server settings runtime");+ yield* runStartupPhase(+ "settings.start",+ serverSettings.start.pipe(+ Effect.catch((error) =>+ Effect.logWarning("failed to start server settings runtime", {+ path: error.settingsPath,+ operation: error.operation,+ providerInstanceId: error.providerInstanceId,+ environmentVariable: error.environmentVariable,+ cause: error.cause,+ }),),- );+ ),+ );- yield* Effect.logDebug("startup phase: starting server settings runtime");- yield* runStartupPhase(- "settings.start",- serverSettings.start.pipe(- Effect.catch((error) =>- Effect.logWarning("failed to start server settings runtime", {- path: error.settingsPath,- operation: error.operation,- providerInstanceId: error.providerInstanceId,- environmentVariable: error.environmentVariable,- cause: error.cause,- }),+ const welcomeBase = yield* resolveWelcomeBase;+ const environment = yield* serverEnvironment.getDescriptor;+ const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;+ if (legacyMigrationThreadCount > 0) {+ yield* lifecycleEvents.publish({+ version: 1,+ type: "legacyThreadMigration",+ payload: {+ status: "running",+ totalThreadCount: legacyMigrationThreadCount,+ },+ });+ }+ const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({+ importLegacyShells: runStartupPhase(+ "orchestration-v2.legacy-v1.import-shells",+ legacyV1ThreadImporter.reconcileShells.pipe(+ Effect.tap((summary) =>+ summary.importedThreadCount === 0+ ? Effect.void+ : Effect.logInfo("Imported legacy v1 thread shells", summary),),),- );+ ),+ recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),+ recoverDelegatedTasks: runStartupPhase(+ "orchestration-v2.delegated-tasks.recover",+ orchestrator.recoverDelegatedTasks,+ ),+ startEffectWorker: runStartupPhase(+ "orchestration-v2.effect-worker.start",+ startEffectWorkerWithRelay({+ runWorker: EffectWorker.runDaemon,+ startRelay: agentAwarenessRelay.start(),+ workerFiberRef: effectWorkerFiber,+ }),+ ),+ autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd+ ? runStartupPhase(+ "welcome.autobootstrap",+ resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),+ )+ : Effect.succeed({})+ ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),+ });+ yield* Effect.logInfo("V2 orchestration recovery completed", recovery);+ // Runs after activation: the status check fetches every enabled project's+ // remote, and awaiting it here held command readiness for that long.+ yield* runStartupPhase(+ "projects.auto-pull",+ Effect.gen(function* () {+ const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells();+ const settings = yield* serverSettings.getSettings;+ yield* autoPullProjects(projects, settings);+ }),+ ).pipe(+ Effect.catch((cause) =>+ Effect.logWarning("Failed to load projects for automatic pull", { cause }),+ ),+ forkParked,+ );- const welcomeBase = yield* resolveWelcomeBase;- const environment = yield* serverEnvironment.getDescriptor;- const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;- if (legacyMigrationThreadCount > 0) {- yield* lifecycleEvents.publish({- version: 1,- type: "legacyThreadMigration",- payload: {- status: "running",- totalThreadCount: legacyMigrationThreadCount,- },- });- }- const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({- importLegacyShells: runStartupPhase(- "orchestration-v2.legacy-v1.import-shells",- legacyV1ThreadImporter.reconcileShells.pipe(- Effect.tap((summary) =>- summary.importedThreadCount === 0- ? Effect.void- : Effect.logInfo("Imported legacy v1 thread shells", summary),+ const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(+ Effect.tap((summary) =>+ summary.importedThreadCount === 0+ ? Effect.void+ : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),+ ),+ );+ yield* (+ legacyMigrationThreadCount > 0+ ? importPendingTranscripts.pipe(+ Effect.tap(() =>+ lifecycleEvents.publish({+ version: 1,+ type: "legacyThreadMigration",+ payload: {+ status: "complete",+ totalThreadCount: legacyMigrationThreadCount,+ },+ }),),- ),- ),- recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),- recoverDelegatedTasks: runStartupPhase(- "orchestration-v2.delegated-tasks.recover",- orchestrator.recoverDelegatedTasks,- ),- startEffectWorker: runStartupPhase(- "orchestration-v2.effect-worker.start",- startEffectWorkerWithRelay({- runWorker: EffectWorker.runDaemon,- startRelay: agentAwarenessRelay.start(),- workerFiberRef: effectWorkerFiber,- }),- ),- autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd- ? runStartupPhase(- "welcome.autobootstrap",- resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),- )- : Effect.succeed({})- ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),- });- yield* Effect.logInfo("V2 orchestration recovery completed", recovery);- // Runs after activation: the status check fetches every enabled project's- // remote, and awaiting it here held command readiness for that long.- yield* runStartupPhase(- "projects.auto-pull",- Effect.gen(function* () {- const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells();- const settings = yield* serverSettings.getSettings;- yield* autoPullProjects(projects, settings);- }),- ).pipe(- Effect.catch((cause) =>- Effect.logWarning("Failed to load projects for automatic pull", { cause }),- ),- forkParked,- );+ )+ : importPendingTranscripts+ ).pipe(forkParked);- const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(- Effect.tap((summary) =>- summary.importedThreadCount === 0- ? Effect.void- : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),- ),- );- yield* (- legacyMigrationThreadCount > 0- ? importPendingTranscripts.pipe(- Effect.tap(() =>- lifecycleEvents.publish({- version: 1,- type: "legacyThreadMigration",- payload: {- status: "complete",- totalThreadCount: legacyMigrationThreadCount,- },- }),- ),- )- : importPendingTranscripts- ).pipe(forkParked);-- yield* forkParked(- Effect.gen(function* () {- yield* Effect.logDebug("startup phase: recording startup heartbeat");- yield* recordStartupHeartbeat.pipe(- Effect.withSpan("server.startup.heartbeat.record", {- attributes: { "startup.phase": "heartbeat.record" },- }),- Effect.ignoreCause({ log: true }),+ yield* forkParked(+ Effect.gen(function* () {+ yield* Effect.logDebug("startup phase: recording startup heartbeat");+ yield* recordStartupHeartbeat.pipe(+ Effect.withSpan("server.startup.heartbeat.record", {+ attributes: { "startup.phase": "heartbeat.record" },+ }),+ Effect.ignoreCause({ log: true }),+ );+ if (serverConfig.startupPresentation === "headless") {+ yield* Effect.logDebug("startup phase: headless access info");+ const accessInfo = yield* issueHeadlessServeAccessInfo();+ yield* runStartupPhase(+ "headless.output",+ Console.log(formatHeadlessServeOutput(accessInfo)),);- if (serverConfig.startupPresentation === "headless") {- yield* Effect.logDebug("startup phase: headless access info");- const accessInfo = yield* issueHeadlessServeAccessInfo();- yield* runStartupPhase(- "headless.output",- Console.log(formatHeadlessServeOutput(accessInfo)),- );- } else {- yield* Effect.logDebug("startup phase: browser open check");- const startupBrowserTarget = yield* resolveStartupBrowserTarget;- if (serverConfig.mode !== "desktop") {- yield* announceStartupPairingUrl(startupBrowserTarget);- }- yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));+ } else {+ yield* Effect.logDebug("startup phase: browser open check");+ const startupBrowserTarget = yield* resolveStartupBrowserTarget;+ if (serverConfig.mode !== "desktop") {+ yield* announceStartupPairingUrl(startupBrowserTarget);}- }),- );-- yield* Effect.logDebug("startup phase: waiting for http listener");- yield* runStartupPhase("http.wait", Deferred.await(httpListening));- yield* runStartupPhase(- "auxiliary-roots.parked",- options?.awaitAuxiliaryParked ?? Effect.void,- );+ yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));+ }+ }),+ );- const updateOutcome = yield* launcher.prepareTrial;+ yield* Effect.logDebug("startup phase: waiting for http listener");+ yield* runStartupPhase("http.wait", Deferred.await(httpListening));+ yield* runStartupPhase("auxiliary-roots.parked", options?.awaitAuxiliaryParked ?? Effect.void);- yield* Effect.logDebug("startup phase: publishing welcome event", {- environmentId: environment.environmentId,- cwd: welcomeBase.cwd,- projectName: welcomeBase.projectName,- bootstrapProjectId: bootstrapTargets.bootstrapProjectId,- bootstrapThreadId: bootstrapTargets.bootstrapThreadId,- });- yield* runStartupPhase(- "welcome.publish",- lifecycleEvents.publish({- version: 1,- type: "welcome",- payload: {- environment,- ...welcomeBase,- ...bootstrapTargets,- },- }),- );+ const updateOutcome = yield* launcher.prepareTrial;- yield* options?.activate ?? Effect.void;- yield* Effect.logDebug("Accepting commands");- yield* commandGate.signalCommandReady;- yield* Effect.logDebug("startup phase: publishing ready event");- yield* runStartupPhase(- "ready.publish",- lifecycleEvents.publish({- version: 1,- type: "ready",- payload: {- at: DateTime.formatIso(yield* DateTime.now),- environment,- ...(updateOutcome === undefined ? {} : { updateOutcome }),- },- }),- );- yield* Effect.logDebug("startup phase: complete");- yield* flushCompileCache;- }).pipe(- Effect.withSpan("server.startup", {- kind: "server",- root: true,- attributes: {- "server.mode": serverConfig.mode,- "server.port": serverConfig.port,- "server.host": serverConfig.host ?? "default",+ yield* Effect.logDebug("startup phase: publishing welcome event", {+ environmentId: environment.environmentId,+ cwd: welcomeBase.cwd,+ projectName: welcomeBase.projectName,+ bootstrapProjectId: bootstrapTargets.bootstrapProjectId,+ bootstrapThreadId: bootstrapTargets.bootstrapThreadId,+ });+ yield* runStartupPhase(+ "welcome.publish",+ lifecycleEvents.publish({+ version: 1,+ type: "welcome",+ payload: {+ environment,+ ...welcomeBase,+ ...bootstrapTargets,},}),);- yield* Effect.forkScoped(- Effect.exit(startup).pipe(- Effect.flatMap((startupExit) => {- if (Exit.isSuccess(startupExit)) return Effect.void;- const error = new ServerRuntimeStartupError({- mode: serverConfig.mode,- host: serverConfig.host ?? null,- port: serverConfig.port,- cause: startupExit.cause,- });- return Effect.logError("server runtime startup failed", {- cause: Cause.pretty(startupExit.cause),- }).pipe(- Effect.andThen(commandGate.failCommandReady(error)),- Effect.andThen(options?.abort?.(error) ?? Effect.void),- );- }),- ),+ yield* options?.activate ?? Effect.void;+ yield* Effect.logDebug("Accepting commands");+ yield* commandGate.signalCommandReady;+ yield* Effect.logDebug("startup phase: publishing ready event");+ yield* runStartupPhase(+ "ready.publish",+ lifecycleEvents.publish({+ version: 1,+ type: "ready",+ payload: {+ at: DateTime.formatIso(yield* DateTime.now),+ environment,+ ...(updateOutcome === undefined ? {} : { updateOutcome }),+ },+ }),);+ yield* Effect.logDebug("startup phase: complete");+ yield* flushCompileCache;+ }).pipe(+ Effect.withSpan("server.startup", {+ kind: "server",+ root: true,+ attributes: {+ "server.mode": serverConfig.mode,+ "server.port": serverConfig.port,+ "server.host": serverConfig.host ?? "default",+ },+ }),+ );- return {- awaitCommandReady: commandGate.awaitCommandReady,- markHttpListening: Deferred.succeed(httpListening, undefined),- enqueueCommand: commandGate.enqueueCommand,- } satisfies ServerRuntimeStartup["Service"];- });+ yield* Effect.forkScoped(+ Effect.exit(startup).pipe(+ Effect.flatMap((startupExit) => {+ if (Exit.isSuccess(startupExit)) return Effect.void;+ const error = new ServerRuntimeStartupError({+ mode: serverConfig.mode,+ host: serverConfig.host ?? null,+ port: serverConfig.port,+ cause: startupExit.cause,+ });+ return Effect.logError("server runtime startup failed", {+ cause: Cause.pretty(startupExit.cause),+ }).pipe(+ Effect.andThen(commandGate.failCommandReady(error)),+ Effect.andThen(options?.abort?.(error) ?? Effect.void),+ );+ }),+ ),+ );++ return {+ awaitCommandReady: commandGate.awaitCommandReady,+ markHttpListening: Deferred.succeed(httpListening, undefined),+ enqueueCommand: commandGate.enqueueCommand,+ } satisfies ServerRuntimeStartup["Service"];+});export const layerWithOptions = (options?: StartupOptions) =>Layer.effect(ServerRuntimeStartup, make(options));diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 976f0229de3..e19a47e1fe3 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -279,24 +279,23 @@ type EditorDiscovery = Pick<"resolveAvailableEditors" | "resolveFileManagerRevealKind">;-const resolveEditorConfig = <E, R>(+const resolveEditorConfig = Effect.fn("ws.resolveEditorConfig")(function* <E, R>(availableEditors: ReadonlyArray<EditorId>,revealKind: Effect.Effect<FileManagerRevealKind | undefined, E, R>,-) =>- Effect.gen(function* () {- const fileManagerRevealKind = availableEditors.includes("file-manager")- ? yield* revealKind- : undefined;- return {- availableEditors,- ...(fileManagerRevealKind === undefined- ? {}- : {- shellRevealInFileManager: true,- shellRevealInFileManagerKind: fileManagerRevealKind,- }),- };- });+) {+ const fileManagerRevealKind = availableEditors.includes("file-manager")+ ? yield* revealKind+ : undefined;+ return {+ availableEditors,+ ...(fileManagerRevealKind === undefined+ ? {}+ : {+ shellRevealInFileManager: true,+ shellRevealInFileManagerKind: fileManagerRevealKind,+ }),+ };+});export const withLateEditorConfig = <E, R>(config: ClientServerConfig,@@ -1642,64 +1641,63 @@ const layerWsRpc = (),);- const loadServerConfig = (options: { readonly usageLimitsCommand: boolean }) =>- Effect.gen(function* () {- const keybindingsConfig = yield* keybindings.loadConfigState;- const currentProviders = yield* providerRegistry.getProviders;- const providers = options.usageLimitsCommand- ? withUsageLimitsCommands(currentProviders, yield* usageLimitSources.current)- : currentProviders;- const settings = ServerSettings.redactServerSettingsForClient(- yield* serverSettings.getSettings,- );- const environment = yield* serverEnvironment.getDescriptor;- const auth = yield* serverAuth.getDescriptor();- const scratchWorkspaceRoot = yield* managedFolders.scratchRoot;- const editorConfig = yield* resolveEditorConfig(- yield* resolveAvailableEditorsForConfig(externalLauncher.resolveAvailableEditors()),- resolveFileManagerRevealKindForConfig(externalLauncher.resolveFileManagerRevealKind()),- );+ const loadServerConfig = Effect.fn("ws.loadServerConfig")(function* (options: {+ readonly usageLimitsCommand: boolean;+ }) {+ const keybindingsConfig = yield* keybindings.loadConfigState;+ const currentProviders = yield* providerRegistry.getProviders;+ const providers = options.usageLimitsCommand+ ? withUsageLimitsCommands(currentProviders, yield* usageLimitSources.current)+ : currentProviders;+ const settings = ServerSettings.redactServerSettingsForClient(+ yield* serverSettings.getSettings,+ );+ const environment = yield* serverEnvironment.getDescriptor;+ const auth = yield* serverAuth.getDescriptor();+ const scratchWorkspaceRoot = yield* managedFolders.scratchRoot;+ const editorConfig = yield* resolveEditorConfig(+ yield* resolveAvailableEditorsForConfig(externalLauncher.resolveAvailableEditors()),+ resolveFileManagerRevealKindForConfig(externalLauncher.resolveFileManagerRevealKind()),+ );- return {- environment,- auth,- cwd: config.cwd,- keybindingsConfigPath: config.keybindingsConfigPath,- keybindings: keybindingsConfig.keybindings,- issues: keybindingsConfig.issues,- providers,- ...editorConfig,- remoteOpenTargets: yield* resolveAvailableEditorsForConfig(- remoteOpenTargets.resolveTargets(),- ),- directEndpoints: yield* resolveAvailableEditorsForConfig(directEndpoints.resolve()),- observability: {- logsDirectoryPath: config.logsDir,- localTracingEnabled: true,- ...(config.otlpTracesUrl !== undefined- ? { otlpTracesUrl: config.otlpTracesUrl }- : {}),- otlpTracesEnabled: config.otlpTracesUrl !== undefined,- ...(config.otlpMetricsUrl !== undefined- ? { otlpMetricsUrl: config.otlpMetricsUrl }- : {}),- otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,- ...(config.otlpLogsUrl !== undefined ? { otlpLogsUrl: config.otlpLogsUrl } : {}),- otlpLogsEnabled: config.otlpLogsUrl !== undefined,- },- settings,- shellResumeCompletionMarker: true,- threadResumeCompletionMarker: true,- threadSnapshotPagination: true,- threadFind: true,- threadFindProgressive: true,- ...Option.match(scratchWorkspaceRoot, {- onNone: () => ({}),- onSome: (root) => ({ scratchWorkspaceRoot: root }),- }),- newProjectsRoot: managedFolders.namedProjectsRoot,- };- });+ return {+ environment,+ auth,+ cwd: config.cwd,+ keybindingsConfigPath: config.keybindingsConfigPath,+ keybindings: keybindingsConfig.keybindings,+ issues: keybindingsConfig.issues,+ providers,+ ...editorConfig,+ remoteOpenTargets: yield* resolveAvailableEditorsForConfig(+ remoteOpenTargets.resolveTargets(),+ ),+ directEndpoints: yield* resolveAvailableEditorsForConfig(directEndpoints.resolve()),+ observability: {+ logsDirectoryPath: config.logsDir,+ localTracingEnabled: true,+ ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),+ otlpTracesEnabled: config.otlpTracesUrl !== undefined,+ ...(config.otlpMetricsUrl !== undefined+ ? { otlpMetricsUrl: config.otlpMetricsUrl }+ : {}),+ otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,+ ...(config.otlpLogsUrl !== undefined ? { otlpLogsUrl: config.otlpLogsUrl } : {}),+ otlpLogsEnabled: config.otlpLogsUrl !== undefined,+ },+ settings,+ shellResumeCompletionMarker: true,+ threadResumeCompletionMarker: true,+ threadSnapshotPagination: true,+ threadFind: true,+ threadFindProgressive: true,+ ...Option.match(scratchWorkspaceRoot, {+ onNone: () => ({}),+ onSome: (root) => ({ scratchWorkspaceRoot: root }),+ }),+ newProjectsRoot: managedFolders.namedProjectsRoot,+ };+ });const refreshGitStatus = (cwd: string) =>vcsStatusBroadcaster@@ -2150,8 +2148,9 @@ const layerWsRpc = (}),),),- [WS_METHODS.serverRefreshProviders]: (input) =>- Effect.gen(function* () {+ [WS_METHODS.serverRefreshProviders]:+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (input) {if (input.refreshModels) {yield* modelManifest.forceRefresh;const instances = yield* providerInstances.listInstances;@@ -2225,59 +2224,65 @@ const layerWsRpc = ([WS_METHODS.mcpAppsToolInfo]: (input) => mcpAppRequests.toolInfo(input),[WS_METHODS.mcpAppsUpdateModelContext]: (input) => mcpAppRequests.updateModelContext(input),[WS_METHODS.mcpAppsReadResource]: (input) => mcpAppRequests.readResource(input),- [WS_METHODS.providerUploadFeedback]: (input) =>- Effect.gen(function* () {- const projection = yield* threadManagement.getThreadRecords(input.threadId, [- "providerThreads",- ]);- const providerThread =- projection.providerThreads.find(- (candidate) => candidate.id === projection.thread.activeProviderThreadId,- ) ?? projection.providerThreads.at(-1);- const providerSessionId = providerThread?.providerSessionId ?? null;- if (providerThread === undefined || providerSessionId === null) {- return yield* Effect.fail(- new ProviderUploadFeedbackError({- threadId: input.threadId,- cause: "No provider session has run in this thread yet.",- }),- );- }- const runtime = Option.getOrNull(yield* providerSessionsV2.get(providerSessionId));- if (runtime === null) {- return yield* Effect.fail(- new ProviderUploadFeedbackError({- threadId: input.threadId,- cause: "The provider session is no longer running. Send a message first.",- }),- );- }- if (runtime.uploadFeedback === undefined) {- return yield* Effect.fail(- new ProviderUploadFeedbackError({- threadId: input.threadId,- cause: `Provider '${runtime.driver}' does not support feedback uploads.`,- }),- );- }- return yield* runtime.uploadFeedback({- providerThread,- ...(input.reason === undefined ? {} : { reason: input.reason }),- });- }).pipe(- Effect.mapError((cause) =>- isProviderUploadFeedbackError(cause)- ? cause- : new ProviderUploadFeedbackError({+ [WS_METHODS.providerUploadFeedback]:+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(+ function* (input) {+ const projection = yield* threadManagement.getThreadRecords(input.threadId, [+ "providerThreads",+ ]);+ const providerThread =+ projection.providerThreads.find(+ (candidate) => candidate.id === projection.thread.activeProviderThreadId,+ ) ?? projection.providerThreads.at(-1);+ const providerSessionId = providerThread?.providerSessionId ?? null;+ if (providerThread === undefined || providerSessionId === null) {+ return yield* Effect.fail(+ new ProviderUploadFeedbackError({threadId: input.threadId,- cause,+ cause: "No provider session has run in this thread yet.",}),- ),+ );+ }+ const runtime = Option.getOrNull(yield* providerSessionsV2.get(providerSessionId));+ if (runtime === null) {+ return yield* Effect.fail(+ new ProviderUploadFeedbackError({+ threadId: input.threadId,+ cause: "The provider session is no longer running. Send a message first.",+ }),+ );+ }+ if (runtime.uploadFeedback === undefined) {+ return yield* Effect.fail(+ new ProviderUploadFeedbackError({+ threadId: input.threadId,+ cause: `Provider '${runtime.driver}' does not support feedback uploads.`,+ }),+ );+ }+ return yield* runtime.uploadFeedback({+ providerThread,+ ...(input.reason === undefined ? {} : { reason: input.reason }),+ });+ },+ (effect, input) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProviderUploadFeedbackError(cause)+ ? cause+ : new ProviderUploadFeedbackError({+ threadId: input.threadId,+ cause,+ }),+ ),+ ),),[WS_METHODS.serverUpdateProvider]: (input) =>providerMaintenanceRunner.updateProvider(input),- [WS_METHODS.providerConsumeResetCredit]: (input) =>- Effect.gen(function* () {+ [WS_METHODS.providerConsumeResetCredit]:+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (input) {if ("sourceId" in input) return yield* usageLimitSources.consumeResetCredit(input);const instance = yield* providerInstances.getInstance(input.instanceId);if (instance === undefined || !instance.enabled) {@@ -2332,13 +2337,15 @@ const layerWsRpc = (ServerSelfUpdate.updateProgressStream(serverSelfUpdate, input),[WS_METHODS.serverCommitDesktopUpdate]: (input) =>serverSelfUpdate.commitDesktopUpdate(input.requestId),- [WS_METHODS.serverUpsertKeybinding]: (rule) =>- Effect.gen(function* () {+ [WS_METHODS.serverUpsertKeybinding]:+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (rule) {const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);return { keybindings: keybindingsConfig, issues: [] };}),- [WS_METHODS.serverRemoveKeybinding]: (rule) =>- Effect.gen(function* () {+ [WS_METHODS.serverRemoveKeybinding]:+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (rule) {const keybindingsConfig = yield* keybindings.removeKeybindingRule(rule);return { keybindings: keybindingsConfig, issues: [] };}),@@ -2347,8 +2354,9 @@ const layerWsRpc = ([WS_METHODS.serverGetDatabaseStorage]: () => databaseStorage.status,[WS_METHODS.serverGetSettings]: (_input) =>serverSettings.getSettings.pipe(Effect.map(ServerSettings.redactServerSettingsForClient)),- [WS_METHODS.serverUpdateSettings]: ({ patch, providerInstanceMutation }) =>- Effect.gen(function* () {+ [WS_METHODS.serverUpdateSettings]:+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* ({ patch, providerInstanceMutation }) {const deviceHosts = patch.deviceHosts? yield* remoteSshDeviceHosts(patch.deviceHosts).pipe(Effect.provide(deviceHostContext),@@ -2659,8 +2667,9 @@ const layerWsRpc = ([WS_METHODS.agentSessionsScan]: () => agentSessionScanner.scan,[WS_METHODS.agentSessionsImport]: (input) =>agentSessionImporter.importRecentAgentThreads(input),- [WS_METHODS.assetsCreateUrl]: (input) =>- Effect.gen(function* () {+ [WS_METHODS.assetsCreateUrl]:+ /* Request instrumentation already owns the span; keep this helper in that context. */+ Effect.fnUntraced(function* (input) {const path = yield* Path.Path;if (input.resource._tag === "attachment" ||