@devries-cameron20 / t3code-1 / commits / 889bb95f7e
Fork 0

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

refactor(server): use Effect functions at transport and startup boundaries (#21999)

Julius Marminge committed Oct 19, 2026 at 18:31 UTC 889bb95f7ed196cc1417b926508fcd45ba229a87
26 files changed +3048 -3018
apps/server/src/auth/McpOAuth.ts
+114 -115
@@ -288,8 +288,8 @@ const make = Effect.gen(function* () {
288 ]),
289 );
290
291 - const register: McpOAuth["Service"]["register"] = (metadata) =>
292 - Effect.gen(function* () {
291 + const register: McpOAuth["Service"]["register"] = Effect.fn("McpOAuth.register")(
292 + function* (metadata) {
293 const rawName = metadata.client_name?.trim() ?? "";
294 const name = (rawName.length > 0 ? rawName : DEFAULT_CLIENT_NAME).slice(
295 0,
@@ -314,59 +314,58 @@ const make = Effect.gen(function* () {
314 // asks for refresh_token, and hosted agents may ask for a client secret; every client
315 // is registered as public and proves itself with PKCE instead.
316 return { clientId: signClientId(name, redirectUris), name, redirectUris };
317 - });
317 + },
318 + );
319
319 - const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = ({ urls, request }) =>
320 - Effect.gen(function* () {
321 - const client = parseClientId(request.client_id ?? "");
322 - if (client === undefined) {
323 - return yield* new McpOAuthPageError({
324 - description: "This sign-in link names an unknown app. Start the sign-in again from it.",
325 - });
326 - }
327 - const redirectUri = request.redirect_uri;
328 - if (
329 - redirectUri === undefined ||
330 - !client.redirectUris.some((registered) => redirectMatches(registered, redirectUri))
331 - ) {
332 - return yield* new McpOAuthPageError({
333 - description: "This sign-in link sends you to an address the app did not register.",
334 - });
335 - }
336 - const state = request.state;
337 - const fail = (error: McpOAuthRedirectError["error"], description: string) =>
338 - new McpOAuthRedirectError({
339 - error,
340 - description,
341 - redirectUri,
342 - ...(state === undefined ? {} : { state }),
343 - });
344 - if (request.response_type !== "code") {
345 - return yield* fail("unsupported_response_type", "Only response_type=code is supported.");
346 - }
347 - const codeChallenge = request.code_challenge;
348 - if (
349 - request.code_challenge_method !== "S256" ||
350 - codeChallenge === undefined ||
351 - !CODE_CHALLENGE_PATTERN.test(codeChallenge)
352 - ) {
353 - return yield* fail("invalid_request", "PKCE with code_challenge_method=S256 is required.");
354 - }
355 - if (!sameResource(urls, request.resource)) {
356 - return yield* fail(
357 - "invalid_target",
358 - `This server only issues tokens for ${urls.resource}.`,
359 - );
360 - }
361 - return {
362 - client,
320 + const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = Effect.fn(
321 + "McpOAuth.validateAuthorization",
322 + )(function* ({ urls, request }) {
323 + const client = parseClientId(request.client_id ?? "");
324 + if (client === undefined) {
325 + return yield* new McpOAuthPageError({
326 + description: "This sign-in link names an unknown app. Start the sign-in again from it.",
327 + });
328 + }
329 + const redirectUri = request.redirect_uri;
330 + if (
331 + redirectUri === undefined ||
332 + !client.redirectUris.some((registered) => redirectMatches(registered, redirectUri))
333 + ) {
334 + return yield* new McpOAuthPageError({
335 + description: "This sign-in link sends you to an address the app did not register.",
336 + });
337 + }
338 + const state = request.state;
339 + const fail = (error: McpOAuthRedirectError["error"], description: string) =>
340 + new McpOAuthRedirectError({
341 + error,
342 + description,
343 redirectUri,
364 - codeChallenge,
365 - state,
366 - resource: urls.resource,
367 - issuer: urls.issuer,
368 - } satisfies AuthorizationRequest;
369 - });
344 + ...(state === undefined ? {} : { state }),
345 + });
346 + if (request.response_type !== "code") {
347 + return yield* fail("unsupported_response_type", "Only response_type=code is supported.");
348 + }
349 + const codeChallenge = request.code_challenge;
350 + if (
351 + request.code_challenge_method !== "S256" ||
352 + codeChallenge === undefined ||
353 + !CODE_CHALLENGE_PATTERN.test(codeChallenge)
354 + ) {
355 + return yield* fail("invalid_request", "PKCE with code_challenge_method=S256 is required.");
356 + }
357 + if (!sameResource(urls, request.resource)) {
358 + return yield* fail("invalid_target", `This server only issues tokens for ${urls.resource}.`);
359 + }
360 + return {
361 + client,
362 + redirectUri,
363 + codeChallenge,
364 + state,
365 + resource: urls.resource,
366 + issuer: urls.issuer,
367 + } satisfies AuthorizationRequest;
368 + });
369
370 const approvingBrowserSession: McpOAuth["Service"]["approvingBrowserSession"] = (
371 request,
@@ -383,73 +382,72 @@ const make = Effect.gen(function* () {
382 Effect.orElseSucceed(() => undefined),
383 );
384
386 - const mintCode = (authorization: AuthorizationRequest, access: AuthMcpClientAccess) =>
387 - Effect.gen(function* () {
388 - const now = yield* Clock.currentTimeMillis;
389 - const code = Buffer.from(yield* crypto.randomBytes(32).pipe(Effect.orDie)).toString(
390 - "base64url",
391 - );
392 - yield* Ref.update(codes, (current) => {
393 - const next = new Map(
394 - Array.from(current).filter(([, pending]) => pending.expiresAtMs > now),
395 - );
396 - next.set(code, {
397 - clientId: authorization.client.clientId,
398 - clientName: authorization.client.name,
399 - redirectUri: authorization.redirectUri,
400 - codeChallenge: authorization.codeChallenge,
401 - resource: authorization.resource,
402 - access,
403 - expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS,
404 - });
405 - return next;
385 + const mintCode = Effect.fn("McpOAuth.mintCode")(function* (
386 + authorization: AuthorizationRequest,
387 + access: AuthMcpClientAccess,
388 + ) {
389 + const now = yield* Clock.currentTimeMillis;
390 + const code = Buffer.from(yield* crypto.randomBytes(32).pipe(Effect.orDie)).toString(
391 + "base64url",
392 + );
393 + yield* Ref.update(codes, (current) => {
394 + const next = new Map(Array.from(current).filter(([, pending]) => pending.expiresAtMs > now));
395 + next.set(code, {
396 + clientId: authorization.client.clientId,
397 + clientName: authorization.client.name,
398 + redirectUri: authorization.redirectUri,
399 + codeChallenge: authorization.codeChallenge,
400 + resource: authorization.resource,
401 + access,
402 + expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS,
403 });
407 - return code;
404 + return next;
405 });
406 + return code;
407 + });
408
410 - const approve: McpOAuth["Service"]["approve"] = (input) =>
411 - Effect.gen(function* () {
412 - const { decision } = input;
413 - if (decision._tag === "pairing-code") {
414 - yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
415 - Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
416 - Effect.logError("MCP approval code check failed.", { cause }).pipe(
417 - Effect.andThen(
418 - Effect.fail(
419 - new McpOAuthPageError({
420 - description: "The code could not be checked. Try again.",
421 - }),
422 - ),
409 + const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) {
410 + const { decision } = input;
411 + if (decision._tag === "pairing-code") {
412 + yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
413 + Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
414 + Effect.logError("MCP approval code check failed.", { cause }).pipe(
415 + Effect.andThen(
416 + Effect.fail(
417 + new McpOAuthPageError({
418 + description: "The code could not be checked. Try again.",
419 + }),
420 ),
421 ),
422 ),
426 - );
427 - } else {
428 - const session = yield* approvingBrowserSession(input.request, input.authorization);
429 - if (
430 - session === undefined ||
431 - !timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||
432 - !EnvironmentAuth.mcpClientScopes(decision.access).every((scope) =>
433 - session.scopes.includes(scope),
434 - )
435 - ) {
436 - return yield* new McpOAuthPageError({
437 - description: "Your session cannot approve this request. Enter a pairing code instead.",
438 - });
439 - }
423 + ),
424 + );
425 + } else {
426 + const session = yield* approvingBrowserSession(input.request, input.authorization);
427 + if (
428 + session === undefined ||
429 + !timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||
430 + !EnvironmentAuth.mcpClientScopes(decision.access).every((scope) =>
431 + session.scopes.includes(scope),
432 + )
433 + ) {
434 + return yield* new McpOAuthPageError({
435 + description: "Your session cannot approve this request. Enter a pairing code instead.",
436 + });
437 }
441 - const code = yield* mintCode(input.authorization, decision.access);
442 - yield* Effect.logInfo("Approved an MCP client sign-in.", {
443 - client: input.authorization.client.name,
444 - access: decision.access,
445 - method: decision._tag,
446 - });
447 - return redirectWith(input.authorization.redirectUri, {
448 - code,
449 - state: input.authorization.state,
450 - iss: input.authorization.issuer,
451 - });
438 + }
439 + const code = yield* mintCode(input.authorization, decision.access);
440 + yield* Effect.logInfo("Approved an MCP client sign-in.", {
441 + client: input.authorization.client.name,
442 + access: decision.access,
443 + method: decision._tag,
444 + });
445 + return redirectWith(input.authorization.redirectUri, {
446 + code,
447 + state: input.authorization.state,
448 + iss: input.authorization.issuer,
449 });
450 + });
451
452 const deny: McpOAuth["Service"]["deny"] = (authorization) =>
453 redirectWith(authorization.redirectUri, {
@@ -458,8 +456,8 @@ const make = Effect.gen(function* () {
456 iss: authorization.issuer,
457 });
458
461 - const exchangeCode: McpOAuth["Service"]["exchangeCode"] = ({ request, urls, token }) =>
462 - Effect.gen(function* () {
459 + const exchangeCode: McpOAuth["Service"]["exchangeCode"] = Effect.fn("McpOAuth.exchangeCode")(
460 + function* ({ request, urls, token }) {
461 const fail = (error: AuthMcpTokenError["error"], description: string) =>
462 new AuthMcpTokenError({ error, error_description: description });
463 if (token.grant_type !== "authorization_code") {
@@ -517,7 +515,8 @@ const make = Effect.gen(function* () {
515 expires_in: Math.max(0, Math.floor((issued.expiresAt.epochMilliseconds - now) / 1000)),
516 scope: encodeOAuthScope(EnvironmentAuth.mcpClientScopes(pending.access)),
517 };
520 - });
518 + },
519 + );
520
521 return McpOAuth.of({
522 register,
apps/server/src/auth/SessionStore.ts
+27 -26
@@ -539,33 +539,34 @@ export const make = Effect.gen(function* () {
539 sessionId,
540 }).pipe(Effect.asVoid);
541
542 - const loadActiveSession = (sessionId: AuthSessionId) =>
543 - Effect.gen(function* () {
544 - const row = yield* authSessions.getById({ sessionId });
545 - if (Option.isNone(row) || row.value.revokedAt !== null) {
546 - return Option.none<AuthClientSession>();
547 - }
542 + const loadActiveSession = Effect.fn("SessionStore.loadActiveSession")(function* (
543 + sessionId: AuthSessionId,
544 + ) {
545 + const row = yield* authSessions.getById({ sessionId });
546 + if (Option.isNone(row) || row.value.revokedAt !== null) {
547 + return Option.none<AuthClientSession>();
548 + }
549
549 - const connectedSessions = yield* Ref.get(connectedSessionsRef);
550 - const connected = connectedSessions.has(row.value.sessionId);
551 - const now = yield* DateTime.now;
552 - if (!connected && row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {
553 - return Option.none<AuthClientSession>();
554 - }
555 - return Option.some(
556 - toAuthClientSession({
557 - sessionId: row.value.sessionId,
558 - subject: row.value.subject,
559 - scopes: row.value.scopes,
560 - method: row.value.method,
561 - client: toClientMetadata(row.value.client),
562 - issuedAt: row.value.issuedAt,
563 - expiresAt: row.value.expiresAt,
564 - lastConnectedAt: row.value.lastConnectedAt,
565 - connected,
566 - }),
567 - );
568 - });
550 + const connectedSessions = yield* Ref.get(connectedSessionsRef);
551 + const connected = connectedSessions.has(row.value.sessionId);
552 + const now = yield* DateTime.now;
553 + if (!connected && row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {
554 + return Option.none<AuthClientSession>();
555 + }
556 + return Option.some(
557 + toAuthClientSession({
558 + sessionId: row.value.sessionId,
559 + subject: row.value.subject,
560 + scopes: row.value.scopes,
561 + method: row.value.method,
562 + client: toClientMetadata(row.value.client),
563 + issuedAt: row.value.issuedAt,
564 + expiresAt: row.value.expiresAt,
565 + lastConnectedAt: row.value.lastConnectedAt,
566 + connected,
567 + }),
568 + );
569 + });
570
571 const markConnected: SessionStore["Service"]["markConnected"] = (sessionId) =>
572 Ref.modify(connectedSessionsRef, (current) => {
apps/server/src/auth/dpop.ts
+63 -64
@@ -52,74 +52,73 @@ export const mapDpopReplayStoreError = (
52 cause: error,
53 });
54
55 -export const verifyRequestDpopProof = (input: {
55 +export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(function* (input: {
56 readonly request: HttpServerRequest.HttpServerRequest;
57 readonly expectedThumbprint?: string;
58 readonly expectedAccessToken?: string;
59 -}) =>
60 - Effect.gen(function* () {
61 - const proof = input.request.headers.dpop;
62 - const url = HttpServerRequest.toURL(input.request);
63 - if (Option.isNone(url)) {
64 - return yield* new ServerAuthInvalidCredentialError({
65 - diagnostic: "Invalid DPoP request URL.",
66 - });
67 - }
68 - const now = yield* DateTime.now;
69 - const result = verifyDpopProof({
70 - proof,
71 - method: input.request.method,
72 - url: url.value.href,
73 - nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
74 - ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
75 - ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
59 +}) {
60 + const proof = input.request.headers.dpop;
61 + const url = HttpServerRequest.toURL(input.request);
62 + if (Option.isNone(url)) {
63 + return yield* new ServerAuthInvalidCredentialError({
64 + diagnostic: "Invalid DPoP request URL.",
65 });
77 - if (!result.ok) {
78 - yield* Effect.annotateCurrentSpan({
79 - "environment.dpop.failure_code": result.code,
80 - });
81 - return yield* new ServerAuthInvalidCredentialError({
82 - diagnostic: result.reason,
83 - dpopFailureReason: mapDpopFailureReason(result.code),
84 - });
85 - }
86 - const secretStore = yield* ServerSecretStore.ServerSecretStore;
87 - const replayKey = yield* Crypto.Crypto.pipe(
88 - Effect.flatMap((crypto) =>
89 - crypto.digest("SHA-256", new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)),
66 + }
67 + const now = yield* DateTime.now;
68 + const result = verifyDpopProof({
69 + proof,
70 + method: input.request.method,
71 + url: url.value.href,
72 + nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
73 + ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
74 + ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
75 + });
76 + if (!result.ok) {
77 + yield* Effect.annotateCurrentSpan({
78 + "environment.dpop.failure_code": result.code,
79 + });
80 + return yield* new ServerAuthInvalidCredentialError({
81 + diagnostic: result.reason,
82 + dpopFailureReason: mapDpopFailureReason(result.code),
83 + });
84 + }
85 + const secretStore = yield* ServerSecretStore.ServerSecretStore;
86 + const replayKey = yield* Crypto.Crypto.pipe(
87 + Effect.flatMap((crypto) =>
88 + crypto.digest("SHA-256", new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)),
89 + ),
90 + Effect.map(Base64Url.encode),
91 + Effect.mapError(
92 + (cause) =>
93 + new ServerAuthDpopReplayKeyCalculationError({
94 + cause,
95 + }),
96 + ),
97 + );
98 + yield* secretStore
99 + .create(
100 + `${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`,
101 + new TextEncoder().encode(
102 + [
103 + `thumbprint=${result.thumbprint}`,
104 + `jti=${result.jti}`,
105 + `iat=${result.iat}`,
106 + `consumedAt=${DateTime.formatIso(now)}`,
107 + ].join("\n"),
108 ),
91 - Effect.map(Base64Url.encode),
92 - Effect.mapError(
93 - (cause) =>
94 - new ServerAuthDpopReplayKeyCalculationError({
95 - cause,
96 - }),
109 + )
110 + .pipe(
111 + Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
112 + Effect.gen(function* () {
113 + const mapped = mapDpopReplayStoreError(error);
114 + if (mapped._tag === "ServerAuthInvalidCredentialError") {
115 + yield* Effect.annotateCurrentSpan({
116 + "environment.dpop.failure_code": mapped.dpopFailureReason,
117 + });
118 + }
119 + return yield* mapped;
120 + }),
121 ),
122 );
99 - yield* secretStore
100 - .create(
101 - `${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`,
102 - new TextEncoder().encode(
103 - [
104 - `thumbprint=${result.thumbprint}`,
105 - `jti=${result.jti}`,
106 - `iat=${result.iat}`,
107 - `consumedAt=${DateTime.formatIso(now)}`,
108 - ].join("\n"),
109 - ),
110 - )
111 - .pipe(
112 - Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
113 - Effect.gen(function* () {
114 - const mapped = mapDpopReplayStoreError(error);
115 - if (mapped._tag === "ServerAuthInvalidCredentialError") {
116 - yield* Effect.annotateCurrentSpan({
117 - "environment.dpop.failure_code": mapped.dpopFailureReason,
118 - });
119 - }
120 - return yield* mapped;
121 - }),
122 - ),
123 - );
124 - return result.thumbprint;
125 - });
123 + return result.thumbprint;
124 +});
apps/server/src/auth/http.ts
+12 -10
@@ -51,8 +51,9 @@ const appendDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request,
51 Effect.succeed(HttpServerResponse.setHeader(response, "www-authenticate", "DPoP")),
52 );
53
54 -const appendDpopChallengeOnUnauthorized = (error: EnvironmentAuthInvalidError) =>
55 - Effect.gen(function* () {
54 +const appendDpopChallengeOnUnauthorized =
55 + /* Request instrumentation already owns the span; keep this helper in that context. */
56 + Effect.fnUntraced(function* (error: EnvironmentAuthInvalidError) {
57 const request = yield* HttpServerRequest.HttpServerRequest;
58 const usesDpop =
59 (request.originalUrl.startsWith("/oauth/token") && request.headers.dpop !== undefined) ||
@@ -68,8 +69,9 @@ const currentEnvironmentTraceId = Effect.currentParentSpan.pipe(
69 Effect.orElseSucceed(() => "unavailable"),
70 );
71
71 -export function annotateEnvironmentRequest(endpoint: string) {
72 - return Effect.gen(function* () {
72 +export const annotateEnvironmentRequest =
73 + /* Request instrumentation already owns the span; keep this helper in that context. */
74 + Effect.fnUntraced(function* (endpoint: string) {
75 const request = yield* HttpServerRequest.HttpServerRequest;
76 const url = HttpServerRequest.toURL(request);
77 const traceId = yield* currentEnvironmentTraceId;
@@ -91,7 +93,6 @@ export function annotateEnvironmentRequest(endpoint: string) {
93 "url.path": url._tag === "Some" ? url.value.pathname : "unknown",
94 });
95 });
94 -}
96
97 export function failEnvironmentAuthInvalid(
98 reason: EnvironmentAuthInvalidReason,
@@ -160,8 +161,9 @@ export function failEnvironmentNotFound(reason: EnvironmentResourceNotFoundReaso
161 * authenticate the way the `/ws` upgrade does: a cookie for browser sessions, or a short-lived
162 * `wsTicket` minted over authenticated HTTP for bearer and DPoP clients.
163 */
163 -export const authenticateMediaRequest = (requiredScope: AuthEnvironmentScope) =>
164 - Effect.gen(function* () {
164 +export const authenticateMediaRequest =
165 + /* Request instrumentation already owns the span; keep this helper in that context. */
166 + Effect.fnUntraced(function* (requiredScope: AuthEnvironmentScope) {
167 const request = yield* HttpServerRequest.HttpServerRequest;
168 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
169 const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(
@@ -183,8 +185,9 @@ export const authenticateMediaRequest = (requiredScope: AuthEnvironmentScope) =>
185 return session;
186 });
187
186 -export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {
187 - return Effect.gen(function* () {
188 +export const failEnvironmentInternal =
189 + /* Request instrumentation already owns the span; keep this helper in that context. */
190 + Effect.fnUntraced(function* (reason: EnvironmentInternalErrorReason, error?: unknown) {
191 const traceId = yield* currentEnvironmentTraceId;
192 if (error !== undefined) {
193 yield* Effect.logError("environment api operation failed", {
@@ -195,7 +198,6 @@ export function failEnvironmentInternal(reason: EnvironmentInternalErrorReason,
198 }
199 return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId });
200 });
198 -}
201
202 const appendSessionCookie = (cookieName: string, token: string, expiresAt: DateTime.DateTime) =>
203 Effect.fromResult(
apps/server/src/auth/mcpOAuthHttp.ts
+6 -5
@@ -38,11 +38,12 @@ const requestUrls = Effect.map(HttpServerRequest.HttpServerRequest, McpOAuth.req
38 * An unverified client or redirect is reported, never redirected; any other problem goes back to
39 * the agent through its (verified) redirect URI.
40 */
41 -const forwardedAuthorization = (
42 - oauth: McpOAuth.McpOAuth["Service"],
43 - request: AuthMcpAuthorizationRequest,
44 -) =>
45 - Effect.gen(function* () {
41 +const forwardedAuthorization =
42 + /* Request instrumentation already owns the span; keep this helper in that context. */
43 + Effect.fnUntraced(function* (
44 + oauth: McpOAuth.McpOAuth["Service"],
45 + request: AuthMcpAuthorizationRequest,
46 + ) {
47 const urls = yield* requestUrls;
48 return yield* oauth.validateAuthorization({ urls, request }).pipe(
49 Effect.catchTags({
apps/server/src/bootstrap.ts
+34 -33
@@ -166,43 +166,44 @@ const isFdReady = (fd: number) =>
166 }),
167 );
168
169 -const makeBootstrapInputStream = (fd: number) =>
170 - Effect.gen(function* () {
171 - const platform = yield* HostProcess.Platform;
172 - const fdPath = resolveFdPath(fd, platform);
173 - return yield* Effect.try<NodeStream.Readable, BootstrapInputStreamOpenError>({
174 - try: () => {
175 - if (fdPath === undefined) {
176 - return makeDirectBootstrapStream(fd);
177 - }
169 +const makeBootstrapInputStream = Effect.fn("bootstrap.makeBootstrapInputStream")(function* (
170 + fd: number,
171 +) {
172 + const platform = yield* HostProcess.Platform;
173 + const fdPath = resolveFdPath(fd, platform);
174 + return yield* Effect.try<NodeStream.Readable, BootstrapInputStreamOpenError>({
175 + try: () => {
176 + if (fdPath === undefined) {
177 + return makeDirectBootstrapStream(fd);
178 + }
179
179 - let streamFd: number | undefined;
180 - try {
181 - streamFd = NodeFS.openSync(fdPath, "r");
182 - return NodeFS.createReadStream("", {
183 - fd: streamFd,
184 - encoding: "utf8",
185 - autoClose: true,
186 - });
187 - } catch (error) {
188 - if (isBootstrapFdPathDuplicationError(error)) {
189 - if (streamFd !== undefined) {
190 - NodeFS.closeSync(streamFd);
191 - }
192 - return makeDirectBootstrapStream(fd);
180 + let streamFd: number | undefined;
181 + try {
182 + streamFd = NodeFS.openSync(fdPath, "r");
183 + return NodeFS.createReadStream("", {
184 + fd: streamFd,
185 + encoding: "utf8",
186 + autoClose: true,
187 + });
188 + } catch (error) {
189 + if (isBootstrapFdPathDuplicationError(error)) {
190 + if (streamFd !== undefined) {
191 + NodeFS.closeSync(streamFd);
192 }
194 - throw error;
193 + return makeDirectBootstrapStream(fd);
194 }
196 - },
197 - catch: (error) =>
198 - new BootstrapInputStreamOpenError({
199 - fd,
200 - platform,
201 - ...(fdPath === undefined ? {} : { fdPath }),
202 - cause: error,
203 - }),
204 - });
195 + throw error;
196 + }
197 + },
198 + catch: (error) =>
199 + new BootstrapInputStreamOpenError({
200 + fd,
201 + platform,
202 + ...(fdPath === undefined ? {} : { fdPath }),
203 + cause: error,
204 + }),
205 });
206 +});
207
208 const makeDirectBootstrapStream = (fd: number): NodeStream.Readable => {
209 try {
apps/server/src/cli/auth.ts
+16 -17
@@ -23,29 +23,28 @@ import {
23 resolveCliAuthConfig,
24 } from "./config.ts";
25
26 -const runWithEnvironmentAuth = <A, E>(
26 +const runWithEnvironmentAuth = Effect.fn("auth.runWithEnvironmentAuth")(function* <A, E>(
27 flags: CliAuthLocationFlags,
28 run: (environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,
29 options?: {
30 readonly quietLogs?: boolean;
31 },
32 -) =>
33 - Effect.gen(function* () {
34 - const logLevel = yield* GlobalFlag.LogLevel;
35 - const config = yield* resolveCliAuthConfig(flags, logLevel);
36 - const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
37 - return yield* Effect.gen(function* () {
38 - const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
39 - return yield* run(environmentAuth);
40 - }).pipe(
41 - Effect.provide(
42 - Layer.mergeAll(EnvironmentAuth.layerRuntime).pipe(
43 - Layer.provide(ServerConfig.layer(config)),
44 - Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
45 - ),
32 +) {
33 + const logLevel = yield* GlobalFlag.LogLevel;
34 + const config = yield* resolveCliAuthConfig(flags, logLevel);
35 + const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
36 + return yield* Effect.gen(function* () {
37 + const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
38 + return yield* run(environmentAuth);
39 + }).pipe(
40 + Effect.provide(
41 + Layer.mergeAll(EnvironmentAuth.layerRuntime).pipe(
42 + Layer.provide(ServerConfig.layer(config)),
43 + Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
44 ),
47 - );
48 - });
45 + ),
46 + );
47 +});
48
49 const ttlFlag = Flag.String("ttl").pipe(
50 Flag.withSchema(DurationFromString),
apps/server/src/cli/config.ts
+221 -222
@@ -249,7 +249,7 @@ const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: st
249 return parsePersistedServerObservabilitySettings(raw);
250 });
251
252 -export const resolveServerConfig = (
252 +export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(function* (
253 flags: CliServerFlags,
254 cliLogLevel: Option.Option<LogLevel.LogLevel>,
255 options?: {
@@ -257,235 +257,234 @@ export const resolveServerConfig = (
257 readonly forceAutoBootstrapProjectFromCwd?: boolean;
258 readonly rejectRunningServer?: boolean;
259 },
260 -) =>
261 - Effect.gen(function* () {
262 - const { findAvailablePort } = yield* NetService.NetService;
263 - const path = yield* Path.Path;
264 - const fs = yield* FileSystem.FileSystem;
265 - const env = yield* EnvServerConfig;
266 - const normalizedFlags = {
267 - mode: flags.mode ?? Option.none(),
268 - port: flags.port ?? Option.none(),
269 - host: flags.host ?? Option.none(),
270 - baseDir: flags.baseDir ?? Option.none(),
271 - cwd: flags.cwd ?? Option.none(),
272 - devUrl: flags.devUrl ?? Option.none(),
273 - noBrowser: flags.noBrowser ?? Option.none(),
274 - bootstrapFd: flags.bootstrapFd ?? Option.none(),
275 - autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
276 - logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
277 - tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
278 - tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
279 - } satisfies CliServerFlags;
280 - const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
281 - const bootstrapEnvelope =
282 - bootstrapFd !== undefined
283 - ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)
284 - : Option.none();
285 - const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
260 +) {
261 + const { findAvailablePort } = yield* NetService.NetService;
262 + const path = yield* Path.Path;
263 + const fs = yield* FileSystem.FileSystem;
264 + const env = yield* EnvServerConfig;
265 + const normalizedFlags = {
266 + mode: flags.mode ?? Option.none(),
267 + port: flags.port ?? Option.none(),
268 + host: flags.host ?? Option.none(),
269 + baseDir: flags.baseDir ?? Option.none(),
270 + cwd: flags.cwd ?? Option.none(),
271 + devUrl: flags.devUrl ?? Option.none(),
272 + noBrowser: flags.noBrowser ?? Option.none(),
273 + bootstrapFd: flags.bootstrapFd ?? Option.none(),
274 + autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
275 + logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
276 + tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
277 + tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
278 + } satisfies CliServerFlags;
279 + const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
280 + const bootstrapEnvelope =
281 + bootstrapFd !== undefined
282 + ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)
283 + : Option.none();
284 + const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
285
287 - const mode: ServerConfig.RuntimeMode = Option.getOrElse(
288 - resolveOptionPrecedence(
289 - normalizedFlags.mode,
290 - Option.fromUndefinedOr(env.mode),
291 - Option.fromUndefinedOr(bootstrap?.mode),
292 - ),
293 - () => "web",
294 - );
286 + const mode: ServerConfig.RuntimeMode = Option.getOrElse(
287 + resolveOptionPrecedence(
288 + normalizedFlags.mode,
289 + Option.fromUndefinedOr(env.mode),
290 + Option.fromUndefinedOr(bootstrap?.mode),
291 + ),
292 + () => "web",
293 + );
294
296 - const port = yield* Option.match(
297 - resolveOptionPrecedence(
298 - normalizedFlags.port,
299 - Option.fromUndefinedOr(env.port),
300 - Option.fromUndefinedOr(bootstrap?.port),
301 - ),
302 - {
303 - onSome: (value) => Effect.succeed(value),
304 - onNone: () => {
305 - if (mode === "desktop") {
306 - return Effect.succeed(ServerConfig.DEFAULT_PORT);
307 - }
308 - return findAvailablePort(ServerConfig.DEFAULT_PORT);
309 - },
295 + const port = yield* Option.match(
296 + resolveOptionPrecedence(
297 + normalizedFlags.port,
298 + Option.fromUndefinedOr(env.port),
299 + Option.fromUndefinedOr(bootstrap?.port),
300 + ),
301 + {
302 + onSome: (value) => Effect.succeed(value),
303 + onNone: () => {
304 + if (mode === "desktop") {
305 + return Effect.succeed(ServerConfig.DEFAULT_PORT);
306 + }
307 + return findAvailablePort(ServerConfig.DEFAULT_PORT);
308 },
311 - );
312 - const devUrl = Option.getOrElse(
313 - resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
314 - () => undefined,
315 - );
316 - const devAuthToken =
317 - mode === "web" && devUrl !== undefined ? yield* DevAuthTokenConfig : undefined;
318 - const explicitBaseDir = resolveOptionPrecedence(
319 - normalizedFlags.baseDir,
320 - Option.fromUndefinedOr(env.t3Home),
321 - ).pipe(Option.filter((value) => value.trim().length > 0));
322 - const baseDir = yield* resolveBaseDir(
323 - Option.getOrUndefined(
324 - resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
325 - ),
326 - );
327 - const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
328 - const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
329 - const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
330 - baseDirIsExplicit: Option.isSome(explicitBaseDir),
331 - });
332 - // An interactive CLI must not start over a discovered server. Lifetime locking
333 - // and supervisor handoff are separate; this preflight cannot arbitrate two starts.
334 - if (options?.rejectRunningServer && mode === "web") {
335 - const runtime = yield* readPersistedServerRuntimeState(derivedPaths.serverRuntimeStatePath);
336 - // A killed container can leave a record with the new server's own PID.
337 - if (
338 - Option.isSome(runtime) &&
339 - runtime.value.pid > 0 &&
340 - runtime.value.pid !== process.pid &&
341 - isProcessAlive(runtime.value.pid)
342 - ) {
343 - return yield* new CliError.UserError({
344 - 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.`,
345 - });
346 - }
309 + },
310 + );
311 + const devUrl = Option.getOrElse(
312 + resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
313 + () => undefined,
314 + );
315 + const devAuthToken =
316 + mode === "web" && devUrl !== undefined ? yield* DevAuthTokenConfig : undefined;
317 + const explicitBaseDir = resolveOptionPrecedence(
318 + normalizedFlags.baseDir,
319 + Option.fromUndefinedOr(env.t3Home),
320 + ).pipe(Option.filter((value) => value.trim().length > 0));
321 + const baseDir = yield* resolveBaseDir(
322 + Option.getOrUndefined(
323 + resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
324 + ),
325 + );
326 + const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
327 + const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
328 + const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
329 + baseDirIsExplicit: Option.isSome(explicitBaseDir),
330 + });
331 + // An interactive CLI must not start over a discovered server. Lifetime locking
332 + // and supervisor handoff are separate; this preflight cannot arbitrate two starts.
333 + if (options?.rejectRunningServer && mode === "web") {
334 + const runtime = yield* readPersistedServerRuntimeState(derivedPaths.serverRuntimeStatePath);
335 + // A killed container can leave a record with the new server's own PID.
336 + if (
337 + Option.isSome(runtime) &&
338 + runtime.value.pid > 0 &&
339 + runtime.value.pid !== process.pid &&
340 + isProcessAlive(runtime.value.pid)
341 + ) {
342 + return yield* new CliError.UserError({
343 + 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.`,
344 + });
345 }
348 - yield* fs.makeDirectory(cwd, { recursive: true });
349 - yield* ServerConfig.ensureServerDirectories(derivedPaths);
350 - const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
351 - derivedPaths.settingsPath,
352 - );
353 - const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
354 - yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
355 - const startupPresentation = options?.startupPresentation ?? "browser";
356 - const isHeadlessStartup = startupPresentation === "headless";
357 - const noBrowser = Option.getOrElse(
358 - resolveOptionPrecedence(
359 - isHeadlessStartup ? Option.some(true) : Option.none(),
360 - normalizedFlags.noBrowser,
361 - Option.fromUndefinedOr(env.noBrowser),
362 - Option.fromUndefinedOr(bootstrap?.noBrowser),
363 - ),
364 - () => mode === "desktop",
365 - );
366 - const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
367 - const desktopBootstrapSecret = bootstrap?.desktopBootstrapSecret;
368 - const shellEnvironmentPrepared = bootstrap?.shellEnvironmentPrepared;
369 - const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
370 - const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
371 - const desktopBrowserFd = bootstrap?.desktopBrowserFd;
372 - const desktopBrowserControlFd = bootstrap?.desktopBrowserControlFd;
373 - const resourceMonitorPath = bootstrap?.resourceMonitorPath;
374 - const autoBootstrapProjectFromCwd = Option.getOrElse(
375 - resolveOptionPrecedence(
376 - Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
377 - isHeadlessStartup ? Option.some(false) : Option.none(),
378 - normalizedFlags.autoBootstrapProjectFromCwd,
379 - Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
380 - ),
381 - () => mode === "web",
382 - );
383 - const logWebSocketEvents = Option.getOrElse(
384 - resolveOptionPrecedence(
385 - normalizedFlags.logWebSocketEvents,
386 - Option.fromUndefinedOr(env.logWebSocketEvents),
387 - ),
388 - () => Boolean(devUrl),
389 - );
390 - const tailscaleServeEnabled = Option.getOrElse(
391 - resolveOptionPrecedence(
392 - normalizedFlags.tailscaleServeEnabled,
393 - Option.fromUndefinedOr(env.tailscaleServeEnabled),
394 - Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
395 - ),
396 - () => false,
397 - );
398 - const tailscaleServePort = Option.getOrElse(
399 - resolveOptionPrecedence(
400 - normalizedFlags.tailscaleServePort,
401 - Option.fromUndefinedOr(env.tailscaleServePort),
402 - Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
403 - ),
404 - () => 443,
405 - );
406 - const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
407 - const host = Option.getOrElse(
408 - resolveOptionPrecedence(
409 - normalizedFlags.host,
410 - Option.fromUndefinedOr(env.host),
411 - Option.fromUndefinedOr(bootstrap?.host),
412 - ),
413 - () => (mode === "desktop" ? "127.0.0.1" : undefined),
414 - );
415 - const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
346 + }
347 + yield* fs.makeDirectory(cwd, { recursive: true });
348 + yield* ServerConfig.ensureServerDirectories(derivedPaths);
349 + const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
350 + derivedPaths.settingsPath,
351 + );
352 + const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
353 + yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
354 + const startupPresentation = options?.startupPresentation ?? "browser";
355 + const isHeadlessStartup = startupPresentation === "headless";
356 + const noBrowser = Option.getOrElse(
357 + resolveOptionPrecedence(
358 + isHeadlessStartup ? Option.some(true) : Option.none(),
359 + normalizedFlags.noBrowser,
360 + Option.fromUndefinedOr(env.noBrowser),
361 + Option.fromUndefinedOr(bootstrap?.noBrowser),
362 + ),
363 + () => mode === "desktop",
364 + );
365 + const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
366 + const desktopBootstrapSecret = bootstrap?.desktopBootstrapSecret;
367 + const shellEnvironmentPrepared = bootstrap?.shellEnvironmentPrepared;
368 + const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
369 + const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
370 + const desktopBrowserFd = bootstrap?.desktopBrowserFd;
371 + const desktopBrowserControlFd = bootstrap?.desktopBrowserControlFd;
372 + const resourceMonitorPath = bootstrap?.resourceMonitorPath;
373 + const autoBootstrapProjectFromCwd = Option.getOrElse(
374 + resolveOptionPrecedence(
375 + Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
376 + isHeadlessStartup ? Option.some(false) : Option.none(),
377 + normalizedFlags.autoBootstrapProjectFromCwd,
378 + Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
379 + ),
380 + () => mode === "web",
381 + );
382 + const logWebSocketEvents = Option.getOrElse(
383 + resolveOptionPrecedence(
384 + normalizedFlags.logWebSocketEvents,
385 + Option.fromUndefinedOr(env.logWebSocketEvents),
386 + ),
387 + () => Boolean(devUrl),
388 + );
389 + const tailscaleServeEnabled = Option.getOrElse(
390 + resolveOptionPrecedence(
391 + normalizedFlags.tailscaleServeEnabled,
392 + Option.fromUndefinedOr(env.tailscaleServeEnabled),
393 + Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
394 + ),
395 + () => false,
396 + );
397 + const tailscaleServePort = Option.getOrElse(
398 + resolveOptionPrecedence(
399 + normalizedFlags.tailscaleServePort,
400 + Option.fromUndefinedOr(env.tailscaleServePort),
401 + Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
402 + ),
403 + () => 443,
404 + );
405 + const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
406 + const host = Option.getOrElse(
407 + resolveOptionPrecedence(
408 + normalizedFlags.host,
409 + Option.fromUndefinedOr(env.host),
410 + Option.fromUndefinedOr(bootstrap?.host),
411 + ),
412 + () => (mode === "desktop" ? "127.0.0.1" : undefined),
413 + );
414 + const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
415
417 - const otel = yield* OtelEnvironment.load;
416 + const otel = yield* OtelEnvironment.load;
417
419 - const signalExport: SignalExport = {
420 - protocol: env.otlpProtocol,
421 - headers: env.otlpHeaders,
422 - exportIntervalMs: env.otlpExportIntervalMs,
423 - };
424 - const traces = OtelEnvironment.resolveSignalEndpoint(
425 - otel,
426 - "traces",
427 - { url: env.otlpTracesUrl, export: signalExport },
428 - bootstrap?.otlpTracesUrl,
429 - persistedObservabilitySettings.otlpTracesUrl,
430 - );
431 - const metrics = OtelEnvironment.resolveSignalEndpoint(
432 - otel,
433 - "metrics",
434 - { url: env.otlpMetricsUrl, export: signalExport },
435 - bootstrap?.otlpMetricsUrl,
436 - persistedObservabilitySettings.otlpMetricsUrl,
437 - );
438 - const logs = OtelEnvironment.resolveSignalEndpoint(
439 - otel,
440 - "logs",
441 - { url: env.otlpLogsUrl, export: signalExport },
442 - bootstrap?.otlpLogsUrl,
443 - persistedObservabilitySettings.otlpLogsUrl,
444 - );
418 + const signalExport: SignalExport = {
419 + protocol: env.otlpProtocol,
420 + headers: env.otlpHeaders,
421 + exportIntervalMs: env.otlpExportIntervalMs,
422 + };
423 + const traces = OtelEnvironment.resolveSignalEndpoint(
424 + otel,
425 + "traces",
426 + { url: env.otlpTracesUrl, export: signalExport },
427 + bootstrap?.otlpTracesUrl,
428 + persistedObservabilitySettings.otlpTracesUrl,
429 + );
430 + const metrics = OtelEnvironment.resolveSignalEndpoint(
431 + otel,
432 + "metrics",
433 + { url: env.otlpMetricsUrl, export: signalExport },
434 + bootstrap?.otlpMetricsUrl,
435 + persistedObservabilitySettings.otlpMetricsUrl,
436 + );
437 + const logs = OtelEnvironment.resolveSignalEndpoint(
438 + otel,
439 + "logs",
440 + { url: env.otlpLogsUrl, export: signalExport },
441 + bootstrap?.otlpLogsUrl,
442 + persistedObservabilitySettings.otlpLogsUrl,
443 + );
444
446 - const config: ServerConfig.ServerConfig["Service"] = {
447 - logLevel,
448 - traceMinLevel: env.traceMinLevel,
449 - traceTimingEnabled: env.traceTimingEnabled,
450 - traceBatchWindowMs: env.traceBatchWindowMs,
451 - traceMaxBytes: env.traceMaxBytes,
452 - traceMaxFiles: env.traceMaxFiles,
453 - otlpTracesUrl: traces?.url,
454 - otlpMetricsUrl: metrics?.url,
455 - otlpLogsUrl: logs?.url,
456 - otlpTracesExport: traces?.export ?? signalExport,
457 - otlpMetricsExport: metrics?.export ?? signalExport,
458 - otlpLogsExport: logs?.export ?? signalExport,
459 - otelEnvironment: otel,
460 - mode,
461 - port,
462 - cwd,
463 - baseDir,
464 - ...derivedPaths,
465 - serverTracePath,
466 - host,
467 - staticDir,
468 - devUrl,
469 - ...(devAuthToken === undefined ? {} : { devAuthToken }),
470 - devAllowedOrigins: env.devAllowedOrigins,
471 - noBrowser,
472 - startupPresentation,
473 - desktopBootstrapToken,
474 - ...(desktopBootstrapSecret === undefined ? {} : { desktopBootstrapSecret }),
475 - ...(shellEnvironmentPrepared === undefined ? {} : { shellEnvironmentPrepared }),
476 - desktopTelemetryFd,
477 - desktopTelemetryControlFd,
478 - desktopBrowserFd,
479 - desktopBrowserControlFd,
480 - resourceMonitorPath,
481 - autoBootstrapProjectFromCwd,
482 - logWebSocketEvents,
483 - tailscaleServeEnabled,
484 - tailscaleServePort,
485 - };
445 + const config: ServerConfig.ServerConfig["Service"] = {
446 + logLevel,
447 + traceMinLevel: env.traceMinLevel,
448 + traceTimingEnabled: env.traceTimingEnabled,
449 + traceBatchWindowMs: env.traceBatchWindowMs,
450 + traceMaxBytes: env.traceMaxBytes,
451 + traceMaxFiles: env.traceMaxFiles,
452 + otlpTracesUrl: traces?.url,
453 + otlpMetricsUrl: metrics?.url,
454 + otlpLogsUrl: logs?.url,
455 + otlpTracesExport: traces?.export ?? signalExport,
456 + otlpMetricsExport: metrics?.export ?? signalExport,
457 + otlpLogsExport: logs?.export ?? signalExport,
458 + otelEnvironment: otel,
459 + mode,
460 + port,
461 + cwd,
462 + baseDir,
463 + ...derivedPaths,
464 + serverTracePath,
465 + host,
466 + staticDir,
467 + devUrl,
468 + ...(devAuthToken === undefined ? {} : { devAuthToken }),
469 + devAllowedOrigins: env.devAllowedOrigins,
470 + noBrowser,
471 + startupPresentation,
472 + desktopBootstrapToken,
473 + ...(desktopBootstrapSecret === undefined ? {} : { desktopBootstrapSecret }),
474 + ...(shellEnvironmentPrepared === undefined ? {} : { shellEnvironmentPrepared }),
475 + desktopTelemetryFd,
476 + desktopTelemetryControlFd,
477 + desktopBrowserFd,
478 + desktopBrowserControlFd,
479 + resourceMonitorPath,
480 + autoBootstrapProjectFromCwd,
481 + logWebSocketEvents,
482 + tailscaleServeEnabled,
483 + tailscaleServePort,
484 + };
485
487 - return config;
488 - });
486 + return config;
487 +});
488
489 export const resolveCliAuthConfig = (
490 flags: CliAuthLocationFlags,
apps/server/src/cli/invocation.ts
+28 -25
@@ -170,21 +170,23 @@ const resolveInstallLauncher = Effect.gen(function* () {
170 * installs. `args` are quoted for the host's shell: POSIX, or PowerShell on
171 * Windows.
172 */
173 -export const resolveHostCliCommand = (subcommand: string, args: ReadonlyArray<string> = []) =>
174 - Effect.gen(function* () {
175 - const platform = yield* HostProcess.Platform;
176 - const withArgs = (prefix: string) =>
177 - [prefix, ...args.map((arg) => hostShellWord(platform, arg))].join(" ");
178 - const command = yield* resolveCliCommand(subcommand);
179 - if (command !== `t3 ${subcommand}`) return { command: withArgs(command), launcher: false };
180 - if (yield* isCommandAvailable("t3")) return { command: withArgs(command), launcher: false };
181 - const launcher = yield* resolveInstallLauncher;
182 - if (Option.isNone(launcher)) return { command: withArgs(command), launcher: false };
183 - // PowerShell runs a quoted path only through the call operator.
184 - const quoted = hostShellWord(platform, launcher.value);
185 - const call = platform === "win32" ? `& ${quoted}` : quoted;
186 - return { command: withArgs(`${call} ${subcommand}`), launcher: true };
187 - });
173 +export const resolveHostCliCommand = Effect.fn("invocation.resolveHostCliCommand")(function* (
174 + subcommand: string,
175 + args: ReadonlyArray<string> = [],
176 +) {
177 + const platform = yield* HostProcess.Platform;
178 + const withArgs = (prefix: string) =>
179 + [prefix, ...args.map((arg) => hostShellWord(platform, arg))].join(" ");
180 + const command = yield* resolveCliCommand(subcommand);
181 + if (command !== `t3 ${subcommand}`) return { command: withArgs(command), launcher: false };
182 + if (yield* isCommandAvailable("t3")) return { command: withArgs(command), launcher: false };
183 + const launcher = yield* resolveInstallLauncher;
184 + if (Option.isNone(launcher)) return { command: withArgs(command), launcher: false };
185 + // PowerShell runs a quoted path only through the call operator.
186 + const quoted = hostShellWord(platform, launcher.value);
187 + const call = platform === "win32" ? `& ${quoted}` : quoted;
188 + return { command: withArgs(`${call} ${subcommand}`), launcher: true };
189 +});
190
191 /**
192 * `sudo` resets PATH on most distributions, which drops a user-installed Node
@@ -192,16 +194,17 @@ export const resolveHostCliCommand = (subcommand: string, args: ReadonlyArray<st
194 * carries PATH through unless Node is on root's PATH too. An absolute launcher
195 * needs neither.
196 */
195 -export const resolveRootCliCommand = (subcommand: string) =>
196 - Effect.gen(function* () {
197 - const { command, launcher } = yield* resolveHostCliCommand(subcommand);
198 - if (launcher) return `sudo ${command}`;
199 - const executablePath = yield* HostProcess.ExecutablePath;
200 - const systemNode = ROOT_PATH_DIRECTORIES.some((directory) =>
201 - executablePath.startsWith(`${directory}/`),
202 - );
203 - return systemNode ? `sudo ${command}` : `sudo env "PATH=$PATH" ${command}`;
204 - });
197 +export const resolveRootCliCommand = Effect.fn("invocation.resolveRootCliCommand")(function* (
198 + subcommand: string,
199 +) {
200 + const { command, launcher } = yield* resolveHostCliCommand(subcommand);
201 + if (launcher) return `sudo ${command}`;
202 + const executablePath = yield* HostProcess.ExecutablePath;
203 + const systemNode = ROOT_PATH_DIRECTORIES.some((directory) =>
204 + executablePath.startsWith(`${directory}/`),
205 + );
206 + return systemNode ? `sudo ${command}` : `sudo env "PATH=$PATH" ${command}`;
207 +});
208
209 const ROOT_PATH_DIRECTORIES = [
210 "/usr/local/sbin",
apps/server/src/cli/pair.ts
+8 -4
@@ -180,10 +180,12 @@ type EnvironmentProbeResult =
180 | { readonly _tag: "unreachable" }
181 | { readonly _tag: "not-a-t3-server" };
182
183 -const probeEnvironmentDescriptor = (
183 +const probeEnvironmentDescriptor: (
184 baseUrl: string,
185 -): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>
186 - Effect.gen(function* () {
185 +) => Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> = Effect.fn(
186 + "pair.probeEnvironmentDescriptor",
187 +)(
188 + function* (baseUrl: string) {
189 const client = yield* HttpClient.HttpClient;
190 const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());
191 const response = yield* client.execute(request).pipe(
@@ -202,7 +204,9 @@ const probeEnvironmentDescriptor = (
204 Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
205 );
206 return { _tag: "descriptor", descriptor } as const;
205 - }).pipe(Effect.catch((outcome) => Effect.succeed(outcome)));
207 + },
208 + Effect.catch((outcome) => Effect.succeed(outcome)),
209 +);
210
211 interface DiscoveredPairTarget {
212 readonly baseDir: string;
apps/server/src/cli/project.ts
+18 -16
@@ -316,32 +316,34 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
316 } satisfies ProjectMutationTarget;
317 });
318
319 -const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
320 - Effect.gen(function* () {
319 +const fetchLiveOrchestrationSnapshot = Effect.fn("project.fetchLiveOrchestrationSnapshot")(
320 + function* (origin: string, bearerToken: string) {
321 const client = yield* makeLiveServerClient(origin);
322 return yield* client.projects.snapshot({
323 headers: { authorization: `Bearer ${bearerToken}` },
324 });
325 - }).pipe(
326 - withProjectCliLiveServerTimeout,
327 - Effect.mapError(projectCommandErrorFromLiveServerRequest),
328 - );
325 + },
326 + (effect, _origin, _bearerToken) =>
327 + effect.pipe(
328 + withProjectCliLiveServerTimeout,
329 + Effect.mapError(projectCommandErrorFromLiveServerRequest),
330 + ),
331 +);
332
330 -const dispatchLiveOrchestrationCommand = (
331 - origin: string,
332 - bearerToken: string,
333 - command: ProjectCliDispatchCommand,
334 -) =>
335 - Effect.gen(function* () {
333 +const dispatchLiveOrchestrationCommand = Effect.fn("project.dispatchLiveOrchestrationCommand")(
334 + function* (origin: string, bearerToken: string, command: ProjectCliDispatchCommand) {
335 const client = yield* makeLiveServerClient(origin);
336 yield* client.projects.mutate({
337 headers: { authorization: `Bearer ${bearerToken}` },
338 payload: command,
339 } as Parameters<typeof client.projects.mutate>[0]);
341 - }).pipe(
342 - withProjectCliLiveServerTimeout,
343 - Effect.mapError(projectCommandErrorFromLiveServerRequest),
344 - );
340 + },
341 + (effect, _origin, _bearerToken, _command) =>
342 + effect.pipe(
343 + withProjectCliLiveServerTimeout,
344 + Effect.mapError(projectCommandErrorFromLiveServerRequest),
345 + ),
346 +);
347
348 const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
349 const projects = yield* ProjectService.ProjectService;
apps/server/src/cli/server.ts
+35 -38
@@ -13,52 +13,49 @@ import { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } fr
13
14 const encodeCommand = Schema.encodeEffect(Schema.fromJsonString(Schema.String));
15
16 -const runServerCommand = (
16 +const runServerCommand = Effect.fn("server.runServerCommand")(function* (
17 flags: CliServerFlags,
18 options?: {
19 readonly startupPresentation?: ServerConfig.StartupPresentation;
20 readonly forceAutoBootstrapProjectFromCwd?: boolean;
21 readonly rejectRunningServer?: boolean;
22 },
23 -) =>
24 - Effect.gen(function* () {
25 - const logLevel = yield* GlobalFlag.LogLevel;
26 - const config = yield* resolveServerConfig(flags, logLevel, options);
27 - const run = runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config));
28 - if (config.mode !== "desktop" || config.desktopBootstrapToken === undefined) return yield* run;
29 - return yield* Effect.raceFirst(
30 - run,
31 - awaitLauncherLoss().pipe(
32 - // End like SIGTERM does (interrupt-only exit, so the runtime forces process exit).
33 - Effect.andThen(Effect.interrupt),
34 - ),
35 - );
36 - });
23 +) {
24 + const logLevel = yield* GlobalFlag.LogLevel;
25 + const config = yield* resolveServerConfig(flags, logLevel, options);
26 + const run = runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config));
27 + if (config.mode !== "desktop" || config.desktopBootstrapToken === undefined) return yield* run;
28 + return yield* Effect.raceFirst(
29 + run,
30 + awaitLauncherLoss().pipe(
31 + // End like SIGTERM does (interrupt-only exit, so the runtime forces process exit).
32 + Effect.andThen(Effect.interrupt),
33 + ),
34 + );
35 +});
36
38 -export const runDefaultServerCommand = (flags: CliServerFlags) =>
39 - Effect.gen(function* () {
40 - if (Option.isSome(flags.cwd)) {
41 - const cwd = flags.cwd.value.trim();
42 - const fs = yield* FileSystem.FileSystem;
43 - const platform = yield* HostProcess.Platform;
44 - const explicitPath =
45 - cwd === "." ||
46 - cwd === ".." ||
47 - cwd === "~" ||
48 - /[/\\]/.test(cwd) ||
49 - (platform === "win32" && /^[a-z]:/i.test(cwd));
50 - if (
51 - !explicitPath &&
52 - (!(yield* fs.exists(cwd)) || (yield* fs.stat(cwd)).type !== "Directory")
53 - ) {
54 - return yield* new CliError.UserError({
55 - cause: cwd,
56 - userMessage: `Unknown command ${yield* encodeCommand(cwd)}. Use "t3 --help" for commands or an explicit path such as "t3 ./my-project" for a new directory.`,
57 - });
58 - }
37 +export const runDefaultServerCommand = Effect.fn("server.runDefaultServerCommand")(function* (
38 + flags: CliServerFlags,
39 +) {
40 + if (Option.isSome(flags.cwd)) {
41 + const cwd = flags.cwd.value.trim();
42 + const fs = yield* FileSystem.FileSystem;
43 + const platform = yield* HostProcess.Platform;
44 + const explicitPath =
45 + cwd === "." ||
46 + cwd === ".." ||
47 + cwd === "~" ||
48 + /[/\\]/.test(cwd) ||
49 + (platform === "win32" && /^[a-z]:/i.test(cwd));
50 + if (!explicitPath && (!(yield* fs.exists(cwd)) || (yield* fs.stat(cwd)).type !== "Directory")) {
51 + return yield* new CliError.UserError({
52 + cause: cwd,
53 + userMessage: `Unknown command ${yield* encodeCommand(cwd)}. Use "t3 --help" for commands or an explicit path such as "t3 ./my-project" for a new directory.`,
54 + });
55 }
60 - return yield* runServerCommand(flags, { rejectRunningServer: true });
61 - });
56 + }
57 + return yield* runServerCommand(flags, { rejectRunningServer: true });
58 +});
59
60 export const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
61 Command.withDescription("Run the T3 Code server."),
apps/server/src/cloud/ManagedEndpointRuntime.ts
+47 -43
@@ -185,8 +185,9 @@ export const make = Effect.gen(function* () {
185 yield* stopConnector(active);
186 });
187
188 - const superviseConnector = (connector: ActiveConnector) =>
189 - Effect.gen(function* () {
188 + // Lives until connector exit and starts replacements; avoid nested lifetime spans.
189 + const superviseConnector = Effect.fnUntraced(
190 + function* (connector: ActiveConnector) {
191 const result = yield* Effect.result(connector.child.exitCode);
192 const activeAtExit = yield* Ref.get(activeRef);
193 if (
@@ -253,9 +254,9 @@ export const make = Effect.gen(function* () {
254 yield* reconcileConfig(desiredConfig);
255 }),
256 );
256 - }).pipe(
257 - Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),
258 - );
257 + },
258 + Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),
259 + );
260
261 // The new connector starts next to the old one on the same tunnel, and the
262 // old one stops only once the new one registers, so clients never see the
@@ -370,8 +371,9 @@ export const make = Effect.gen(function* () {
371 yield* Effect.forkIn(retryPinnedRelayClientInstall, runtimeScope);
372 });
373
373 - const watchConnectorRegistration = (connector: ActiveConnector) =>
374 - Effect.gen(function* () {
374 + // Registration retries can last for the connector lifetime; keep this loop untraced.
375 + const watchConnectorRegistration = Effect.fnUntraced(
376 + function* (connector: ActiveConnector) {
377 yield* Effect.sleep(CONNECTOR_REGISTRATION_TIMEOUT);
378 if (yield* Deferred.isDone(connector.registered)) return true;
379 yield* Effect.logWarning(
@@ -384,46 +386,48 @@ export const make = Effect.gen(function* () {
386 );
387 yield* Queue.offer(recoveryRequests, connector.config);
388 return false;
387 - }).pipe(Effect.repeat({ until: (connected) => connected }));
389 + },
390 + Effect.repeat({ until: (connected) => connected }),
391 + );
392
393 // Only an explicit 503 counts: a failed request says nothing about the
390 - const watchConnectorReadiness = (connector: ActiveConnector) =>
391 - Effect.gen(function* () {
392 - const readyUrl = `http://${yield* Deferred.await(connector.metricsAddress)}/ready`;
393 - let notReadyChecks = 0;
394 - while (true) {
395 - yield* Effect.sleep(CONNECTOR_READINESS_INTERVAL);
396 - const status = yield* httpClient.get(readyUrl).pipe(
397 - Effect.map((response) => response.status),
398 - Effect.scoped,
399 - Effect.withTracerEnabled(false),
400 - Effect.timeoutOption(CONNECTOR_READINESS_REQUEST_TIMEOUT),
401 - Effect.orElseSucceed(() => Option.none<number>()),
402 - );
403 - if (Option.isNone(status)) continue;
404 - if (status.value === 200) {
405 - notReadyChecks = 0;
406 - yield* Ref.set(notReadyChecksBeforeRestartRef, CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART);
407 - continue;
408 - }
409 - if (status.value !== 503) continue;
410 - notReadyChecks += 1;
411 - const threshold = yield* Ref.get(notReadyChecksBeforeRestartRef);
412 - if (notReadyChecks < threshold) continue;
394 + // Readiness polling runs for the connector lifetime; keep this loop untraced.
395 + const watchConnectorReadiness = Effect.fnUntraced(function* (connector: ActiveConnector) {
396 + const readyUrl = `http://${yield* Deferred.await(connector.metricsAddress)}/ready`;
397 + let notReadyChecks = 0;
398 + while (true) {
399 + yield* Effect.sleep(CONNECTOR_READINESS_INTERVAL);
400 + const status = yield* httpClient.get(readyUrl).pipe(
401 + Effect.map((response) => response.status),
402 + Effect.scoped,
403 + Effect.withTracerEnabled(false),
404 + Effect.timeoutOption(CONNECTOR_READINESS_REQUEST_TIMEOUT),
405 + Effect.orElseSucceed(() => Option.none<number>()),
406 + );
407 + if (Option.isNone(status)) continue;
408 + if (status.value === 200) {
409 notReadyChecks = 0;
414 - yield* Ref.set(
415 - notReadyChecksBeforeRestartRef,
416 - Math.min(threshold * 2, CONNECTOR_NOT_READY_CHECKS_MAX),
417 - );
418 - yield* Effect.logWarning("Relay client has no tunnel connection; restarting it", {
419 - pid: Number(connector.child.pid),
420 - notReadyChecks: threshold,
421 - tunnelId: connector.config.tunnelId,
422 - tunnelName: connector.config.tunnelName,
423 - });
424 - yield* connector.child.kill().pipe(Effect.ignore);
410 + yield* Ref.set(notReadyChecksBeforeRestartRef, CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART);
411 + continue;
412 }
426 - });
413 + if (status.value !== 503) continue;
414 + notReadyChecks += 1;
415 + const threshold = yield* Ref.get(notReadyChecksBeforeRestartRef);
416 + if (notReadyChecks < threshold) continue;
417 + notReadyChecks = 0;
418 + yield* Ref.set(
419 + notReadyChecksBeforeRestartRef,
420 + Math.min(threshold * 2, CONNECTOR_NOT_READY_CHECKS_MAX),
421 + );
422 + yield* Effect.logWarning("Relay client has no tunnel connection; restarting it", {
423 + pid: Number(connector.child.pid),
424 + notReadyChecks: threshold,
425 + tunnelId: connector.config.tunnelId,
426 + tunnelName: connector.config.tunnelName,
427 + });
428 + yield* connector.child.kill().pipe(Effect.ignore);
429 + }
430 + });
431
432 const observeConnectorOutput = (connector: ActiveConnector) => {
433 let rejectedRegistrations = 0;
apps/server/src/cloud/bootService.ts
+52 -53
@@ -877,60 +877,59 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
877 Effect.withSpan("cloud.boot_service.restart"),
878 );
879
880 - const withStopped = <A, E, R>(
880 + const withStopped = Effect.fn("cloud.boot_service.with_stopped")(function* <A, E, R>(
881 operation: Effect.Effect<A, E, R>,
882 - ): Effect.Effect<A, E | BootServiceError, R> =>
883 - Effect.gen(function* () {
884 - if (detectedManager === undefined) return yield* operation;
885 - const manager = detectedManager;
886 - const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
887 - if (Option.isNone(unit)) return yield* operation;
888 - const installedBaseDir = bootServiceBaseDirOf(unit.value);
889 - if (
890 - installedBaseDir === undefined ||
891 - path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
892 - ) {
893 - return yield* operation;
894 - }
895 - // `is-active` fails while a crash-looping unit sits in `activating
896 - // (auto-restart)`, and a throttled launchd job is loaded without a pid;
897 - // both would start the server mid-repair. So the unit is always
898 - // stopped, and started again when it was active, enabled or loaded
899 - // before; a disabled unit caught crash-looping stays stopped.
900 - const restore =
901 - manager.kind === "systemd"
902 - ? yield* Effect.map(
903 - Effect.all(
904 - [
905 - probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
906 - probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
907 - ],
908 - { concurrency: "unbounded" },
909 - ),
910 - ([enabled, active]) => succeeded(active) || succeeded(enabled),
911 - )
912 - : succeeded(
913 - yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
914 - );
915 - return yield* Effect.acquireUseRelease(
916 - // Every stop step is required when the service is to be restored: a
917 - // step that was fine to skip during uninstall would leave the server
918 - // holding the database. A stop that fails (a timeout, say) may still
919 - // have stopped the service, so the restore below runs either way.
920 - // Nothing to restore means nothing is expected to be loaded, and the
921 - // stop is best-effort (launchd's bootout fails on an unloaded job).
922 - runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),
923 - (stopped): Effect.Effect<A, E | BootServiceError, R> =>
924 - Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),
925 - (_, exit) => {
926 - if (!restore) return Effect.void;
927 - // Start only: `activate` would also enable a unit the user disabled.
928 - // When the operation itself failed, its error is the one worth reporting.
929 - const start = runSteps(manager.restart);
930 - return Exit.isFailure(exit) ? Effect.ignore(start) : start;
931 - },
932 - );
933 - }).pipe(Effect.withSpan("cloud.boot_service.with_stopped"));
882 + ): Effect.fn.Return<A, E | BootServiceError, R> {
883 + if (detectedManager === undefined) return yield* operation;
884 + const manager = detectedManager;
885 + const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
886 + if (Option.isNone(unit)) return yield* operation;
887 + const installedBaseDir = bootServiceBaseDirOf(unit.value);
888 + if (
889 + installedBaseDir === undefined ||
890 + path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
891 + ) {
892 + return yield* operation;
893 + }
894 + // `is-active` fails while a crash-looping unit sits in `activating
895 + // (auto-restart)`, and a throttled launchd job is loaded without a pid;
896 + // both would start the server mid-repair. So the unit is always
897 + // stopped, and started again when it was active, enabled or loaded
898 + // before; a disabled unit caught crash-looping stays stopped.
899 + const restore =
900 + manager.kind === "systemd"
901 + ? yield* Effect.map(
902 + Effect.all(
903 + [
904 + probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
905 + probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
906 + ],
907 + { concurrency: "unbounded" },
908 + ),
909 + ([enabled, active]) => succeeded(active) || succeeded(enabled),
910 + )
911 + : succeeded(
912 + yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
913 + );
914 + return yield* Effect.acquireUseRelease(
915 + // Every stop step is required when the service is to be restored: a
916 + // step that was fine to skip during uninstall would leave the server
917 + // holding the database. A stop that fails (a timeout, say) may still
918 + // have stopped the service, so the restore below runs either way.
919 + // Nothing to restore means nothing is expected to be loaded, and the
920 + // stop is best-effort (launchd's bootout fails on an unloaded job).
921 + runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),
922 + (stopped): Effect.Effect<A, E | BootServiceError, R> =>
923 + Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),
924 + (_, exit) => {
925 + if (!restore) return Effect.void;
926 + // Start only: `activate` would also enable a unit the user disabled.
927 + // When the operation itself failed, its error is the one worth reporting.
928 + const start = runSteps(manager.restart);
929 + return Exit.isFailure(exit) ? Effect.ignore(start) : start;
930 + },
931 + );
932 + });
933
934 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
935 const manager = yield* requireManager;
apps/server/src/cloud/config.ts
+6 -4
@@ -48,10 +48,10 @@ export function isAgentActivityPublishingEnabledValue(value: string | null): boo
48 * Mirrors the per-publish gate in AgentAwarenessRelay, so the descriptor
49 capability never advertises publishing that the publisher would skip.
50 */
51 -export const readAgentActivityPublishingActive = (
51 +export const readAgentActivityPublishingActive: (
52 secrets: ServerSecretStore.ServerSecretStore["Service"],
53 -): Effect.Effect<boolean> =>
54 - Effect.gen(function* () {
53 +) => Effect.Effect<boolean> = Effect.fn("config.readAgentActivityPublishingActive")(
54 + function* (secrets: ServerSecretStore.ServerSecretStore["Service"]) {
55 const readSecretString = (name: string) =>
56 secrets
57 .get(name)
@@ -74,7 +74,9 @@ export const readAgentActivityPublishingActive = (
74 environmentCredential !== null &&
75 environmentCredential !== ""
76 );
77 - }).pipe(Effect.orElseSucceed(() => false));
77 + },
78 + Effect.orElseSucceed(() => false),
79 +);
80
81 const readSecretString = (name: string) =>
82 ServerSecretStore.ServerSecretStore.pipe(
apps/server/src/cloud/selfUpdate.ts
+27 -28
@@ -141,34 +141,33 @@ export const withRunningThreadContinuation = Effect.fn(
141
142 return ServerSelfUpdate.of({
143 update,
144 - commitDesktopUpdate: (requestId) =>
145 - Effect.gen(function* () {
146 - const shouldContinue = yield* Ref.modify(desktopContinuationTokens, (tokens) => [
147 - HashSet.has(tokens, requestId),
148 - HashSet.remove(tokens, requestId),
149 - ]);
150 - let handoffAccepted = false;
151 - let continuationThreadIds: ReadonlyArray<ThreadId> = [];
152 - return yield* clearOnError(
153 - Effect.gen(function* () {
154 - continuationThreadIds = shouldContinue ? yield* input.prepare : [];
155 - return yield* input.selfUpdate.commitDesktopUpdate(requestId, () =>
156 - Effect.sync(() => {
157 - handoffAccepted = true;
158 - }),
159 - );
160 - }),
161 - () => continuationThreadIds,
162 - () => handoffAccepted,
163 - ).pipe(
164 - Effect.catchCause((cause) =>
165 - (shouldContinue && !handoffAccepted
166 - ? Ref.update(desktopContinuationTokens, HashSet.add(requestId))
167 - : Effect.void
168 - ).pipe(Effect.andThen(Effect.failCause(cause))),
169 - ),
170 - );
171 - }),
144 + commitDesktopUpdate: Effect.fn("selfUpdate.commitDesktopUpdate")(function* (requestId) {
145 + const shouldContinue = yield* Ref.modify(desktopContinuationTokens, (tokens) => [
146 + HashSet.has(tokens, requestId),
147 + HashSet.remove(tokens, requestId),
148 + ]);
149 + let handoffAccepted = false;
150 + let continuationThreadIds: ReadonlyArray<ThreadId> = [];
151 + return yield* clearOnError(
152 + Effect.gen(function* () {
153 + continuationThreadIds = shouldContinue ? yield* input.prepare : [];
154 + return yield* input.selfUpdate.commitDesktopUpdate(requestId, () =>
155 + Effect.sync(() => {
156 + handoffAccepted = true;
157 + }),
158 + );
159 + }),
160 + () => continuationThreadIds,
161 + () => handoffAccepted,
162 + ).pipe(
163 + Effect.catchCause((cause) =>
164 + (shouldContinue && !handoffAccepted
165 + ? Ref.update(desktopContinuationTokens, HashSet.add(requestId))
166 + : Effect.void
167 + ).pipe(Effect.andThen(Effect.failCause(cause))),
168 + ),
169 + );
170 + }),
171 });
172 });
173
apps/server/src/http.ts
+5 -4
@@ -291,10 +291,11 @@ export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
291 return redirectUrl.toString();
292 }
293
294 -const authenticateRawRouteWithScope = (
295 - scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,
296 -) =>
297 - Effect.gen(function* () {
294 +const authenticateRawRouteWithScope =
295 + /* Request instrumentation already owns the span; keep this helper in that context. */
296 + Effect.fnUntraced(function* (
297 + scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,
298 + ) {
299 const request = yield* HttpServerRequest.HttpServerRequest;
300 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
301 const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
apps/server/src/mcp/AcpMcpStdioBridge.ts
+103 -97
@@ -74,36 +74,37 @@ export function callAcpMcpTool(
74 let sessionId: string | null = null;
75 let protocolVersion: string | null = null;
76
77 - const send = (message: unknown): Effect.Effect<ReadonlyArray<unknown>, AcpMcpBridgeError> =>
78 - Effect.gen(function* () {
79 - const response = yield* Effect.tryPromise({
80 - try: () =>
81 - fetchImplementation(options.endpoint, {
82 - method: "POST",
83 - headers: {
84 - "content-type": "application/json",
85 - accept: "application/json, text/event-stream",
86 - authorization: options.authorization,
87 - ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
88 - ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
89 - },
90 - body: JSON.stringify(message),
91 - }),
92 - catch: bridgeError,
93 - });
94 - sessionId = response.headers.get("mcp-session-id") ?? sessionId;
95 - if (!response.ok) {
96 - yield* discardResponseBody(response);
97 - return yield* Effect.fail(
98 - new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
99 - );
100 - }
101 - const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));
102 - for (const payload of payloads) {
103 - protocolVersion = protocolVersionOf(payload) ?? protocolVersion;
104 - }
105 - return payloads;
77 + const send = Effect.fn("AcpMcpStdioBridge.send")(function* (
78 + message: unknown,
79 + ): Effect.fn.Return<ReadonlyArray<unknown>, AcpMcpBridgeError> {
80 + const response = yield* Effect.tryPromise({
81 + try: () =>
82 + fetchImplementation(options.endpoint, {
83 + method: "POST",
84 + headers: {
85 + "content-type": "application/json",
86 + accept: "application/json, text/event-stream",
87 + authorization: options.authorization,
88 + ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
89 + ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
90 + },
91 + body: JSON.stringify(message),
92 + }),
93 + catch: bridgeError,
94 });
95 + sessionId = response.headers.get("mcp-session-id") ?? sessionId;
96 + if (!response.ok) {
97 + yield* discardResponseBody(response);
98 + return yield* Effect.fail(
99 + new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
100 + );
101 + }
102 + const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));
103 + for (const payload of payloads) {
104 + protocolVersion = protocolVersionOf(payload) ?? protocolVersion;
105 + }
106 + return payloads;
107 + });
108
109 const initializeId = "t3-acp-cli-initialize";
110 const initialized = yield* send({
@@ -156,13 +157,14 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.
157 options.output.write(`${JSON.stringify(message)}\n`);
158 });
159
159 - const handleServerPayload = (payload: unknown): Effect.Effect<void> =>
160 - Effect.gen(function* () {
161 - for (const entry of Array.isArray(payload) ? payload : [payload]) {
162 - protocolVersion = protocolVersionOf(entry) ?? protocolVersion;
163 - yield* writeMessage(entry);
164 - }
165 - });
160 + const handleServerPayload = Effect.fn("AcpMcpStdioBridge.handleServerPayload")(function* (
161 + payload: unknown,
162 + ): Effect.fn.Return<void> {
163 + for (const entry of Array.isArray(payload) ? payload : [payload]) {
164 + protocolVersion = protocolVersionOf(entry) ?? protocolVersion;
165 + yield* writeMessage(entry);
166 + }
167 + });
168
169 const respondWithError = (
170 requestId: unknown,
@@ -175,8 +177,10 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.
177 error: { code, message },
178 });
179
178 - const forward = (line: string, envelope: JsonRpcEnvelope): Effect.Effect<void> =>
179 - Effect.gen(function* () {
180 + const forward: (line: string, envelope: JsonRpcEnvelope) => Effect.Effect<void> = Effect.fn(
181 + "AcpMcpStdioBridge.forward",
182 + )(
183 + function* (line: string, envelope: JsonRpcEnvelope) {
184 const response = yield* Effect.tryPromise({
185 try: () =>
186 fetchImplementation(options.endpoint, {
@@ -203,16 +207,19 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.
207 return yield* discardResponseBody(response);
208 }
209 yield* Stream.runForEach(responsePayloads(response, bridgeError), handleServerPayload);
206 - }).pipe(
207 - Effect.catchCause((cause) => {
208 - if (envelope.id === undefined) return Effect.void;
209 - const error = Cause.squash(cause);
210 - return respondWithError(
211 - envelope.id,
212 - `T3 Code MCP bridge request failed: ${error instanceof Error ? error.message : String(error)}`,
213 - );
214 - }),
215 - );
210 + },
211 + (effect, _line, envelope) =>
212 + effect.pipe(
213 + Effect.catchCause((cause) => {
214 + if (envelope.id === undefined) return Effect.void;
215 + const error = Cause.squash(cause);
216 + return respondWithError(
217 + envelope.id,
218 + `T3 Code MCP bridge request failed: ${error instanceof Error ? error.message : String(error)}`,
219 + );
220 + }),
221 + ),
222 + );
223
224 // Only session establishment is ordered; client responses to
225 // server-initiated SSE requests must bypass the barrier or they would
@@ -221,65 +228,64 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.
228 let sessionBarrier: Effect.Effect<void> = Effect.void;
229 let sessionBarrierPending = false;
230
224 - const launch = (task: Effect.Effect<void>): Effect.Effect<void> =>
225 - Effect.gen(function* () {
226 - const fiber = yield* Effect.forkChild(task);
231 + const launch = Effect.fn("AcpMcpStdioBridge.launch")(function* (
232 + task: Effect.Effect<void>,
233 + ): Effect.fn.Return<void> {
234 + const fiber = yield* Effect.forkChild(task);
235 + running.add(fiber);
236 + yield* Effect.forkChild(
237 + Fiber.await(fiber).pipe(
238 + Effect.andThen(
239 + Effect.sync(() => {
240 + running.delete(fiber);
241 + }),
242 + ),
243 + ),
244 + );
245 + });
246 +
247 + const dispatch = Effect.fn("AcpMcpStdioBridge.dispatch")(function* (
248 + line: string,
249 + ): Effect.fn.Return<void> {
250 + if (line.trim().length === 0) return;
251 + let parsed: unknown;
252 + try {
253 + parsed = JSON.parse(line);
254 + } catch {
255 + return yield* respondWithError(null, "Parse error", -32700);
256 + }
257 + const envelope = asEnvelope(parsed);
258 + if (envelope === null) return;
259 + const isResponse = envelope.id !== undefined && ("result" in envelope || "error" in envelope);
260 + const isSessionHandshake =
261 + envelope.method === "initialize" || envelope.method === "notifications/initialized";
262 + if (isResponse) {
263 + return yield* launch(forward(line, envelope));
264 + }
265 + if (isSessionHandshake) {
266 + const prior = sessionBarrier;
267 + const fiber = yield* Effect.forkChild(prior.pipe(Effect.andThen(forward(line, envelope))));
268 running.add(fiber);
269 + const barrier = Fiber.await(fiber).pipe(Effect.asVoid);
270 + sessionBarrier = barrier;
271 + sessionBarrierPending = true;
272 yield* Effect.forkChild(
273 Fiber.await(fiber).pipe(
274 Effect.andThen(
275 Effect.sync(() => {
276 running.delete(fiber);
277 + if (sessionBarrier === barrier) sessionBarrierPending = false;
278 }),
279 ),
280 ),
281 );
237 - });
238 -
239 - const dispatch = (line: string): Effect.Effect<void> =>
240 - Effect.gen(function* () {
241 - if (line.trim().length === 0) return;
242 - let parsed: unknown;
243 - try {
244 - parsed = JSON.parse(line);
245 - } catch {
246 - return yield* respondWithError(null, "Parse error", -32700);
247 - }
248 - const envelope = asEnvelope(parsed);
249 - if (envelope === null) return;
250 - const isResponse =
251 - envelope.id !== undefined && ("result" in envelope || "error" in envelope);
252 - const isSessionHandshake =
253 - envelope.method === "initialize" || envelope.method === "notifications/initialized";
254 - if (isResponse) {
255 - return yield* launch(forward(line, envelope));
256 - }
257 - if (isSessionHandshake) {
258 - const prior = sessionBarrier;
259 - const fiber = yield* Effect.forkChild(
260 - prior.pipe(Effect.andThen(forward(line, envelope))),
261 - );
262 - running.add(fiber);
263 - const barrier = Fiber.await(fiber).pipe(Effect.asVoid);
264 - sessionBarrier = barrier;
265 - sessionBarrierPending = true;
266 - yield* Effect.forkChild(
267 - Fiber.await(fiber).pipe(
268 - Effect.andThen(
269 - Effect.sync(() => {
270 - running.delete(fiber);
271 - if (sessionBarrier === barrier) sessionBarrierPending = false;
272 - }),
273 - ),
274 - ),
275 - );
276 - return;
277 - }
278 - const task = sessionBarrierPending
279 - ? sessionBarrier.pipe(Effect.andThen(forward(line, envelope)))
280 - : forward(line, envelope);
281 - return yield* launch(task);
282 - });
282 + return;
283 + }
284 + const task = sessionBarrierPending
285 + ? sessionBarrier.pipe(Effect.andThen(forward(line, envelope)))
286 + : forward(line, envelope);
287 + return yield* launch(task);
288 + });
289
290 const reader = NodeReadline.createInterface({ input: options.input });
291 yield* Stream.runForEach(Stream.fromAsyncIterable(reader, bridgeError), dispatch).pipe(
apps/server/src/mcp/McpHttpServer.ts
+133 -118
@@ -634,7 +634,11 @@ const imageToolFailure =
634 * `McpServer.toolkit` serializes every result as JSON text, which is the wrong
635 * shape for a screenshot: the model needs image content.
636 */
637 -const registerImageTool = <T extends Tool.Any, E, R>(
637 +const registerImageTool = Effect.fn("McpHttpServer.registerImageTool")(function* <
638 + T extends Tool.Any,
639 + E,
640 + R,
641 +>(
642 tool: T,
643 handle: (payload: Tool.Parameters<T>) => Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
644 provide: (
@@ -646,73 +650,72 @@ const registerImageTool = <T extends Tool.Any, E, R>(
650 >,
651 operation: string,
652 failureText: string | ((error: E) => string),
649 -) =>
650 - Effect.gen(function* () {
651 - const server = yield* McpServer.McpServer;
652 - yield* server.addTool({
653 - tool: new McpSchema.Tool({
654 - name: tool.name,
655 - description: Tool.getDescription(tool),
656 - inputSchema: Tool.getJsonSchema(tool),
657 - annotations: {
658 - ...Context.getOption(tool.annotations, Tool.Title).pipe(
659 - Option.map((title) => ({ title })),
660 - Option.getOrUndefined,
661 - ),
662 - readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
663 - destructiveHint: Context.get(tool.annotations, Tool.Destructive),
664 - idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
665 - openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
666 - },
653 +) {
654 + const server = yield* McpServer.McpServer;
655 + yield* server.addTool({
656 + tool: new McpSchema.Tool({
657 + name: tool.name,
658 + description: Tool.getDescription(tool),
659 + inputSchema: Tool.getJsonSchema(tool),
660 + annotations: {
661 + ...Context.getOption(tool.annotations, Tool.Title).pipe(
662 + Option.map((title) => ({ title })),
663 + Option.getOrUndefined,
664 + ),
665 + readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
666 + destructiveHint: Context.get(tool.annotations, Tool.Destructive),
667 + idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
668 + openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
669 + },
670 + }),
671 + annotations: tool.annotations,
672 + handle: (payload) =>
673 + Effect.withFiber((fiber) => {
674 + const invocation = Context.getUnsafe(
675 + fiber.context,
676 + McpInvocationContext.McpInvocationContext,
677 + );
678 + return provide(handle(payload as Tool.Parameters<T>)).pipe(
679 + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
680 + Effect.matchCauseEffect({
681 + onFailure: imageToolFailure(tool.name, operation, failureText),
682 + onSuccess: ({ encodedResult }) => {
683 + const { screenshot, ...rest } = encodedResult as ImageToolResult;
684 + const includeImage =
685 + (payload as { readonly includeImage?: boolean } | undefined)?.includeImage !==
686 + false;
687 + const metadata = {
688 + ...rest,
689 + screenshot: {
690 + mimeType: screenshot.mimeType,
691 + width: screenshot.width,
692 + height: screenshot.height,
693 + },
694 + };
695 + return Effect.succeed(
696 + new McpSchema.CallToolResult({
697 + isError: false,
698 + structuredContent: metadata,
699 + content: [
700 + { type: "text", text: JSON.stringify(metadata) },
701 + ...(includeImage
702 + ? [
703 + {
704 + type: "image" as const,
705 + data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
706 + mimeType: screenshot.mimeType,
707 + },
708 + ]
709 + : []),
710 + ],
711 + }),
712 + );
713 + },
714 + }),
715 + );
716 }),
668 - annotations: tool.annotations,
669 - handle: (payload) =>
670 - Effect.withFiber((fiber) => {
671 - const invocation = Context.getUnsafe(
672 - fiber.context,
673 - McpInvocationContext.McpInvocationContext,
674 - );
675 - return provide(handle(payload as Tool.Parameters<T>)).pipe(
676 - Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
677 - Effect.matchCauseEffect({
678 - onFailure: imageToolFailure(tool.name, operation, failureText),
679 - onSuccess: ({ encodedResult }) => {
680 - const { screenshot, ...rest } = encodedResult as ImageToolResult;
681 - const includeImage =
682 - (payload as { readonly includeImage?: boolean } | undefined)?.includeImage !==
683 - false;
684 - const metadata = {
685 - ...rest,
686 - screenshot: {
687 - mimeType: screenshot.mimeType,
688 - width: screenshot.width,
689 - height: screenshot.height,
690 - },
691 - };
692 - return Effect.succeed(
693 - new McpSchema.CallToolResult({
694 - isError: false,
695 - structuredContent: metadata,
696 - content: [
697 - { type: "text", text: JSON.stringify(metadata) },
698 - ...(includeImage
699 - ? [
700 - {
701 - type: "image" as const,
702 - data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
703 - mimeType: screenshot.mimeType,
704 - },
705 - ]
706 - : []),
707 - ],
708 - }),
709 - );
710 - },
711 - }),
712 - );
713 - }),
714 - });
717 });
718 +});
719
720 const registerDeviceScreenshot = Effect.fn("McpHttpServer.registerDeviceScreenshot")(function* () {
721 const devices = yield* DeviceService.DeviceService;
@@ -820,8 +823,9 @@ const handoffTargetIds = (
823 * agent chose, and the provider, model, and modes of each thread that received
824 * the work. Ids, prompts, and free text are never recorded.
825 */
823 -const withToolAnalytics = <A, E, R>(registration: Effect.Effect<A, E, R>) =>
824 - Effect.gen(function* () {
826 +const withToolAnalytics =
827 + /* Request instrumentation already owns the span; keep this helper in that context. */
828 + Effect.fnUntraced(function* <A, E, R>(registration: Effect.Effect<A, E, R>) {
829 const server = yield* McpServer.McpServer;
830 const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);
831 if (Option.isNone(analytics)) return yield* registration;
@@ -834,8 +838,9 @@ const withToolAnalytics = <A, E, R>(registration: Effect.Effect<A, E, R>) =>
838 .getThreadShell(ThreadId.make(threadId))
839 .pipe(Effect.orElseSucceed(() => null));
840 // Delegation depth: parents walked from the caller, capped.
837 - const depthOf = (thread: AgentThread) =>
838 - Effect.gen(function* () {
841 + const depthOf =
842 + /* Request instrumentation already owns the span; keep this helper in that context. */
843 + Effect.fnUntraced(function* (thread: AgentThread) {
844 let depth = 0;
845 let parentId =
846 thread.lineage.relationshipToParent === "subagent" ? thread.lineage.parentThreadId : null;
@@ -868,59 +873,69 @@ const withToolAnalytics = <A, E, R>(registration: Effect.Effect<A, E, R>) =>
873 }),
874 Effect.orElseSucceed(() => false),
875 );
871 - const record = (
872 - tool: string,
873 - args: unknown,
874 - result: McpSchema.CallToolResult | undefined,
875 - durationMs: number,
876 - ) =>
877 - Effect.gen(function* () {
878 - // Client credentials (no calling thread) report an unknown caller.
879 - const invocation = Option.getOrUndefined(
880 - yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext),
881 - )?.thread;
882 - const providers = Option.isSome(registry) ? yield* registry.value.getProviders : [];
883 - // Only handoff tools pay for thread lookups; the rest report the
884 - // caller's provider from the credential.
885 - const handoff = HANDOFF_TOOLS.has(tool);
886 - const caller =
887 - handoff && invocation !== undefined
888 - ? ((yield* shellOf(invocation.threadId)) ?? undefined)
889 - : undefined;
890 - const targetIds = handoff
891 - ? [...new Set(handoffTargetIds(tool, args, result))].filter(
892 - (threadId) => threadId !== invocation?.threadId,
893 - )
894 - : [];
895 - const targets = yield* Effect.forEach(targetIds, shellOf);
896 - for (const properties of agentToolProperties({
897 - tool,
898 - providers,
899 - caller,
900 - ...(invocation === undefined
901 - ? {}
902 - : { callerProviderInstanceId: invocation.providerInstanceId }),
903 - ...(caller === undefined || invocation === undefined
904 - ? {}
905 - : {
906 - callerDepth: yield* depthOf(caller),
907 - callerScheduledRun: yield* scheduledRunOf(invocation.threadId, caller.activeRunId),
908 - }),
909 - targets: targets.filter((thread) => thread !== null),
910 - outcome: toolOutcome(result),
911 - ...(handoff ? { settings: handoffSettings(tool, args, result?.structuredContent) } : {}),
912 - durationMs,
913 - })) {
914 - yield* analytics.value.record("mcp.tool.invoked", properties);
915 - }
916 - }).pipe(Effect.ignoreCause);
876 + const record =
877 + /* Request instrumentation already owns the span; keep this helper in that context. */
878 + Effect.fnUntraced(
879 + function* (
880 + tool: string,
881 + args: unknown,
882 + result: McpSchema.CallToolResult | undefined,
883 + durationMs: number,
884 + ) {
885 + // Client credentials (no calling thread) report an unknown caller.
886 + const invocation = Option.getOrUndefined(
887 + yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext),
888 + )?.thread;
889 + const providers = Option.isSome(registry) ? yield* registry.value.getProviders : [];
890 + // Only handoff tools pay for thread lookups; the rest report the
891 + // caller's provider from the credential.
892 + const handoff = HANDOFF_TOOLS.has(tool);
893 + const caller =
894 + handoff && invocation !== undefined
895 + ? ((yield* shellOf(invocation.threadId)) ?? undefined)
896 + : undefined;
897 + const targetIds = handoff
898 + ? [...new Set(handoffTargetIds(tool, args, result))].filter(
899 + (threadId) => threadId !== invocation?.threadId,
900 + )
901 + : [];
902 + const targets = yield* Effect.forEach(targetIds, shellOf);
903 + for (const properties of agentToolProperties({
904 + tool,
905 + providers,
906 + caller,
907 + ...(invocation === undefined
908 + ? {}
909 + : { callerProviderInstanceId: invocation.providerInstanceId }),
910 + ...(caller === undefined || invocation === undefined
911 + ? {}
912 + : {
913 + callerDepth: yield* depthOf(caller),
914 + callerScheduledRun: yield* scheduledRunOf(
915 + invocation.threadId,
916 + caller.activeRunId,
917 + ),
918 + }),
919 + targets: targets.filter((thread) => thread !== null),
920 + outcome: toolOutcome(result),
921 + ...(handoff
922 + ? { settings: handoffSettings(tool, args, result?.structuredContent) }
923 + : {}),
924 + durationMs,
925 + })) {
926 + yield* analytics.value.record("mcp.tool.invoked", properties);
927 + }
928 + },
929 + (effect, _tool, _args, _result, _durationMs) => effect.pipe(Effect.ignoreCause),
930 + );
931 const recordingServer = McpServer.McpServer.of({
932 ...server,
933 addTool: (options) =>
934 server.addTool({
935 ...options,
922 - handle: (payload) =>
923 - Effect.gen(function* () {
936 + handle:
937 + /* Request instrumentation already owns the span; keep this helper in that context. */
938 + Effect.fnUntraced(function* (payload) {
939 const startedAt = yield* Clock.currentTimeMillis;
940 return yield* options.handle(payload).pipe(
941 Effect.onExit((exit) => {
apps/server/src/mcp/OrchestratorMcpService.ts
+1183 -1197
@@ -1020,35 +1020,38 @@ const make = Effect.gen(function* () {
1020 )
1021 .pipe(Effect.mapError(threadManagementFailure));
1022
1023 - const loadCaller = (scope: McpInvocationScope) =>
1024 - Effect.gen(function* () {
1025 - yield* requireCapability(scope);
1026 - if (scope.thread === undefined) {
1027 - return {
1028 - parent: undefined,
1029 - limits: {
1030 - runtimeMode: clientRuntimeModeCeiling(scope.client),
1031 - interactionMode: "default",
1032 - } satisfies { runtimeMode: RuntimeMode; interactionMode: ProviderInteractionMode },
1033 - } as const;
1034 - }
1035 - const parent = yield* loadProjection(scope.thread.threadId);
1023 + const loadCaller = Effect.fn("OrchestratorMcpService.loadCaller")(function* (
1024 + scope: McpInvocationScope,
1025 + ) {
1026 + yield* requireCapability(scope);
1027 + if (scope.thread === undefined) {
1028 return {
1037 - parent,
1029 + parent: undefined,
1030 limits: {
1039 - runtimeMode: parent.thread.runtimeMode,
1040 - interactionMode: parent.thread.interactionMode,
1041 - },
1031 + runtimeMode: clientRuntimeModeCeiling(scope.client),
1032 + interactionMode: "default",
1033 + } satisfies { runtimeMode: RuntimeMode; interactionMode: ProviderInteractionMode },
1034 } as const;
1043 - });
1035 + }
1036 + const parent = yield* loadProjection(scope.thread.threadId);
1037 + return {
1038 + parent,
1039 + limits: {
1040 + runtimeMode: parent.thread.runtimeMode,
1041 + interactionMode: parent.thread.interactionMode,
1042 + },
1043 + } as const;
1044 + });
1045
1045 - const loadThreadCaller = (scope: McpInvocationScope, operation: string) =>
1046 - Effect.gen(function* () {
1047 - yield* requireCapability(scope);
1048 - const threadScope = yield* requireThreadScope(scope, operation);
1049 - const parent = yield* loadProjection(threadScope.thread.threadId);
1050 - return { scope: threadScope, parent } as const;
1051 - });
1046 + const loadThreadCaller = Effect.fn("OrchestratorMcpService.loadThreadCaller")(function* (
1047 + scope: McpInvocationScope,
1048 + operation: string,
1049 + ) {
1050 + yield* requireCapability(scope);
1051 + const threadScope = yield* requireThreadScope(scope, operation);
1052 + const parent = yield* loadProjection(threadScope.thread.threadId);
1053 + return { scope: threadScope, parent } as const;
1054 + });
1055
1056 const resolveProjectTarget = (
1057 parent: Pick<OrchestrationV2ThreadProjection, "thread"> | undefined,
@@ -1065,26 +1068,29 @@ const make = Effect.gen(function* () {
1068 ),
1069 );
1070
1068 - const loadTargetThread = (threadId: ThreadId) =>
1069 - Effect.gen(function* () {
1070 - const shell = yield* threadManagement
1071 - .getThreadShell(threadId)
1072 - .pipe(Effect.mapError(threadManagementFailure));
1073 - if (shell === null || shell.deletedAt !== null) {
1074 - return yield* failure("thread_not_found", `Thread ${threadId} was not found.`);
1075 - }
1076 - return yield* loadProjectThread(shell.projectId, threadId);
1077 - });
1078 -
1079 - const loadScopedThread = (scope: McpInvocationScope, threadId: ThreadId) =>
1080 - Effect.gen(function* () {
1081 - const caller = yield* loadCaller(scope);
1082 - const target =
1083 - caller.parent !== undefined && threadId === caller.parent.thread.id
1084 - ? caller.parent
1085 - : yield* loadTargetThread(threadId);
1086 - return { ...caller, target } as const;
1087 - });
1071 + const loadTargetThread = Effect.fn("OrchestratorMcpService.loadTargetThread")(function* (
1072 + threadId: ThreadId,
1073 + ) {
1074 + const shell = yield* threadManagement
1075 + .getThreadShell(threadId)
1076 + .pipe(Effect.mapError(threadManagementFailure));
1077 + if (shell === null || shell.deletedAt !== null) {
1078 + return yield* failure("thread_not_found", `Thread ${threadId} was not found.`);
1079 + }
1080 + return yield* loadProjectThread(shell.projectId, threadId);
1081 + });
1082 +
1083 + const loadScopedThread = Effect.fn("OrchestratorMcpService.loadScopedThread")(function* (
1084 + scope: McpInvocationScope,
1085 + threadId: ThreadId,
1086 + ) {
1087 + const caller = yield* loadCaller(scope);
1088 + const target =
1089 + caller.parent !== undefined && threadId === caller.parent.thread.id
1090 + ? caller.parent
1091 + : yield* loadTargetThread(threadId);
1092 + return { ...caller, target } as const;
1093 + });
1094
1095 /**
1096 * A thread caller writes to another thread only while its own run is live,
@@ -1135,24 +1141,26 @@ const make = Effect.gen(function* () {
1141 : Effect.void;
1142 };
1143
1138 - const loadReadableThread = (scope: McpInvocationScope, threadId: ThreadId) =>
1139 - Effect.gen(function* () {
1140 - const { parent } = yield* loadCaller(scope);
1141 - const shell = yield* threadManagement
1142 - .getThreadShell(threadId)
1143 - .pipe(Effect.mapError(threadManagementFailure));
1144 - if (shell === null || shell.deletedAt !== null) {
1145 - return yield* failure("thread_not_found", `Thread ${threadId} is no longer available.`);
1146 - }
1147 - const target = yield* threadManagement
1148 - .getProjectThreadRecords({ projectId: shell.projectId, threadId }, [
1149 - "runs",
1150 - "runtimeRequests",
1151 - "contextTransfers",
1152 - ])
1153 - .pipe(Effect.mapError(threadManagementFailure));
1154 - return { parent, target, shell } as const;
1155 - });
1144 + const loadReadableThread = Effect.fn("OrchestratorMcpService.loadReadableThread")(function* (
1145 + scope: McpInvocationScope,
1146 + threadId: ThreadId,
1147 + ) {
1148 + const { parent } = yield* loadCaller(scope);
1149 + const shell = yield* threadManagement
1150 + .getThreadShell(threadId)
1151 + .pipe(Effect.mapError(threadManagementFailure));
1152 + if (shell === null || shell.deletedAt !== null) {
1153 + return yield* failure("thread_not_found", `Thread ${threadId} is no longer available.`);
1154 + }
1155 + const target = yield* threadManagement
1156 + .getProjectThreadRecords({ projectId: shell.projectId, threadId }, [
1157 + "runs",
1158 + "runtimeRequests",
1159 + "contextTransfers",
1160 + ])
1161 + .pipe(Effect.mapError(threadManagementFailure));
1162 + return { parent, target, shell } as const;
1163 + });
1164
1165 const loadProviders = providerRegistry.getProviders;
1166
@@ -1196,7 +1204,7 @@ const make = Effect.gen(function* () {
1204 );
1205 };
1206
1199 - const resolveTarget = (input: {
1207 + const resolveTarget = Effect.fn("OrchestratorMcpService.resolveTarget")(function* (input: {
1208 readonly parent: Pick<OrchestrationV2ThreadProjection, "thread">;
1209 readonly target: OrchestratorMcpTarget | undefined;
1210 readonly providers: ReadonlyArray<ServerProvider>;
@@ -1208,327 +1216,317 @@ const make = Effect.gen(function* () {
1216 * one checked for a receipt.
1217 */
1218 readonly skipProjectEnablementFilter?: boolean;
1211 - }): Effect.Effect<ResolvedTarget, OrchestratorMcpFailure> =>
1212 - Effect.gen(function* () {
1213 - const requestedInstanceId = input.target?.providerInstanceId;
1214 - const requestedDriver = input.target?.driverKind;
1215 - const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds();
1216 - let instanceId = requestedInstanceId;
1217 -
1218 - if (instanceId === undefined && requestedDriver !== undefined) {
1219 - const candidates = input.providers.filter(
1220 - (provider) =>
1221 - provider.driver === requestedDriver &&
1222 - orchestrationCapableInstanceIds.has(provider.instanceId),
1223 - );
1224 - if (candidates.length === 0) {
1225 - return yield* failure(
1226 - "provider_unavailable",
1227 - `No V2 provider adapter is registered for driver ${requestedDriver}.`,
1228 - );
1229 - }
1230 - const healthyCandidates = candidates.filter(
1231 - (candidate) => providerConstraints(candidate, true).length === 0,
1232 - );
1233 - const inheritedCandidate = healthyCandidates.find(
1234 - (candidate) => candidate.instanceId === input.parent.thread.modelSelection.instanceId,
1235 - );
1236 - const orderedCandidates = [
1237 - ...(inheritedCandidate === undefined ? [] : [inheritedCandidate]),
1238 - ...healthyCandidates.filter((candidate) => candidate !== inheritedCandidate),
1239 - ];
1240 - for (const candidate of orderedCandidates) {
1241 - const enabledForProject =
1242 - input.skipProjectEnablementFilter === true ||
1243 - (yield* threadManagement.isProviderInstanceEnabledForProject({
1244 - projectId: input.parent.thread.projectId,
1245 - instanceId: candidate.instanceId,
1246 - }));
1247 - if (enabledForProject) {
1248 - instanceId = candidate.instanceId;
1249 - break;
1250 - }
1251 - }
1252 - if (instanceId === undefined) {
1253 - return yield* failure(
1254 - "provider_unavailable",
1255 - healthyCandidates.length === 0
1256 - ? `No available V2 provider instance for driver ${requestedDriver}.`
1257 - : `No instance of driver ${requestedDriver} is enabled for this project.`,
1258 - );
1259 - }
1260 - }
1261 - instanceId ??= input.parent.thread.modelSelection.instanceId;
1262 -
1263 - const provider = input.providers.find((candidate) => candidate.instanceId === instanceId);
1264 - if (provider === undefined) {
1219 + }): Effect.fn.Return<ResolvedTarget, OrchestratorMcpFailure> {
1220 + const requestedInstanceId = input.target?.providerInstanceId;
1221 + const requestedDriver = input.target?.driverKind;
1222 + const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds();
1223 + let instanceId = requestedInstanceId;
1224 +
1225 + if (instanceId === undefined && requestedDriver !== undefined) {
1226 + const candidates = input.providers.filter(
1227 + (provider) =>
1228 + provider.driver === requestedDriver &&
1229 + orchestrationCapableInstanceIds.has(provider.instanceId),
1230 + );
1231 + if (candidates.length === 0) {
1232 return yield* failure(
1233 "provider_unavailable",
1267 - `Provider instance ${instanceId} is not registered.`,
1268 - );
1269 - }
1270 - if (requestedDriver !== undefined && provider.driver !== requestedDriver) {
1271 - return yield* failure(
1272 - "invalid_request",
1273 - `Provider instance ${instanceId} uses driver ${provider.driver}, not ${requestedDriver}.`,
1234 + `No V2 provider adapter is registered for driver ${requestedDriver}.`,
1235 );
1236 }
1276 - const constraints = providerConstraints(
1277 - provider,
1278 - orchestrationCapableInstanceIds.has(provider.instanceId),
1237 + const healthyCandidates = candidates.filter(
1238 + (candidate) => providerConstraints(candidate, true).length === 0,
1239 );
1280 - if (constraints.length > 0) {
1240 + const inheritedCandidate = healthyCandidates.find(
1241 + (candidate) => candidate.instanceId === input.parent.thread.modelSelection.instanceId,
1242 + );
1243 + const orderedCandidates = [
1244 + ...(inheritedCandidate === undefined ? [] : [inheritedCandidate]),
1245 + ...healthyCandidates.filter((candidate) => candidate !== inheritedCandidate),
1246 + ];
1247 + for (const candidate of orderedCandidates) {
1248 + const enabledForProject =
1249 + input.skipProjectEnablementFilter === true ||
1250 + (yield* threadManagement.isProviderInstanceEnabledForProject({
1251 + projectId: input.parent.thread.projectId,
1252 + instanceId: candidate.instanceId,
1253 + }));
1254 + if (enabledForProject) {
1255 + instanceId = candidate.instanceId;
1256 + break;
1257 + }
1258 + }
1259 + if (instanceId === undefined) {
1260 return yield* failure(
1261 "provider_unavailable",
1283 - `Provider ${instanceId} cannot run a child task: ${constraints.join(" ")}`,
1262 + healthyCandidates.length === 0
1263 + ? `No available V2 provider instance for driver ${requestedDriver}.`
1264 + : `No instance of driver ${requestedDriver} is enabled for this project.`,
1265 );
1266 }
1267 + }
1268 + instanceId ??= input.parent.thread.modelSelection.instanceId;
1269
1287 - const inheritedSelection = input.parent.thread.modelSelection;
1288 - const requestedModel = input.target?.model;
1289 - const model =
1290 - requestedModel ??
1291 - (instanceId === inheritedSelection.instanceId
1292 - ? inheritedSelection.model
1293 - : provider?.models[0]?.slug);
1294 - if (model === undefined) {
1295 - return yield* failure(
1296 - "model_unavailable",
1297 - `Provider ${instanceId} has no model available for inheritance.`,
1298 - );
1299 - }
1300 - if (
1301 - requestedModel !== undefined &&
1302 - provider !== undefined &&
1303 - provider.models.length > 0 &&
1304 - !provider.models.some((candidate) => candidate.slug === requestedModel)
1305 - ) {
1270 + const provider = input.providers.find((candidate) => candidate.instanceId === instanceId);
1271 + if (provider === undefined) {
1272 + return yield* failure(
1273 + "provider_unavailable",
1274 + `Provider instance ${instanceId} is not registered.`,
1275 + );
1276 + }
1277 + if (requestedDriver !== undefined && provider.driver !== requestedDriver) {
1278 + return yield* failure(
1279 + "invalid_request",
1280 + `Provider instance ${instanceId} uses driver ${provider.driver}, not ${requestedDriver}.`,
1281 + );
1282 + }
1283 + const constraints = providerConstraints(
1284 + provider,
1285 + orchestrationCapableInstanceIds.has(provider.instanceId),
1286 + );
1287 + if (constraints.length > 0) {
1288 + return yield* failure(
1289 + "provider_unavailable",
1290 + `Provider ${instanceId} cannot run a child task: ${constraints.join(" ")}`,
1291 + );
1292 + }
1293 +
1294 + const inheritedSelection = input.parent.thread.modelSelection;
1295 + const requestedModel = input.target?.model;
1296 + const model =
1297 + requestedModel ??
1298 + (instanceId === inheritedSelection.instanceId
1299 + ? inheritedSelection.model
1300 + : provider?.models[0]?.slug);
1301 + if (model === undefined) {
1302 + return yield* failure(
1303 + "model_unavailable",
1304 + `Provider ${instanceId} has no model available for inheritance.`,
1305 + );
1306 + }
1307 + if (
1308 + requestedModel !== undefined &&
1309 + provider !== undefined &&
1310 + provider.models.length > 0 &&
1311 + !provider.models.some((candidate) => candidate.slug === requestedModel)
1312 + ) {
1313 + return yield* failure(
1314 + "model_unavailable",
1315 + `Model ${requestedModel} is not advertised by provider ${instanceId}.`,
1316 + );
1317 + }
1318 +
1319 + const requestedOptions = input.target?.options;
1320 + if (requestedOptions !== undefined) {
1321 + const descriptors = provider.models.find((candidate) => candidate.slug === model)
1322 + ?.capabilities?.optionDescriptors;
1323 + const invalid = invalidOptionSelections(requestedOptions, descriptors);
1324 + if (invalid.length > 0) {
1325 return yield* failure(
1307 - "model_unavailable",
1308 - `Model ${requestedModel} is not advertised by provider ${instanceId}.`,
1326 + "invalid_request",
1327 + `Model ${model} on provider ${instanceId} rejected options: ${invalid.join(" ")}`,
1328 );
1329 }
1330 + }
1331
1312 - const requestedOptions = input.target?.options;
1313 - if (requestedOptions !== undefined) {
1314 - const descriptors = provider.models.find((candidate) => candidate.slug === model)
1315 - ?.capabilities?.optionDescriptors;
1316 - const invalid = invalidOptionSelections(requestedOptions, descriptors);
1317 - if (invalid.length > 0) {
1318 - return yield* failure(
1319 - "invalid_request",
1320 - `Model ${model} on provider ${instanceId} rejected options: ${invalid.join(" ")}`,
1321 - );
1322 - }
1323 - }
1324 -
1325 - return {
1326 - modelSelection:
1327 - instanceId === inheritedSelection.instanceId &&
1328 - model === inheritedSelection.model &&
1329 - requestedOptions === undefined
1330 - ? inheritedSelection
1331 - : requestedOptions === undefined
1332 - ? { instanceId, model }
1333 - : { instanceId, model, options: requestedOptions },
1334 - supportedRuntimeModes: provider.supportedRuntimeModes,
1335 - };
1336 - });
1332 + return {
1333 + modelSelection:
1334 + instanceId === inheritedSelection.instanceId &&
1335 + model === inheritedSelection.model &&
1336 + requestedOptions === undefined
1337 + ? inheritedSelection
1338 + : requestedOptions === undefined
1339 + ? { instanceId, model }
1340 + : { instanceId, model, options: requestedOptions },
1341 + supportedRuntimeModes: provider.supportedRuntimeModes,
1342 + };
1343 + });
1344
1345 const requestKey = (clientRequestId: string | undefined): Effect.Effect<string> =>
1346 clientRequestId === undefined
1347 ? crypto.randomUUIDv4().pipe(Effect.orDie)
1348 : Effect.succeed(clientRequestId);
1349
1343 - const readTask = (
1350 + const readTask = Effect.fn("OrchestratorMcpService.readTask")(function* (
1351 scope: McpThreadInvocationScope,
1352 taskId: NodeId,
1353 waitTimedOut = false,
1354 acknowledgeTerminal = false,
1355 acknowledgementOperation = "task-status-acknowledge",
1349 - ): Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> =>
1350 - Effect.gen(function* () {
1351 - yield* requireCapability(scope);
1352 - const parentProjection = yield* loadProjection(scope.thread.threadId);
1353 - const task = parentProjection.subagents.find(
1354 - (candidate) =>
1355 - candidate.id === taskId &&
1356 - candidate.origin === "app_owned" &&
1357 - candidate.threadId === scope.thread.threadId,
1356 + ): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {
1357 + yield* requireCapability(scope);
1358 + const parentProjection = yield* loadProjection(scope.thread.threadId);
1359 + const task = parentProjection.subagents.find(
1360 + (candidate) =>
1361 + candidate.id === taskId &&
1362 + candidate.origin === "app_owned" &&
1363 + candidate.threadId === scope.thread.threadId,
1364 + );
1365 + if (task === undefined || task.childThreadId === null) {
1366 + return yield* failure(
1367 + "task_not_found",
1368 + `Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`,
1369 );
1359 - if (task === undefined || task.childThreadId === null) {
1360 - return yield* failure(
1361 - "task_not_found",
1362 - `Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`,
1363 - );
1364 - }
1365 - const childControls = yield* threadManagement
1366 - .getThreadRecords(
1367 - task.childThreadId,
1368 - [
1369 - "runs",
1370 - "messages",
1371 - "contextTransfers",
1372 - "subagents",
1373 - "providerThreads",
1374 - "runtimeRequests",
1375 - ],
1376 - { messageRoles: ["user"] },
1377 - )
1378 - .pipe(Effect.mapError(threadManagementFailure));
1379 - const childRun = delegatedTaskRun(childControls, task);
1380 - const terminalRun = latestTerminalResultRun(childControls, childRun);
1381 - const progress = delegatedTaskProgress(childControls);
1382 - const taskResultRun =
1383 - childRun?.delegatedTaskId === task.id
1384 - ? childControls.runs
1385 - .filter((run) => run.delegatedTaskId === task.id)
1386 - .toSorted((a, b) => b.ordinal - a.ordinal)[0]
1387 - : progress.resultRun;
1388 - const taskWorkState =
1389 - childRun?.delegatedTaskId === task.id
1390 - ? isTerminalTaskStatus(taskStatusForRun(taskResultRun))
1391 - ? "result_available"
1392 - : "working"
1393 - : progress.state;
1394 - const resultRunIds = [
1395 - ...new Set(
1396 - [taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined),
1370 + }
1371 + const childControls = yield* threadManagement
1372 + .getThreadRecords(
1373 + task.childThreadId,
1374 + ["runs", "messages", "contextTransfers", "subagents", "providerThreads", "runtimeRequests"],
1375 + { messageRoles: ["user"] },
1376 + )
1377 + .pipe(Effect.mapError(threadManagementFailure));
1378 + const childRun = delegatedTaskRun(childControls, task);
1379 + const terminalRun = latestTerminalResultRun(childControls, childRun);
1380 + const progress = delegatedTaskProgress(childControls);
1381 + const taskResultRun =
1382 + childRun?.delegatedTaskId === task.id
1383 + ? childControls.runs
1384 + .filter((run) => run.delegatedTaskId === task.id)
1385 + .toSorted((a, b) => b.ordinal - a.ordinal)[0]
1386 + : progress.resultRun;
1387 + const taskWorkState =
1388 + childRun?.delegatedTaskId === task.id
1389 + ? isTerminalTaskStatus(taskStatusForRun(taskResultRun))
1390 + ? "result_available"
1391 + : "working"
1392 + : progress.state;
1393 + const resultRunIds = [
1394 + ...new Set(
1395 + [taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined),
1396 + ),
1397 + ];
1398 + const resultRecords = yield* threadManagement
1399 + .getThreadRecords(task.childThreadId, ["messages", "turnItems"], {
1400 + messageRoles: ["assistant"],
1401 + messageRunIds: resultRunIds,
1402 + turnItemRunIds: resultRunIds,
1403 + turnItemTypes: ["assistant_message", "error"],
1404 + })
1405 + .pipe(Effect.mapError(threadManagementFailure));
1406 + const childProjection = {
1407 + ...childControls,
1408 + messages: [...childControls.messages, ...resultRecords.messages],
1409 + turnItems: resultRecords.turnItems,
1410 + };
1411 + const heldForRestart =
1412 + task.result === null &&
1413 + taskWorkState === "result_available" &&
1414 + (yield* threadManagement
1415 + .delegatedTaskResultPending(task.childThreadId, childRun?.delegatedTaskId)
1416 + .pipe(Effect.mapError(threadManagementFailure)));
1417 + const workState =
1418 + task.result !== null ? "result_available" : heldForRestart ? "working" : taskWorkState;
1419 + const status =
1420 + task.result !== null
1421 + ? taskStatusForRun(
1422 + task.status === "completed" ||
1423 + task.status === "failed" ||
1424 + task.status === "cancelled" ||
1425 + task.status === "interrupted"
1426 + ? { status: task.status }
1427 + : childRun,
1428 + )
1429 + : workState === "result_available"
1430 + ? taskStatusForRun(taskResultRun ?? childRun)
1431 + : taskStatusForRun(taskResultRun ?? childRun) === "queued"
1432 + ? "queued"
1433 + : "running";
1434 + const derivedResult =
1435 + task.result !== null
1436 + ? task.result
1437 + : taskResultRun !== undefined && isTerminalTaskStatus(status)
1438 + ? subagentResultForRun(childProjection, taskResultRun).text
1439 + : null;
1440 + const resultTransfers = parentProjection.contextTransfers.filter(
1441 + (transfer) =>
1442 + transfer.type === "subagent_result" &&
1443 + transfer.sourceThreadId === task.childThreadId &&
1444 + transfer.targetThreadId === scope.thread.threadId,
1445 + );
1446 + const resultTransferForRun = (run: OrchestrationV2Run | undefined) =>
1447 + !canExposeTaskRunResult(run)
1448 + ? null
1449 + : (resultTransfers.find((transfer) => transfer.sourcePoint.runId === run.id) ??
1450 + (run.id === childRun?.id
1451 + ? resultTransfers.find((transfer) => transfer.sourcePoint.runId === undefined)
1452 + : undefined) ??
1453 + null);
1454 + const resultTransfer = taskResultTransfer(parentProjection, childProjection, task) ?? null;
1455 + const terminalStatus = terminalRun === undefined ? null : taskStatusForRun(terminalRun);
1456 + const latestTerminalSummary = canExposeTaskRunResult(terminalRun)
1457 + ? terminalRun.id === childRun?.id
1458 + ? derivedResult
1459 + : subagentResultForRun(childProjection, terminalRun).text
1460 + : null;
1461 + const resultContextTransferId = resultTransfer?.id ?? null;
1462 + const latestTerminalResultContextTransferId = resultTransferForRun(terminalRun)?.id ?? null;
1463 + const response = {
1464 + taskId: task.id,
1465 + childThreadId: task.childThreadId,
1466 + childRunId: childRun?.id ?? null,
1467 + childNodeId: task.id,
1468 + status,
1469 + workState,
1470 + hasPendingChildRuns: hasPendingChildRuns(childProjection, childRun),
1471 + providerInstanceId: task.providerInstanceId,
1472 + model: task.model,
1473 + summary: derivedResult,
1474 + resultContextTransferId,
1475 + latestTerminalRunId: terminalRun?.id ?? null,
1476 + latestTerminalStatus:
1477 + terminalStatus !== null && isTerminalTaskStatus(terminalStatus) ? terminalStatus : null,
1478 + latestTerminalSummary: latestTerminalSummary === derivedResult ? null : latestTerminalSummary,
1479 + latestTerminalResultContextTransferId:
1480 + latestTerminalResultContextTransferId === resultContextTransferId
1481 + ? null
1482 + : latestTerminalResultContextTransferId,
1483 + hasPendingQuestion:
1484 + !isTerminalTaskStatus(status) &&
1485 + childControls.runtimeRequests.some(
1486 + (request) =>
1487 + request.kind === "user_input" &&
1488 + request.status === "pending" &&
1489 + request.responseCapability.type === "live",
1490 ),
1398 - ];
1399 - const resultRecords = yield* threadManagement
1400 - .getThreadRecords(task.childThreadId, ["messages", "turnItems"], {
1401 - messageRoles: ["assistant"],
1402 - messageRunIds: resultRunIds,
1403 - turnItemRunIds: resultRunIds,
1404 - turnItemTypes: ["assistant_message", "error"],
1491 + waitTimedOut,
1492 + } satisfies OrchestratorMcpDelegateTaskResult;
1493 + if (
1494 + acknowledgeTerminal &&
1495 + isTerminalTaskStatus(status) &&
1496 + task.completionDelivery?.state !== "acknowledged" &&
1497 + task.completionDelivery?.state !== "disposed"
1498 + ) {
1499 + const observingRun = ThreadManagementService.latestActiveRun(parentProjection);
1500 + const acknowledgementRequestKey = yield* requestKey(undefined);
1501 + yield* threadManagement
1502 + .dispatch({
1503 + type: "delegated_task.completion-delivery.acknowledge",
1504 + commandId: stableCommandId({
1505 + scope,
1506 + requestKey: acknowledgementRequestKey,
1507 + operation: acknowledgementOperation,
1508 + }),
1509 + parentThreadId: scope.thread.threadId,
1510 + taskId,
1511 + observedByRunId:
1512 + observingRun?.providerInstanceId === scope.thread.providerInstanceId
1513 + ? observingRun.id
1514 + : null,
1515 })
1406 - .pipe(Effect.mapError(threadManagementFailure));
1407 - const childProjection = {
1408 - ...childControls,
1409 - messages: [...childControls.messages, ...resultRecords.messages],
1410 - turnItems: resultRecords.turnItems,
1411 - };
1412 - const heldForRestart =
1413 - task.result === null &&
1414 - taskWorkState === "result_available" &&
1415 - (yield* threadManagement
1416 - .delegatedTaskResultPending(task.childThreadId, childRun?.delegatedTaskId)
1417 - .pipe(Effect.mapError(threadManagementFailure)));
1418 - const workState =
1419 - task.result !== null ? "result_available" : heldForRestart ? "working" : taskWorkState;
1420 - const status =
1421 - task.result !== null
1422 - ? taskStatusForRun(
1423 - task.status === "completed" ||
1424 - task.status === "failed" ||
1425 - task.status === "cancelled" ||
1426 - task.status === "interrupted"
1427 - ? { status: task.status }
1428 - : childRun,
1429 - )
1430 - : workState === "result_available"
1431 - ? taskStatusForRun(taskResultRun ?? childRun)
1432 - : taskStatusForRun(taskResultRun ?? childRun) === "queued"
1433 - ? "queued"
1434 - : "running";
1435 - const derivedResult =
1436 - task.result !== null
1437 - ? task.result
1438 - : taskResultRun !== undefined && isTerminalTaskStatus(status)
1439 - ? subagentResultForRun(childProjection, taskResultRun).text
1440 - : null;
1441 - const resultTransfers = parentProjection.contextTransfers.filter(
1442 - (transfer) =>
1443 - transfer.type === "subagent_result" &&
1444 - transfer.sourceThreadId === task.childThreadId &&
1445 - transfer.targetThreadId === scope.thread.threadId,
1446 - );
1447 - const resultTransferForRun = (run: OrchestrationV2Run | undefined) =>
1448 - !canExposeTaskRunResult(run)
1449 - ? null
1450 - : (resultTransfers.find((transfer) => transfer.sourcePoint.runId === run.id) ??
1451 - (run.id === childRun?.id
1452 - ? resultTransfers.find((transfer) => transfer.sourcePoint.runId === undefined)
1453 - : undefined) ??
1454 - null);
1455 - const resultTransfer = taskResultTransfer(parentProjection, childProjection, task) ?? null;
1456 - const terminalStatus = terminalRun === undefined ? null : taskStatusForRun(terminalRun);
1457 - const latestTerminalSummary = canExposeTaskRunResult(terminalRun)
1458 - ? terminalRun.id === childRun?.id
1459 - ? derivedResult
1460 - : subagentResultForRun(childProjection, terminalRun).text
1461 - : null;
1462 - const resultContextTransferId = resultTransfer?.id ?? null;
1463 - const latestTerminalResultContextTransferId = resultTransferForRun(terminalRun)?.id ?? null;
1464 - const response = {
1465 - taskId: task.id,
1466 - childThreadId: task.childThreadId,
1467 - childRunId: childRun?.id ?? null,
1468 - childNodeId: task.id,
1469 - status,
1470 - workState,
1471 - hasPendingChildRuns: hasPendingChildRuns(childProjection, childRun),
1472 - providerInstanceId: task.providerInstanceId,
1473 - model: task.model,
1474 - summary: derivedResult,
1475 - resultContextTransferId,
1476 - latestTerminalRunId: terminalRun?.id ?? null,
1477 - latestTerminalStatus:
1478 - terminalStatus !== null && isTerminalTaskStatus(terminalStatus) ? terminalStatus : null,
1479 - latestTerminalSummary:
1480 - latestTerminalSummary === derivedResult ? null : latestTerminalSummary,
1481 - latestTerminalResultContextTransferId:
1482 - latestTerminalResultContextTransferId === resultContextTransferId
1483 - ? null
1484 - : latestTerminalResultContextTransferId,
1485 - hasPendingQuestion:
1486 - !isTerminalTaskStatus(status) &&
1487 - childControls.runtimeRequests.some(
1488 - (request) =>
1489 - request.kind === "user_input" &&
1490 - request.status === "pending" &&
1491 - request.responseCapability.type === "live",
1492 - ),
1493 - waitTimedOut,
1494 - } satisfies OrchestratorMcpDelegateTaskResult;
1495 - if (
1496 - acknowledgeTerminal &&
1497 - isTerminalTaskStatus(status) &&
1498 - task.completionDelivery?.state !== "acknowledged" &&
1499 - task.completionDelivery?.state !== "disposed"
1500 - ) {
1501 - const observingRun = ThreadManagementService.latestActiveRun(parentProjection);
1502 - const acknowledgementRequestKey = yield* requestKey(undefined);
1503 - yield* threadManagement
1504 - .dispatch({
1505 - type: "delegated_task.completion-delivery.acknowledge",
1506 - commandId: stableCommandId({
1507 - scope,
1508 - requestKey: acknowledgementRequestKey,
1509 - operation: acknowledgementOperation,
1510 - }),
1511 - parentThreadId: scope.thread.threadId,
1512 - taskId,
1513 - observedByRunId:
1514 - observingRun?.providerInstanceId === scope.thread.providerInstanceId
1515 - ? observingRun.id
1516 - : null,
1517 - })
1518 - .pipe(
1519 - Effect.mapError((error) =>
1520 - failure(
1521 - "orchestration_error",
1522 - `Unable to acknowledge delegated task ${taskId}: ${errorMessage(error)}`,
1523 - ),
1516 + .pipe(
1517 + Effect.mapError((error) =>
1518 + failure(
1519 + "orchestration_error",
1520 + `Unable to acknowledge delegated task ${taskId}: ${errorMessage(error)}`,
1521 ),
1525 - );
1526 - }
1527 - return response;
1528 - });
1522 + ),
1523 + );
1524 + }
1525 + return response;
1526 + });
1527
1530 - const waitForTask = (scope: McpThreadInvocationScope, taskId: NodeId, timeoutMs: number) =>
1531 - Effect.gen(function* () {
1528 + const waitForTask = Effect.fn("OrchestratorMcpService.waitForTask")(
1529 + function* (scope: McpThreadInvocationScope, taskId: NodeId, _timeoutMs: number) {
1530 const streamError = (error: unknown) =>
1531 failure(
1532 "orchestration_error",
@@ -1559,17 +1557,21 @@ const make = Effect.gen(function* () {
1557 Stream.filter((result) => result.hasPendingQuestion || isTerminalTaskStatus(result.status)),
1558 Stream.runHead,
1559 );
1562 - }).pipe(Effect.timeoutOption(Duration.millis(timeoutMs)), Effect.map(Option.flatten));
1560 + },
1561 + (effect, _scope, _taskId, timeoutMs) =>
1562 + effect.pipe(Effect.timeoutOption(Duration.millis(timeoutMs)), Effect.map(Option.flatten)),
1563 + );
1564
1564 - const scheduledTaskRunModes = (task: ScheduledTask) =>
1565 - Effect.gen(function* () {
1565 + const scheduledTaskRunModes = Effect.fn("OrchestratorMcpService.scheduledTaskRunModes")(
1566 + function* (task: ScheduledTask) {
1567 const modes = [{ runtimeMode: task.runtimeMode, interactionMode: task.interactionMode }];
1568 if (task.threadId === null) return modes;
1569 const bound = yield* threadManagement
1570 .getThreadShell(task.threadId)
1571 .pipe(Effect.mapError(threadManagementFailure));
1572 return bound === null || bound.deletedAt !== null ? modes : [...modes, bound];
1572 - });
1573 + },
1574 + );
1575
1576 const withinLimits = (
1577 limits: {
@@ -1586,18 +1588,18 @@ const make = Effect.gen(function* () {
1588 * approved for read-only access, and a thread caller only with a live turn, at modes covering
1589 * every mode the task runs at.
1590 */
1589 - const summarizeScheduledTask = (
1590 - scope: McpInvocationScope,
1591 - caller: {
1592 - readonly parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs"> | undefined;
1593 - readonly limits: {
1594 - readonly runtimeMode: RuntimeMode;
1595 - readonly interactionMode: ProviderInteractionMode;
1596 - };
1597 - },
1598 - task: ScheduledTask,
1599 - ) =>
1600 - Effect.gen(function* () {
1591 + const summarizeScheduledTask = Effect.fn("OrchestratorMcpService.summarizeScheduledTask")(
1592 + function* (
1593 + scope: McpInvocationScope,
1594 + caller: {
1595 + readonly parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs"> | undefined;
1596 + readonly limits: {
1597 + readonly runtimeMode: RuntimeMode;
1598 + readonly interactionMode: ProviderInteractionMode;
1599 + };
1600 + },
1601 + task: ScheduledTask,
1602 + ) {
1603 const live =
1604 caller.parent === undefined
1605 ? scope.client?.access !== "read-only"
@@ -1609,101 +1611,97 @@ const make = Effect.gen(function* () {
1611 Option.isSome(modes) &&
1612 modes.value.every((mode) => withinLimits(caller.limits, mode)),
1613 );
1612 - });
1614 + },
1615 + );
1616
1617 /**
1618 * A scheduled task the caller may change: one whose runs execute at modes no
1619 * broader than the caller's own, so editing its prompt cannot run work above
1620 * the caller's limits.
1621 */
1619 - const loadScheduledTask = (
1622 + const loadScheduledTask = Effect.fn("OrchestratorMcpService.loadScheduledTask")(function* (
1623 scheduledTaskId: ScheduledTask["id"],
1624 limits: {
1625 readonly runtimeMode: RuntimeMode;
1626 readonly interactionMode: ProviderInteractionMode;
1627 },
1625 - ): Effect.Effect<ScheduledTask, OrchestratorMcpFailure> =>
1626 - Effect.gen(function* () {
1627 - const { tasks } = yield* scheduledTasks
1628 - .list()
1628 + ): Effect.fn.Return<ScheduledTask, OrchestratorMcpFailure> {
1629 + const { tasks } = yield* scheduledTasks
1630 + .list()
1631 + .pipe(
1632 + Effect.mapError((error) =>
1633 + failure("orchestration_error", `Could not load scheduled task: ${error.message}`),
1634 + ),
1635 + );
1636 + const task = tasks.find((candidate) => candidate.id === scheduledTaskId);
1637 + if (task === undefined) {
1638 + return yield* failure("task_not_found", `Scheduled task ${scheduledTaskId} was not found.`);
1639 + }
1640 + for (const modes of yield* scheduledTaskRunModes(task)) {
1641 + yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode);
1642 + yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode);
1643 + }
1644 + return task;
1645 + });
1646 +
1647 + return OrchestratorMcpService.of({
1648 + scheduleTask: Effect.fn("OrchestratorMcpService.scheduleTask")(function* (scope, input) {
1649 + const { parent, limits } = yield* loadCaller(scope);
1650 + const projectId = yield* resolveProjectTarget(parent, input.projectId);
1651 + yield* assertLiveCallerForOtherProject(scope, parent, projectId);
1652 + const project = yield* requireProject(projectId);
1653 + const bindToCurrentThread =
1654 + input.bindToCurrentThread ??
1655 + (parent !== undefined && parent.thread.projectId === projectId);
1656 + if (bindToCurrentThread && (parent === undefined || parent.thread.projectId !== projectId)) {
1657 + return yield* failure(
1658 + "invalid_request",
1659 + parent === undefined
1660 + ? "bindToCurrentThread needs an agent running inside a T3 thread."
1661 + : "bindToCurrentThread binds to this thread, which belongs to a different project.",
1662 + );
1663 + }
1664 + const modelSelection =
1665 + parent?.thread.modelSelection ?? (yield* projectDefaultModelSelection(project));
1666 + const derivedTitle = input.prompt.split("\n")[0]?.trim() ?? "";
1667 + const title =
1668 + input.title ?? (derivedTitle.length > 0 ? derivedTitle.slice(0, 80) : "Scheduled task");
1669 + const upsertInput: ScheduledTaskUpsertInput = {
1670 + title,
1671 + prompt: input.prompt,
1672 + enabled: input.enabled ?? true,
1673 + schedule: input.schedule,
1674 + projectId,
1675 + threadId: bindToCurrentThread && parent !== undefined ? parent.thread.id : null,
1676 + workspaceStrategy: scheduledTaskWorkspaceStrategy(bindToCurrentThread),
1677 + modelSelection,
1678 + runtimeMode: limits.runtimeMode,
1679 + interactionMode: limits.interactionMode,
1680 + createdBy: "agent",
1681 + creationSource: "mcp",
1682 + // Scope the idempotency key by provider session so two callers
1683 + // reusing the same clientRequestId cannot collide on one task row.
1684 + ...(input.clientRequestId === undefined
1685 + ? {}
1686 + : {
1687 + commandId: stableCommandId({
1688 + scope,
1689 + requestKey: input.clientRequestId,
1690 + operation: "schedule-task",
1691 + }),
1692 + }),
1693 + };
1694 + const { task } = yield* scheduledTasks
1695 + .upsert(upsertInput)
1696 .pipe(
1697 Effect.mapError((error) =>
1631 - failure("orchestration_error", `Could not load scheduled task: ${error.message}`),
1698 + failure("orchestration_error", `Could not schedule task: ${error.message}`),
1699 ),
1700 );
1634 - const task = tasks.find((candidate) => candidate.id === scheduledTaskId);
1635 - if (task === undefined) {
1636 - return yield* failure("task_not_found", `Scheduled task ${scheduledTaskId} was not found.`);
1637 - }
1638 - for (const modes of yield* scheduledTaskRunModes(task)) {
1639 - yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode);
1640 - yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode);
1641 - }
1642 - return task;
1643 - });
1644 -
1645 - return OrchestratorMcpService.of({
1646 - scheduleTask: (scope, input) =>
1647 - Effect.gen(function* () {
1648 - const { parent, limits } = yield* loadCaller(scope);
1649 - const projectId = yield* resolveProjectTarget(parent, input.projectId);
1650 - yield* assertLiveCallerForOtherProject(scope, parent, projectId);
1651 - const project = yield* requireProject(projectId);
1652 - const bindToCurrentThread =
1653 - input.bindToCurrentThread ??
1654 - (parent !== undefined && parent.thread.projectId === projectId);
1655 - if (
1656 - bindToCurrentThread &&
1657 - (parent === undefined || parent.thread.projectId !== projectId)
1658 - ) {
1659 - return yield* failure(
1660 - "invalid_request",
1661 - parent === undefined
1662 - ? "bindToCurrentThread needs an agent running inside a T3 thread."
1663 - : "bindToCurrentThread binds to this thread, which belongs to a different project.",
1664 - );
1665 - }
1666 - const modelSelection =
1667 - parent?.thread.modelSelection ?? (yield* projectDefaultModelSelection(project));
1668 - const derivedTitle = input.prompt.split("\n")[0]?.trim() ?? "";
1669 - const title =
1670 - input.title ?? (derivedTitle.length > 0 ? derivedTitle.slice(0, 80) : "Scheduled task");
1671 - const upsertInput: ScheduledTaskUpsertInput = {
1672 - title,
1673 - prompt: input.prompt,
1674 - enabled: input.enabled ?? true,
1675 - schedule: input.schedule,
1676 - projectId,
1677 - threadId: bindToCurrentThread && parent !== undefined ? parent.thread.id : null,
1678 - workspaceStrategy: scheduledTaskWorkspaceStrategy(bindToCurrentThread),
1679 - modelSelection,
1680 - runtimeMode: limits.runtimeMode,
1681 - interactionMode: limits.interactionMode,
1682 - createdBy: "agent",
1683 - creationSource: "mcp",
1684 - // Scope the idempotency key by provider session so two callers
1685 - // reusing the same clientRequestId cannot collide on one task row.
1686 - ...(input.clientRequestId === undefined
1687 - ? {}
1688 - : {
1689 - commandId: stableCommandId({
1690 - scope,
1691 - requestKey: input.clientRequestId,
1692 - operation: "schedule-task",
1693 - }),
1694 - }),
1695 - };
1696 - const { task } = yield* scheduledTasks
1697 - .upsert(upsertInput)
1698 - .pipe(
1699 - Effect.mapError((error) =>
1700 - failure("orchestration_error", `Could not schedule task: ${error.message}`),
1701 - ),
1702 - );
1703 - return yield* summarizeScheduledTask(scope, { parent, limits }, task);
1704 - }),
1705 - listScheduledTasks: (scope, input) =>
1706 - Effect.gen(function* () {
1701 + return yield* summarizeScheduledTask(scope, { parent, limits }, task);
1702 + }),
1703 + listScheduledTasks: Effect.fn("OrchestratorMcpService.listScheduledTasks")(
1704 + function* (scope, input) {
1705 const { parent, limits } = yield* loadCaller(scope);
1706 const projectId = input.projectId ?? parent?.thread.projectId;
1707 const { tasks } = yield* scheduledTasks
@@ -1719,9 +1717,10 @@ const make = Effect.gen(function* () {
1717 (task) => summarizeScheduledTask(scope, { parent, limits }, task),
1718 ),
1719 };
1722 - }),
1723 - updateScheduledTask: (scope, input) =>
1724 - Effect.gen(function* () {
1720 + },
1721 + ),
1722 + updateScheduledTask: Effect.fn("OrchestratorMcpService.updateScheduledTask")(
1723 + function* (scope, input) {
1724 const { parent, limits } = yield* loadCaller(scope);
1725 const existing = yield* loadScheduledTask(input.scheduledTaskId, limits);
1726 yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId);
@@ -1772,9 +1771,10 @@ const make = Effect.gen(function* () {
1771 ),
1772 );
1773 return yield* summarizeScheduledTask(scope, { parent, limits }, task);
1775 - }),
1776 - deleteScheduledTask: (scope, input) =>
1777 - Effect.gen(function* () {
1774 + },
1775 + ),
1776 + deleteScheduledTask: Effect.fn("OrchestratorMcpService.deleteScheduledTask")(
1777 + function* (scope, input) {
1778 const { parent, limits } = yield* loadCaller(scope);
1779 const existing = yield* loadScheduledTask(input.scheduledTaskId, limits);
1780 yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId);
@@ -1786,545 +1786,541 @@ const make = Effect.gen(function* () {
1786 ),
1787 );
1788 return { scheduledTaskId: existing.id, deleted: true };
1789 - }),
1790 - requestSecret: (scope, input) =>
1791 - Effect.gen(function* () {
1792 - const { scope: threadScope, parent } = yield* loadThreadCaller(scope, "request_secret");
1793 - const threadId = threadScope.thread.threadId;
1794 - const run = ThreadManagementService.latestActiveRun(parent);
1795 - if (
1796 - run === undefined ||
1797 - run.rootNodeId === null ||
1798 - run.providerInstanceId !== threadScope.thread.providerInstanceId
1799 - ) {
1800 - return yield* failure(
1801 - "parent_not_active",
1802 - "Asking for a secret requires an active run owned by this MCP provider session.",
1803 - );
1804 - }
1805 - const runId = run.id;
1806 - const nodeId = run.rootNodeId;
1807 - const key = yield* requestKey(input.clientRequestId);
1808 - const turnItemId = TurnItemId.make(
1809 - `turn-item:secret-request:${stablePart(threadId)}:${stablePart(key)}`,
1789 + },
1790 + ),
1791 + requestSecret: Effect.fn("OrchestratorMcpService.requestSecret")(function* (scope, input) {
1792 + const { scope: threadScope, parent } = yield* loadThreadCaller(scope, "request_secret");
1793 + const threadId = threadScope.thread.threadId;
1794 + const run = ThreadManagementService.latestActiveRun(parent);
1795 + if (
1796 + run === undefined ||
1797 + run.rootNodeId === null ||
1798 + run.providerInstanceId !== threadScope.thread.providerInstanceId
1799 + ) {
1800 + return yield* failure(
1801 + "parent_not_active",
1802 + "Asking for a secret requires an active run owned by this MCP provider session.",
1803 );
1811 - const record = (secretStatus: "pending" | "cancelled") =>
1812 - threadManagement
1813 - .dispatch({
1814 - type: "secret_request.record",
1815 - commandId: stableCommandId({
1816 - scope,
1817 - requestKey: key,
1818 - operation: `secret-${secretStatus}`,
1819 - }),
1820 - threadId: threadId,
1821 - runId,
1822 - nodeId,
1823 - turnItemId,
1824 - label: input.label,
1825 - reason: input.reason,
1826 - ...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }),
1827 - secretStatus,
1804 + }
1805 + const runId = run.id;
1806 + const nodeId = run.rootNodeId;
1807 + const key = yield* requestKey(input.clientRequestId);
1808 + const turnItemId = TurnItemId.make(
1809 + `turn-item:secret-request:${stablePart(threadId)}:${stablePart(key)}`,
1810 + );
1811 + const record = (secretStatus: "pending" | "cancelled") =>
1812 + threadManagement
1813 + .dispatch({
1814 + type: "secret_request.record",
1815 + commandId: stableCommandId({
1816 + scope,
1817 + requestKey: key,
1818 + operation: `secret-${secretStatus}`,
1819 + }),
1820 + threadId: threadId,
1821 + runId,
1822 + nodeId,
1823 + turnItemId,
1824 + label: input.label,
1825 + reason: input.reason,
1826 + ...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }),
1827 + secretStatus,
1828 + })
1829 + .pipe(
1830 + Effect.mapError((error) =>
1831 + failure(
1832 + "orchestration_error",
1833 + `Could not record the secret request: ${errorMessage(error)}`,
1834 + ),
1835 + ),
1836 + );
1837 + yield* record("pending");
1838 + // Only this call can hand the agent its ref, so the card must not
1839 + // outlive it: a timeout, a failed wait or an aborted call closes it as
1840 + // cancelled.
1841 + const closeCard = record("cancelled").pipe(
1842 + Effect.catch((error) =>
1843 + Effect.logWarning("Could not close a secret request card", { error: error.message }),
1844 + ),
1845 + );
1846 +
1847 + const answered = yield* Effect.gen(function* () {
1848 + while (true) {
1849 + const projection = yield* threadManagement
1850 + .getThreadRecords(threadId, ["runs", "turnItems"], {
1851 + turnItemTypes: ["secret_request"],
1852 + messageRoles: [],
1853 })
1854 .pipe(
1855 Effect.mapError((error) =>
1856 failure(
1857 "orchestration_error",
1833 - `Could not record the secret request: ${errorMessage(error)}`,
1858 + `Unable to read the secret request: ${errorMessage(error)}`,
1859 ),
1860 ),
1861 );
1837 - yield* record("pending");
1838 - // Only this call can hand the agent its ref, so the card must not
1839 - // outlive it: a timeout, a failed wait or an aborted call closes it as
1840 - // cancelled.
1841 - const closeCard = record("cancelled").pipe(
1842 - Effect.catch((error) =>
1843 - Effect.logWarning("Could not close a secret request card", { error: error.message }),
1862 + const item = projection.turnItems.find((candidate) => candidate.id === turnItemId);
1863 + if (item?.type === "secret_request" && item.secretStatus !== "pending") {
1864 + return item.secretStatus;
1865 + }
1866 + const current = projection.runs.find((candidate) => candidate.id === runId);
1867 + if (
1868 + current === undefined ||
1869 + ThreadManagementService.isTerminalRunStatus(current.status)
1870 + ) {
1871 + yield* record("cancelled");
1872 + return "cancelled" as const;
1873 + }
1874 + yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS));
1875 + }
1876 + }).pipe(
1877 + Effect.timeoutOption(
1878 + Duration.millis(
1879 + Math.min(input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS),
1880 ),
1881 + ),
1882 + Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : closeCard)),
1883 + );
1884 + if (Option.isNone(answered)) yield* closeCard;
1885 + const status = Option.isSome(answered)
1886 + ? answered.value
1887 + : yield* threadManagement
1888 + .getThreadRecords(threadId, ["turnItems"], {
1889 + turnItemTypes: ["secret_request"],
1890 + messageRoles: [],
1891 + })
1892 + .pipe(
1893 + Effect.map((records) => {
1894 + const item = records.turnItems.find((candidate) => candidate.id === turnItemId);
1895 + return item?.type === "secret_request" &&
1896 + (item.secretStatus === "saved" || item.secretStatus === "declined")
1897 + ? item.secretStatus
1898 + : ("timed_out" as const);
1899 + }),
1900 + Effect.orElseSucceed(() => "timed_out" as const),
1901 + );
1902 + yield* Effect.annotateCurrentSpan({ "secret_request.status": status });
1903 + yield* Metrics.increment(Metrics.secretRequestsTotal, { status });
1904 + if (status !== "saved") return { status };
1905 + const secretRef = yield* secretRequests.savedRef({ threadId: threadId, turnItemId });
1906 + if (Option.isNone(secretRef)) {
1907 + return yield* failure(
1908 + "orchestration_error",
1909 + "The user saved the secret, but it could not be read. Ask again with a new clientRequestId.",
1910 );
1911 + }
1912 + return { status, secretRef: secretRef.value };
1913 + }),
1914
1847 - const answered = yield* Effect.gen(function* () {
1848 - while (true) {
1849 - const projection = yield* threadManagement
1850 - .getThreadRecords(threadId, ["runs", "turnItems"], {
1851 - turnItemTypes: ["secret_request"],
1852 - messageRoles: [],
1853 - })
1854 - .pipe(
1855 - Effect.mapError((error) =>
1856 - failure(
1857 - "orchestration_error",
1858 - `Unable to read the secret request: ${errorMessage(error)}`,
1859 - ),
1860 - ),
1861 - );
1862 - const item = projection.turnItems.find((candidate) => candidate.id === turnItemId);
1863 - if (item?.type === "secret_request" && item.secretStatus !== "pending") {
1864 - return item.secretStatus;
1865 - }
1866 - const current = projection.runs.find((candidate) => candidate.id === runId);
1867 - if (
1868 - current === undefined ||
1869 - ThreadManagementService.isTerminalRunStatus(current.status)
1870 - ) {
1871 - yield* record("cancelled");
1872 - return "cancelled" as const;
1873 - }
1874 - yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS));
1875 - }
1876 - }).pipe(
1877 - Effect.timeoutOption(
1878 - Duration.millis(
1879 - Math.min(input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS),
1880 - ),
1881 - ),
1882 - Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : closeCard)),
1883 - );
1884 - if (Option.isNone(answered)) yield* closeCard;
1885 - const status = Option.isSome(answered)
1886 - ? answered.value
1887 - : yield* threadManagement
1888 - .getThreadRecords(threadId, ["turnItems"], {
1889 - turnItemTypes: ["secret_request"],
1890 - messageRoles: [],
1891 - })
1892 - .pipe(
1893 - Effect.map((records) => {
1894 - const item = records.turnItems.find((candidate) => candidate.id === turnItemId);
1895 - return item?.type === "secret_request" &&
1896 - (item.secretStatus === "saved" || item.secretStatus === "declined")
1897 - ? item.secretStatus
1898 - : ("timed_out" as const);
1899 - }),
1900 - Effect.orElseSucceed(() => "timed_out" as const),
1901 - );
1902 - yield* Effect.annotateCurrentSpan({ "secret_request.status": status });
1903 - yield* Metrics.increment(Metrics.secretRequestsTotal, { status });
1904 - if (status !== "saved") return { status };
1905 - const secretRef = yield* secretRequests.savedRef({ threadId: threadId, turnItemId });
1906 - if (Option.isNone(secretRef)) {
1907 - return yield* failure(
1908 - "orchestration_error",
1909 - "The user saved the secret, but it could not be read. Ask again with a new clientRequestId.",
1915 + capabilities: Effect.fn("OrchestratorMcpService.capabilities")(function* (scope) {
1916 + const { parent, limits } = yield* loadCaller(scope);
1917 + const providers = yield* loadProviders;
1918 + const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds();
1919 + const modelPreferences = yield* serverSettings.getSettings.pipe(
1920 + Effect.map((settings) => settings.providerModelPreferences ?? {}),
1921 + Effect.mapError(() => failure("orchestration_error", "Unable to read server settings.")),
1922 + );
1923 + return {
1924 + parentThreadId: parent?.thread.id ?? null,
1925 + inheritedProviderInstanceId: parent?.thread.modelSelection.instanceId ?? null,
1926 + inheritedModel: parent?.thread.modelSelection.model ?? null,
1927 + runtimeMode: limits.runtimeMode,
1928 + interactionMode: limits.interactionMode,
1929 + providers: providers.map((provider) => {
1930 + const constraints = providerConstraints(
1931 + provider,
1932 + orchestrationCapableInstanceIds.has(provider.instanceId),
1933 );
1911 - }
1912 - return { status, secretRef: secretRef.value };
1913 - }).pipe(Effect.withSpan("OrchestratorMcpService.requestSecret")),
1914 -
1915 - capabilities: (scope) =>
1916 - Effect.gen(function* () {
1917 - const { parent, limits } = yield* loadCaller(scope);
1918 - const providers = yield* loadProviders;
1919 - const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds();
1920 - const modelPreferences = yield* serverSettings.getSettings.pipe(
1921 - Effect.map((settings) => settings.providerModelPreferences ?? {}),
1922 - Effect.mapError(() => failure("orchestration_error", "Unable to read server settings.")),
1934 + return {
1935 + providerInstanceId: provider.instanceId,
1936 + driverKind: provider.driver,
1937 + displayName: provider?.displayName ?? null,
1938 + models:
1939 + provider?.models
1940 + .filter(
1941 + (model) =>
1942 + model.isCustom ||
1943 + !modelPreferences[provider.instanceId]?.hiddenModels.includes(model.slug),
1944 + )
1945 + .map((model) => ({
1946 + id: model.slug,
1947 + label: model.name ?? null,
1948 + ...(model.capabilities?.optionDescriptors === undefined
1949 + ? {}
1950 + : { options: model.capabilities.optionDescriptors }),
1951 + })) ?? [],
1952 + ...(provider.supportedRuntimeModes === undefined ||
1953 + provider.supportedRuntimeModes.length === 0
1954 + ? {}
1955 + : { runtimeModes: [...provider.supportedRuntimeModes] }),
1956 + canRunChildTask: constraints.length === 0,
1957 + canRunCrossProviderChildTask: constraints.length === 0,
1958 + constraints: [...constraints],
1959 + };
1960 + }),
1961 + features: {
1962 + appOwnedSubagents: true,
1963 + asyncPolling: true,
1964 + cancellation: true,
1965 + batchThreadCreation: true,
1966 + threadManagement: true,
1967 + incrementalThreadRead: true,
1968 + scheduledTasks: true,
1969 + maxBatchThreads: 20,
1970 + },
1971 + };
1972 + }),
1973 + delegateTask: Effect.fn("OrchestratorMcpService.delegateTask")(function* (callerScope, input) {
1974 + const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task");
1975 + const parentRun = parent.runs
1976 + .filter(ThreadManagementService.isActiveRun)
1977 + .toSorted((left, right) => right.ordinal - left.ordinal)[0];
1978 + if (
1979 + parentRun === undefined ||
1980 + parentRun.rootNodeId === null ||
1981 + parentRun.providerInstanceId !== scope.thread.providerInstanceId
1982 + ) {
1983 + return yield* failure(
1984 + "parent_not_active",
1985 + "Delegated tasks require an active run owned by this MCP provider session.",
1986 );
1924 - return {
1925 - parentThreadId: parent?.thread.id ?? null,
1926 - inheritedProviderInstanceId: parent?.thread.modelSelection.instanceId ?? null,
1927 - inheritedModel: parent?.thread.modelSelection.model ?? null,
1928 - runtimeMode: limits.runtimeMode,
1929 - interactionMode: limits.interactionMode,
1930 - providers: providers.map((provider) => {
1931 - const constraints = providerConstraints(
1932 - provider,
1933 - orchestrationCapableInstanceIds.has(provider.instanceId),
1934 - );
1935 - return {
1936 - providerInstanceId: provider.instanceId,
1937 - driverKind: provider.driver,
1938 - displayName: provider?.displayName ?? null,
1939 - models:
1940 - provider?.models
1941 - .filter(
1942 - (model) =>
1943 - model.isCustom ||
1944 - !modelPreferences[provider.instanceId]?.hiddenModels.includes(model.slug),
1945 - )
1946 - .map((model) => ({
1947 - id: model.slug,
1948 - label: model.name ?? null,
1949 - ...(model.capabilities?.optionDescriptors === undefined
1950 - ? {}
1951 - : { options: model.capabilities.optionDescriptors }),
1952 - })) ?? [],
1953 - ...(provider.supportedRuntimeModes === undefined ||
1954 - provider.supportedRuntimeModes.length === 0
1955 - ? {}
1956 - : { runtimeModes: [...provider.supportedRuntimeModes] }),
1957 - canRunChildTask: constraints.length === 0,
1958 - canRunCrossProviderChildTask: constraints.length === 0,
1959 - constraints: [...constraints],
1960 - };
1961 - }),
1962 - features: {
1963 - appOwnedSubagents: true,
1964 - asyncPolling: true,
1965 - cancellation: true,
1966 - batchThreadCreation: true,
1967 - threadManagement: true,
1968 - incrementalThreadRead: true,
1969 - scheduledTasks: true,
1970 - maxBatchThreads: 20,
1971 - },
1972 - };
1973 - }),
1974 - delegateTask: (callerScope, input) =>
1975 - Effect.gen(function* () {
1976 - const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task");
1977 - const parentRun = parent.runs
1978 - .filter(ThreadManagementService.isActiveRun)
1979 - .toSorted((left, right) => right.ordinal - left.ordinal)[0];
1980 - if (
1981 - parentRun === undefined ||
1982 - parentRun.rootNodeId === null ||
1983 - parentRun.providerInstanceId !== scope.thread.providerInstanceId
1984 - ) {
1985 - return yield* failure(
1986 - "parent_not_active",
1987 - "Delegated tasks require an active run owned by this MCP provider session.",
1987 + }
1988 + const providers = yield* loadProviders;
1989 + const key = yield* requestKey(input.clientRequestId);
1990 + const commandId = stableCommandId({
1991 + scope,
1992 + requestKey: key,
1993 + operation: "delegate-task",
1994 + });
1995 + const isRetryOfAcceptedDelegation = yield* threadManagement.hasReceipt(commandId);
1996 + const target = yield* resolveTargetRechecking({
1997 + parent,
1998 + target: input.target,
1999 + providers,
2000 + skipProjectEnablementFilter: isRetryOfAcceptedDelegation,
2001 + });
2002 + const runtimeMode = yield* resolveRuntimeMode(
2003 + parent.thread.runtimeMode,
2004 + input.runtimeMode,
2005 + target,
2006 + );
2007 + const interactionMode = yield* resolveInteractionMode(
2008 + parent.thread.interactionMode,
2009 + input.interactionMode,
2010 + );
2011 + let workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined;
2012 + if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) {
2013 + const project = yield* requireProject(parent.thread.projectId);
2014 + const base = yield* gitDriver
2015 + .resolveCommit({
2016 + cwd: parent.thread.worktreePath ?? project.workspaceRoot,
2017 + revision: "HEAD",
2018 + })
2019 + .pipe(
2020 + Effect.mapError(() =>
2021 + failure("invalid_request", "Unable to resolve the parent checkout commit."),
2022 + ),
2023 );
1989 - }
1990 - const providers = yield* loadProviders;
1991 - const key = yield* requestKey(input.clientRequestId);
1992 - const commandId = stableCommandId({
1993 - scope,
1994 - requestKey: key,
1995 - operation: "delegate-task",
1996 - });
1997 - const isRetryOfAcceptedDelegation = yield* threadManagement.hasReceipt(commandId);
1998 - const target = yield* resolveTargetRechecking({
1999 - parent,
2000 - target: input.target,
2001 - providers,
2002 - skipProjectEnablementFilter: isRetryOfAcceptedDelegation,
2003 - });
2004 - const runtimeMode = yield* resolveRuntimeMode(
2005 - parent.thread.runtimeMode,
2006 - input.runtimeMode,
2007 - target,
2008 - );
2009 - const interactionMode = yield* resolveInteractionMode(
2010 - parent.thread.interactionMode,
2011 - input.interactionMode,
2012 - );
2013 - let workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined;
2014 - if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) {
2015 - const project = yield* requireProject(parent.thread.projectId);
2016 - const base = yield* gitDriver
2017 - .resolveCommit({
2018 - cwd: parent.thread.worktreePath ?? project.workspaceRoot,
2019 - revision: "HEAD",
2020 - })
2024 + // Launch preparation creates the worktree from the project root, so a
2025 + // parent checkout in another repository (such as a Git folder inside
2026 + // Scratch) would hand it a commit it cannot find.
2027 + if (parent.thread.worktreePath !== null) {
2028 + yield* gitDriver
2029 + .resolveCommit({ cwd: project.workspaceRoot, revision: base.commitSha })
2030 .pipe(
2031 Effect.mapError(() =>
2023 - failure("invalid_request", "Unable to resolve the parent checkout commit."),
2032 + failure(
2033 + "invalid_request",
2034 + `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.`,
2035 + ),
2036 ),
2037 );
2026 - // Launch preparation creates the worktree from the project root, so a
2027 - // parent checkout in another repository (such as a Git folder inside
2028 - // Scratch) would hand it a commit it cannot find.
2029 - if (parent.thread.worktreePath !== null) {
2030 - yield* gitDriver
2031 - .resolveCommit({ cwd: project.workspaceRoot, revision: base.commitSha })
2038 + }
2039 + workspaceStrategy = { type: "worktree", baseRef: base.commitSha, startFromOrigin: false };
2040 + }
2041 + // ThreadManagementService.dispatch is the chokepoint for this command
2042 + // type's own enablement check, using the same command id and its
2043 + // receipt-replay exemption, so no separate assert runs here.
2044 + const result = yield* threadManagement
2045 + .dispatch({
2046 + type: "delegated_task.request",
2047 + createdBy: "agent",
2048 + creationSource: "mcp",
2049 + commandId,
2050 + parentThreadId: scope.thread.threadId,
2051 + parentRunId: parentRun.id,
2052 + parentNodeId: parentRun.rootNodeId,
2053 + task: taskPrompt(input),
2054 + ...(input.title === undefined ? {} : { title: input.title }),
2055 + modelSelection: target.modelSelection,
2056 + runtimeMode,
2057 + interactionMode,
2058 + ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
2059 + // Async delegations wake the parent on every child terminal; wait
2060 + // delegations deliver through the blocking tool call, so a wake is
2061 + // only needed if the parent settled first (timeout, disconnect).
2062 + completionWake: input.mode === "wait" ? "settled_only" : "always",
2063 + })
2064 + .pipe(
2065 + Effect.mapError((error) =>
2066 + error._tag === "ThreadManagementProviderInstanceDisabledError"
2067 + ? threadManagementFailure(error)
2068 + : failure(
2069 + "orchestration_error",
2070 + `Unable to create delegated task: ${errorMessage(error)}`,
2071 + ),
2072 + ),
2073 + );
2074 + const taskEvent = result.storedEvents.find(
2075 + (stored) =>
2076 + stored.event.type === "subagent.updated" && stored.event.payload.origin === "app_owned",
2077 + );
2078 + if (taskEvent?.event.type !== "subagent.updated") {
2079 + return yield* failure(
2080 + "orchestration_error",
2081 + "Delegated task command did not produce a task projection.",
2082 + );
2083 + }
2084 + const taskId = taskEvent.event.payload.id;
2085 + const childThreadId = taskEvent.event.payload.childThreadId;
2086 + const childRunEvent = result.storedEvents.find(
2087 + (stored) => stored.event.type === "run.created" && stored.event.threadId === childThreadId,
2088 + );
2089 + if (
2090 + childThreadId !== null &&
2091 + childRunEvent?.event.type === "run.created" &&
2092 + childRunEvent.event.payload.workspacePreparation !== undefined
2093 + ) {
2094 + yield* threadLaunch.prepareRun({
2095 + commandId,
2096 + threadId: childThreadId,
2097 + runId: childRunEvent.event.payload.id,
2098 + });
2099 + }
2100 +
2101 + if (input.mode !== "wait") {
2102 + return yield* readTask(scope, taskId, false, true);
2103 + }
2104 + const timeoutMs = Math.min(
2105 + MAX_WAIT_TIMEOUT_MS,
2106 + Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
2107 + );
2108 + const waited = yield* waitForTask(scope, taskId, timeoutMs);
2109 + if (Option.isSome(waited) && isTerminalTaskStatus(waited.value.status)) {
2110 + return waited.value;
2111 + }
2112 + // An incomplete wait gives up delivery: upgrade so a later terminal
2113 + // wakes the parent even mid-turn.
2114 + yield* threadManagement
2115 + .dispatch({
2116 + type: "delegated_task.wake-policy",
2117 + commandId: stableCommandId({
2118 + scope,
2119 + requestKey: key,
2120 + operation: "delegate-task-wake-policy",
2121 + }),
2122 + parentThreadId: scope.thread.threadId,
2123 + taskId,
2124 + completionWake: "always",
2125 + })
2126 + .pipe(
2127 + Effect.catch((error) =>
2128 + Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {
2129 + taskId,
2130 + outcome:
2131 + error._tag === "OrchestratorCommandPreviouslyRejectedError"
2132 + ? "previously_rejected"
2133 + : "dispatch_failed",
2134 + error,
2135 + }),
2136 + ),
2137 + Effect.catchCause((cause) =>
2138 + Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {
2139 + taskId,
2140 + outcome: "defect",
2141 + cause,
2142 + }),
2143 + ),
2144 + );
2145 + return yield* readTask(scope, taskId, Option.isNone(waited), true);
2146 + }),
2147 + taskStatus: Effect.fn("OrchestratorMcpService.taskStatus")(function* (callerScope, taskId) {
2148 + const scope = yield* requireThreadScope(callerScope, "task_status");
2149 + return yield* readTask(scope, taskId, false, true);
2150 + }),
2151 + cancelTask: Effect.fn("OrchestratorMcpService.cancelTask")(function* (callerScope, input) {
2152 + const scope = yield* requireThreadScope(callerScope, "task_cancel");
2153 + const current = yield* readTask(scope, input.taskId);
2154 + const key = yield* requestKey(input.clientRequestId);
2155 + const parentProjection = yield* loadProjection(scope.thread.threadId);
2156 + // Cancelling stops the child and every task under it, each a write to a
2157 + // thread its user may have raised above the parent's modes since it was
2158 + // delegated. All of them are checked before anything is stopped.
2159 + const assertStoppable = Effect.fn("OrchestratorMcpService.assertStoppable")(function* (
2160 + threadId: ThreadId,
2161 + ): Effect.fn.Return<void, OrchestratorMcpFailure> {
2162 + const shell = yield* threadManagement
2163 + .getThreadShell(threadId)
2164 + .pipe(Effect.mapError(threadManagementFailure));
2165 + if (shell !== null && shell.deletedAt === null) {
2166 + yield* resolveRuntimeMode(parentProjection.thread.runtimeMode, shell.runtimeMode);
2167 + yield* resolveInteractionMode(
2168 + parentProjection.thread.interactionMode,
2169 + shell.interactionMode,
2170 + );
2171 + }
2172 + const { subagents } = yield* threadManagement
2173 + .getThreadRecords(threadId, ["subagents"])
2174 + .pipe(Effect.mapError(threadManagementFailure));
2175 + for (const task of subagents) {
2176 + if (task.origin === "app_owned" && task.childThreadId !== null) {
2177 + yield* assertStoppable(task.childThreadId);
2178 + }
2179 + }
2180 + });
2181 + yield* assertStoppable(current.childThreadId);
2182 + const parentTask = parentProjection.subagents.find(
2183 + (task) => task.id === input.taskId && task.origin === "app_owned",
2184 + );
2185 + const disposeCompletionDelivery =
2186 + parentTask?.completionDelivery?.state === "disposed"
2187 + ? Effect.void
2188 + : threadManagement
2189 + .dispatch({
2190 + type: "delegated_task.completion-delivery.dispose",
2191 + commandId: stableCommandId({
2192 + scope,
2193 + requestKey: key,
2194 + operation: "cancel-task-completion-delivery",
2195 + }),
2196 + parentThreadId: scope.thread.threadId,
2197 + taskId: input.taskId,
2198 + })
2199 .pipe(
2033 - Effect.mapError(() =>
2200 + Effect.asVoid,
2201 + Effect.mapError((error) =>
2202 failure(
2035 - "invalid_request",
2036 - `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.`,
2203 + "orchestration_error",
2204 + `Unable to dispose delegated task ${input.taskId} completion delivery: ${errorMessage(error)}`,
2205 ),
2206 ),
2207 );
2040 - }
2041 - workspaceStrategy = { type: "worktree", baseRef: base.commitSha, startFromOrigin: false };
2042 - }
2043 - // ThreadManagementService.dispatch is the chokepoint for this command
2044 - // type's own enablement check, using the same command id and its
2045 - // receipt-replay exemption, so no separate assert runs here.
2046 - const result = yield* threadManagement
2208 + const stopChild = Effect.gen(function* () {
2209 + const commandId = stableCommandId({ scope, requestKey: key, operation: "cancel-task" });
2210 + const reason = input.reason;
2211 + yield* threadManagement
2212 .dispatch({
2048 - type: "delegated_task.request",
2049 - createdBy: "agent",
2050 - creationSource: "mcp",
2213 + type: "thread.stop",
2214 commandId,
2052 - parentThreadId: scope.thread.threadId,
2053 - parentRunId: parentRun.id,
2054 - parentNodeId: parentRun.rootNodeId,
2055 - task: taskPrompt(input),
2056 - ...(input.title === undefined ? {} : { title: input.title }),
2057 - modelSelection: target.modelSelection,
2058 - runtimeMode,
2059 - interactionMode,
2060 - ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
2061 - // Async delegations wake the parent on every child terminal; wait
2062 - // delegations deliver through the blocking tool call, so a wake is
2063 - // only needed if the parent settled first (timeout, disconnect).
2064 - completionWake: input.mode === "wait" ? "settled_only" : "always",
2215 + threadId: current.childThreadId,
2216 + ...(reason === undefined ? {} : { reason }),
2217 })
2218 .pipe(
2219 Effect.mapError((error) =>
2068 - error._tag === "ThreadManagementProviderInstanceDisabledError"
2069 - ? threadManagementFailure(error)
2070 - : failure(
2071 - "orchestration_error",
2072 - `Unable to create delegated task: ${errorMessage(error)}`,
2073 - ),
2220 + failure(
2221 + "task_not_cancellable",
2222 + `Unable to stop delegated task ${input.taskId}: ${errorMessage(error)}`,
2223 + ),
2224 ),
2225 );
2076 - const taskEvent = result.storedEvents.find(
2077 - (stored) =>
2078 - stored.event.type === "subagent.updated" && stored.event.payload.origin === "app_owned",
2079 - );
2080 - if (taskEvent?.event.type !== "subagent.updated") {
2081 - return yield* failure(
2082 - "orchestration_error",
2083 - "Delegated task command did not produce a task projection.",
2084 - );
2085 - }
2086 - const taskId = taskEvent.event.payload.id;
2087 - const childThreadId = taskEvent.event.payload.childThreadId;
2088 - const childRunEvent = result.storedEvents.find(
2089 - (stored) =>
2090 - stored.event.type === "run.created" && stored.event.threadId === childThreadId,
2091 - );
2092 - if (
2093 - childThreadId !== null &&
2094 - childRunEvent?.event.type === "run.created" &&
2095 - childRunEvent.event.payload.workspacePreparation !== undefined
2096 - ) {
2097 - yield* threadLaunch.prepareRun({
2098 - commandId,
2099 - threadId: childThreadId,
2100 - runId: childRunEvent.event.payload.id,
2101 - });
2102 - }
2103 -
2104 - if (input.mode !== "wait") {
2105 - return yield* readTask(scope, taskId, false, true);
2106 - }
2107 - const timeoutMs = Math.min(
2108 - MAX_WAIT_TIMEOUT_MS,
2109 - Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
2110 - );
2111 - const waited = yield* waitForTask(scope, taskId, timeoutMs);
2112 - if (Option.isSome(waited) && isTerminalTaskStatus(waited.value.status)) {
2113 - return waited.value;
2114 - }
2115 - // An incomplete wait gives up delivery: upgrade so a later terminal
2116 - // wakes the parent even mid-turn.
2226 yield* threadManagement
2118 - .dispatch({
2119 - type: "delegated_task.wake-policy",
2120 - commandId: stableCommandId({
2121 - scope,
2122 - requestKey: key,
2123 - operation: "delegate-task-wake-policy",
2124 - }),
2125 - parentThreadId: scope.thread.threadId,
2126 - taskId,
2127 - completionWake: "always",
2128 - })
2227 + .stopDelegatedTasks({ threadId: current.childThreadId, commandId, reason })
2228 .pipe(
2130 - Effect.catch((error) =>
2131 - Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {
2132 - taskId,
2133 - outcome:
2134 - error._tag === "OrchestratorCommandPreviouslyRejectedError"
2135 - ? "previously_rejected"
2136 - : "dispatch_failed",
2137 - error,
2138 - }),
2139 - ),
2140 - Effect.catchCause((cause) =>
2141 - Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {
2142 - taskId,
2143 - outcome: "defect",
2144 - cause,
2145 - }),
2229 + Effect.mapError((error) =>
2230 + failure(
2231 + "task_not_cancellable",
2232 + `Stopped delegated task ${input.taskId}, but not every task it delegated: ${errorMessage(error)}`,
2233 + ),
2234 ),
2235 );
2148 - return yield* readTask(scope, taskId, Option.isNone(waited), true);
2149 - }),
2150 - taskStatus: (callerScope, taskId) =>
2151 - Effect.gen(function* () {
2152 - const scope = yield* requireThreadScope(callerScope, "task_status");
2153 - return yield* readTask(scope, taskId, false, true);
2154 - }),
2155 - cancelTask: (callerScope, input) =>
2156 - Effect.gen(function* () {
2157 - const scope = yield* requireThreadScope(callerScope, "task_cancel");
2158 - const current = yield* readTask(scope, input.taskId);
2159 - const key = yield* requestKey(input.clientRequestId);
2160 - const parentProjection = yield* loadProjection(scope.thread.threadId);
2161 - // Cancelling stops the child and every task under it, each a write to a
2162 - // thread its user may have raised above the parent's modes since it was
2163 - // delegated. All of them are checked before anything is stopped.
2164 - const assertStoppable = (threadId: ThreadId): Effect.Effect<void, OrchestratorMcpFailure> =>
2165 - Effect.gen(function* () {
2166 - const shell = yield* threadManagement
2167 - .getThreadShell(threadId)
2168 - .pipe(Effect.mapError(threadManagementFailure));
2169 - if (shell !== null && shell.deletedAt === null) {
2170 - yield* resolveRuntimeMode(parentProjection.thread.runtimeMode, shell.runtimeMode);
2171 - yield* resolveInteractionMode(
2172 - parentProjection.thread.interactionMode,
2173 - shell.interactionMode,
2174 - );
2175 - }
2176 - const { subagents } = yield* threadManagement
2177 - .getThreadRecords(threadId, ["subagents"])
2178 - .pipe(Effect.mapError(threadManagementFailure));
2179 - for (const task of subagents) {
2180 - if (task.origin === "app_owned" && task.childThreadId !== null) {
2181 - yield* assertStoppable(task.childThreadId);
2182 - }
2183 - }
2184 - });
2185 - yield* assertStoppable(current.childThreadId);
2186 - const parentTask = parentProjection.subagents.find(
2187 - (task) => task.id === input.taskId && task.origin === "app_owned",
2188 - );
2189 - const disposeCompletionDelivery =
2190 - parentTask?.completionDelivery?.state === "disposed"
2191 - ? Effect.void
2192 - : threadManagement
2193 - .dispatch({
2194 - type: "delegated_task.completion-delivery.dispose",
2195 - commandId: stableCommandId({
2196 - scope,
2197 - requestKey: key,
2198 - operation: "cancel-task-completion-delivery",
2199 - }),
2200 - parentThreadId: scope.thread.threadId,
2201 - taskId: input.taskId,
2202 - })
2203 - .pipe(
2204 - Effect.asVoid,
2205 - Effect.mapError((error) =>
2206 - failure(
2207 - "orchestration_error",
2208 - `Unable to dispose delegated task ${input.taskId} completion delivery: ${errorMessage(error)}`,
2209 - ),
2210 - ),
2211 - );
2212 - const stopChild = Effect.gen(function* () {
2213 - const commandId = stableCommandId({ scope, requestKey: key, operation: "cancel-task" });
2214 - const reason = input.reason;
2236 + const stopped = yield* threadManagement
2237 + .getThreadRecords(current.childThreadId, ["runs"])
2238 + .pipe(Effect.mapError(threadManagementFailure));
2239 + for (const run of stopped.runs) {
2240 + if (
2241 + run.status !== "queued" ||
2242 + (run.delegatedTaskId !== input.taskId && run.id !== current.childRunId)
2243 + )
2244 + continue;
2245 + // Stop preserves the queue for Resume. Cancelling a task must also
2246 + // remove that task's queued turn, including a previously held one.
2247 yield* threadManagement
2248 .dispatch({
2217 - type: "thread.stop",
2218 - commandId,
2249 + type: "queued-run.cancel",
2250 + commandId: stableCommandId({
2251 + scope,
2252 + requestKey: key,
2253 + operation: `cancel-task-queued-run:${run.id}`,
2254 + }),
2255 threadId: current.childThreadId,
2220 - ...(reason === undefined ? {} : { reason }),
2256 + runId: run.id,
2257 })
2222 - .pipe(
2223 - Effect.mapError((error) =>
2224 - failure(
2225 - "task_not_cancellable",
2226 - `Unable to stop delegated task ${input.taskId}: ${errorMessage(error)}`,
2227 - ),
2228 - ),
2229 - );
2230 - yield* threadManagement
2231 - .stopDelegatedTasks({ threadId: current.childThreadId, commandId, reason })
2232 - .pipe(
2233 - Effect.mapError((error) =>
2234 - failure(
2235 - "task_not_cancellable",
2236 - `Stopped delegated task ${input.taskId}, but not every task it delegated: ${errorMessage(error)}`,
2237 - ),
2238 - ),
2239 - );
2240 - const stopped = yield* threadManagement
2241 - .getThreadRecords(current.childThreadId, ["runs"])
2258 .pipe(Effect.mapError(threadManagementFailure));
2243 - for (const run of stopped.runs) {
2244 - if (
2245 - run.status !== "queued" ||
2246 - (run.delegatedTaskId !== input.taskId && run.id !== current.childRunId)
2247 - )
2248 - continue;
2249 - // Stop preserves the queue for Resume. Cancelling a task must also
2250 - // remove that task's queued turn, including a previously held one.
2251 - yield* threadManagement
2252 - .dispatch({
2253 - type: "queued-run.cancel",
2254 - commandId: stableCommandId({
2255 - scope,
2256 - requestKey: key,
2257 - operation: `cancel-task-queued-run:${run.id}`,
2258 - }),
2259 - threadId: current.childThreadId,
2260 - runId: run.id,
2261 - })
2262 - .pipe(Effect.mapError(threadManagementFailure));
2263 - }
2264 - });
2265 - // Checked above; a user raising one of these threads meanwhile is
2266 - // caught again under that thread's lock, which leaves it running.
2267 - const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);
2268 - const stopWithinLimit = stopChild.pipe(
2269 - Effect.provideService(DispatchModeLimit, {
2270 - runtimeMode: parentProjection.thread.runtimeMode,
2271 - interactionMode: parentProjection.thread.interactionMode,
2272 - refused,
2273 - }),
2274 - Effect.catch((error) =>
2275 - Effect.flatMap(Ref.get(refused), (refusal) =>
2276 - Effect.fail(
2277 - refusal === undefined
2278 - ? error
2279 - : failure(
2280 - refusal.mode === "runtime"
2281 - ? "runtime_mode_escalation_denied"
2282 - : "interaction_mode_escalation_denied",
2283 - `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.`,
2284 - ),
2285 - ),
2259 + }
2260 + });
2261 + // Checked above; a user raising one of these threads meanwhile is
2262 + // caught again under that thread's lock, which leaves it running.
2263 + const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);
2264 + const stopWithinLimit = stopChild.pipe(
2265 + Effect.provideService(DispatchModeLimit, {
2266 + runtimeMode: parentProjection.thread.runtimeMode,
2267 + interactionMode: parentProjection.thread.interactionMode,
2268 + refused,
2269 + }),
2270 + Effect.catch((error) =>
2271 + Effect.flatMap(Ref.get(refused), (refusal) =>
2272 + Effect.fail(
2273 + refusal === undefined
2274 + ? error
2275 + : failure(
2276 + refusal.mode === "runtime"
2277 + ? "runtime_mode_escalation_denied"
2278 + : "interaction_mode_escalation_denied",
2279 + `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.`,
2280 + ),
2281 ),
2282 ),
2288 - );
2289 - if (isTerminalTaskStatus(current.status)) {
2290 - yield* stopWithinLimit;
2291 - yield* disposeCompletionDelivery;
2292 - return {
2293 - taskId: input.taskId,
2294 - status: current.status,
2295 - } satisfies OrchestratorMcpTaskCancelResult;
2296 - }
2297 - const child = yield* loadProjection(current.childThreadId);
2298 - if (
2299 - current.workState !== "waiting_for_children" &&
2300 - ThreadManagementService.latestActiveRun(child) === undefined &&
2301 - !child.runs.some(
2302 - (run) =>
2303 - run.status === "queued" &&
2304 - (run.delegatedTaskId === input.taskId || run.id === current.childRunId),
2305 - )
2306 - ) {
2307 - return yield* failure(
2308 - "task_not_cancellable",
2309 - `Delegated task ${input.taskId} has no interruptible child run.`,
2310 - );
2311 - }
2283 + ),
2284 + );
2285 + if (isTerminalTaskStatus(current.status)) {
2286 yield* stopWithinLimit;
2313 - yield* disposeCompletionDelivery.pipe(
2314 - Effect.catchCause((cause) =>
2315 - Effect.logWarning("orchestrator-mcp.cancel-task.delivery-dispose-failed", {
2316 - taskId: input.taskId,
2317 - cause,
2318 - }),
2319 - ),
2320 - );
2287 + yield* disposeCompletionDelivery;
2288 return {
2289 taskId: input.taskId,
2323 - status: "cancel_requested",
2324 - };
2325 - }),
2326 - createThreads: (callerScope, input) =>
2327 - Effect.gen(function* () {
2290 + status: current.status,
2291 + } satisfies OrchestratorMcpTaskCancelResult;
2292 + }
2293 + const child = yield* loadProjection(current.childThreadId);
2294 + if (
2295 + current.workState !== "waiting_for_children" &&
2296 + ThreadManagementService.latestActiveRun(child) === undefined &&
2297 + !child.runs.some(
2298 + (run) =>
2299 + run.status === "queued" &&
2300 + (run.delegatedTaskId === input.taskId || run.id === current.childRunId),
2301 + )
2302 + ) {
2303 + return yield* failure(
2304 + "task_not_cancellable",
2305 + `Delegated task ${input.taskId} has no interruptible child run.`,
2306 + );
2307 + }
2308 + yield* stopWithinLimit;
2309 + yield* disposeCompletionDelivery.pipe(
2310 + Effect.catchCause((cause) =>
2311 + Effect.logWarning("orchestrator-mcp.cancel-task.delivery-dispose-failed", {
2312 + taskId: input.taskId,
2313 + cause,
2314 + }),
2315 + ),
2316 + );
2317 + return {
2318 + taskId: input.taskId,
2319 + status: "cancel_requested",
2320 + };
2321 + }),
2322 + createThreads: Effect.fn("OrchestratorMcpService.createThreads")(
2323 + function* (callerScope, input) {
2324 const { scope, parent } = yield* loadThreadCaller(callerScope, "create_threads");
2325 const parentRun = ThreadManagementService.latestActiveRun(parent);
2326 if (
@@ -2490,263 +2486,253 @@ const make = Effect.gen(function* () {
2486 { concurrency: 1 },
2487 );
2488 return { threads: created };
2493 - }),
2494 - listThreads: (scope, input) =>
2495 - Effect.gen(function* () {
2496 - const { parent } = yield* loadCaller(scope);
2497 - const projectId = yield* resolveProjectTarget(parent, input.projectId);
2498 - const projectThreads = yield* threadManagement
2499 - .listProjectThreads({
2500 - projectId,
2501 - includeSubagents: input.includeSubagents !== false,
2502 - })
2503 - .pipe(
2504 - Effect.mapError((error) =>
2505 - failure("orchestration_error", `Unable to list threads: ${errorMessage(error)}`),
2506 - ),
2507 - );
2508 - const nowMs = yield* Clock.currentTimeMillis;
2509 - const statuses = input.statuses === undefined ? null : new Set(input.statuses);
2510 - const titleContains = input.titleContains?.toLocaleLowerCase();
2511 - const filtered = projectThreads
2512 - .filter(
2513 - (thread) =>
2514 - statuses === null || statuses.has(thread.activityRunStatus ?? thread.status),
2515 - )
2516 - .filter(
2517 - (thread) =>
2518 - input.settled === undefined || threadSettlement(thread).settled === input.settled,
2519 - )
2520 - .filter(
2521 - (thread) => input.snoozed === undefined || isSnoozed(thread, nowMs) === input.snoozed,
2522 - )
2523 - .filter(
2524 - (thread) =>
2525 - titleContains === undefined ||
2526 - thread.title.toLocaleLowerCase().includes(titleContains),
2527 - );
2528 - const cursor = input.cursor ?? 0;
2529 - const limit = input.limit ?? DEFAULT_THREAD_LIST_LIMIT;
2530 - const page = filtered.slice(cursor, cursor + limit);
2531 - const nextCursor = cursor + page.length < filtered.length ? cursor + page.length : null;
2532 - return {
2489 + },
2490 + ),
2491 + listThreads: Effect.fn("OrchestratorMcpService.listThreads")(function* (scope, input) {
2492 + const { parent } = yield* loadCaller(scope);
2493 + const projectId = yield* resolveProjectTarget(parent, input.projectId);
2494 + const projectThreads = yield* threadManagement
2495 + .listProjectThreads({
2496 projectId,
2534 - currentThreadId: parent?.thread.id ?? null,
2535 - threads: page.map((shell) => listItemFromShell(shell, nowMs)),
2536 - nextCursor,
2537 - total: filtered.length,
2538 - } satisfies OrchestratorMcpThreadListResult;
2539 - }),
2540 - readThread: (scope, input) =>
2541 - Effect.gen(function* () {
2542 - const { parent, target, shell } = yield* loadReadableThread(scope, input.threadId);
2543 - const view = input.view ?? "messages";
2544 - const afterPosition = input.afterPosition ?? -1;
2545 - const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT;
2546 - const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS;
2547 - const timeline = yield* threadManagement
2548 - .getTimelinePage(input.threadId, {
2549 - afterPosition,
2550 - limit,
2551 - view,
2552 - ...(input.itemId === undefined ? {} : { itemId: input.itemId }),
2553 - })
2554 - .pipe(Effect.mapError(threadManagementFailure));
2555 - const page = timeline.items;
2556 - const messageIdsByThread = new Map<ThreadId, Array<MessageId>>();
2557 - for (const row of page) {
2558 - if (row.item.type !== "user_message" && row.item.type !== "assistant_message") continue;
2559 - const ids = messageIdsByThread.get(row.sourceThreadId) ?? [];
2560 - ids.push(row.item.messageId);
2561 - messageIdsByThread.set(row.sourceThreadId, ids);
2562 - }
2563 - const sourceMessages = yield* Effect.forEach(
2564 - [...messageIdsByThread],
2565 - ([threadId, messageIds]) =>
2566 - threadManagement.getThreadRecords(threadId, ["messages"], { messageIds }).pipe(
2567 - Effect.map((records) => [threadId, records.messages] as const),
2568 - Effect.mapError(threadManagementFailure),
2569 - ),
2570 - { concurrency: 1 },
2497 + includeSubagents: input.includeSubagents !== false,
2498 + })
2499 + .pipe(
2500 + Effect.mapError((error) =>
2501 + failure("orchestration_error", `Unable to list threads: ${errorMessage(error)}`),
2502 + ),
2503 );
2572 - const messagesByThreadId = new Map(sourceMessages);
2573 - const returnedRunIds = new Set(
2574 - page
2575 - .filter((row) => row.sourceThreadId === target.thread.id)
2576 - .map((row) => row.item.runId),
2504 + const nowMs = yield* Clock.currentTimeMillis;
2505 + const statuses = input.statuses === undefined ? null : new Set(input.statuses);
2506 + const titleContains = input.titleContains?.toLocaleLowerCase();
2507 + const filtered = projectThreads
2508 + .filter(
2509 + (thread) => statuses === null || statuses.has(thread.activityRunStatus ?? thread.status),
2510 + )
2511 + .filter(
2512 + (thread) =>
2513 + input.settled === undefined || threadSettlement(thread).settled === input.settled,
2514 + )
2515 + .filter(
2516 + (thread) => input.snoozed === undefined || isSnoozed(thread, nowMs) === input.snoozed,
2517 + )
2518 + .filter(
2519 + (thread) =>
2520 + titleContains === undefined || thread.title.toLocaleLowerCase().includes(titleContains),
2521 );
2578 - const tasks =
2579 - parent === undefined ? [] : directAppOwnedChildTasks(parent, target, returnedRunIds);
2580 - if (
2581 - parent !== undefined &&
2582 - scope.thread !== undefined &&
2583 - tasks.length > 0 &&
2584 - (input.textOffset ?? 0) === 0
2585 - ) {
2586 - for (const task of tasks) {
2587 - const transfer = taskResultTransfer(parent, target, task);
2588 - const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id;
2589 - const resultRunIds = resultRunId === undefined ? [] : [resultRunId];
2590 - const resultRecords = yield* threadManagement
2591 - .getThreadRecords(target.thread.id, ["messages", "turnItems"], {
2592 - messageRoles: ["assistant"],
2593 - messageRunIds: resultRunIds,
2594 - turnItemRunIds: resultRunIds,
2595 - turnItemTypes: ["assistant_message", "error"],
2596 - })
2597 - .pipe(Effect.mapError(threadManagementFailure));
2598 - if (
2599 - pageIncludesTerminalTaskResult({
2600 - parent,
2601 - page,
2602 - task,
2603 - target: { ...target, ...resultRecords },
2604 - maxChars,
2605 - })
2606 - ) {
2607 - yield* readTask(
2608 - scope as McpThreadInvocationScope,
2609 - task.id,
2610 - false,
2611 - true,
2612 - "thread-read-acknowledge",
2613 - );
2614 - }
2522 + const cursor = input.cursor ?? 0;
2523 + const limit = input.limit ?? DEFAULT_THREAD_LIST_LIMIT;
2524 + const page = filtered.slice(cursor, cursor + limit);
2525 + const nextCursor = cursor + page.length < filtered.length ? cursor + page.length : null;
2526 + return {
2527 + projectId,
2528 + currentThreadId: parent?.thread.id ?? null,
2529 + threads: page.map((shell) => listItemFromShell(shell, nowMs)),
2530 + nextCursor,
2531 + total: filtered.length,
2532 + } satisfies OrchestratorMcpThreadListResult;
2533 + }),
2534 + readThread: Effect.fn("OrchestratorMcpService.readThread")(function* (scope, input) {
2535 + const { parent, target, shell } = yield* loadReadableThread(scope, input.threadId);
2536 + const view = input.view ?? "messages";
2537 + const afterPosition = input.afterPosition ?? -1;
2538 + const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT;
2539 + const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS;
2540 + const timeline = yield* threadManagement
2541 + .getTimelinePage(input.threadId, {
2542 + afterPosition,
2543 + limit,
2544 + view,
2545 + ...(input.itemId === undefined ? {} : { itemId: input.itemId }),
2546 + })
2547 + .pipe(Effect.mapError(threadManagementFailure));
2548 + const page = timeline.items;
2549 + const messageIdsByThread = new Map<ThreadId, Array<MessageId>>();
2550 + for (const row of page) {
2551 + if (row.item.type !== "user_message" && row.item.type !== "assistant_message") continue;
2552 + const ids = messageIdsByThread.get(row.sourceThreadId) ?? [];
2553 + ids.push(row.item.messageId);
2554 + messageIdsByThread.set(row.sourceThreadId, ids);
2555 + }
2556 + const sourceMessages = yield* Effect.forEach(
2557 + [...messageIdsByThread],
2558 + ([threadId, messageIds]) =>
2559 + threadManagement.getThreadRecords(threadId, ["messages"], { messageIds }).pipe(
2560 + Effect.map((records) => [threadId, records.messages] as const),
2561 + Effect.mapError(threadManagementFailure),
2562 + ),
2563 + { concurrency: 1 },
2564 + );
2565 + const messagesByThreadId = new Map(sourceMessages);
2566 + const returnedRunIds = new Set(
2567 + page.filter((row) => row.sourceThreadId === target.thread.id).map((row) => row.item.runId),
2568 + );
2569 + const tasks =
2570 + parent === undefined ? [] : directAppOwnedChildTasks(parent, target, returnedRunIds);
2571 + if (
2572 + parent !== undefined &&
2573 + scope.thread !== undefined &&
2574 + tasks.length > 0 &&
2575 + (input.textOffset ?? 0) === 0
2576 + ) {
2577 + for (const task of tasks) {
2578 + const transfer = taskResultTransfer(parent, target, task);
2579 + const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id;
2580 + const resultRunIds = resultRunId === undefined ? [] : [resultRunId];
2581 + const resultRecords = yield* threadManagement
2582 + .getThreadRecords(target.thread.id, ["messages", "turnItems"], {
2583 + messageRoles: ["assistant"],
2584 + messageRunIds: resultRunIds,
2585 + turnItemRunIds: resultRunIds,
2586 + turnItemTypes: ["assistant_message", "error"],
2587 + })
2588 + .pipe(Effect.mapError(threadManagementFailure));
2589 + if (
2590 + pageIncludesTerminalTaskResult({
2591 + parent,
2592 + page,
2593 + task,
2594 + target: { ...target, ...resultRecords },
2595 + maxChars,
2596 + })
2597 + ) {
2598 + yield* readTask(
2599 + scope as McpThreadInvocationScope,
2600 + task.id,
2601 + false,
2602 + true,
2603 + "thread-read-acknowledge",
2604 + );
2605 }
2606 }
2617 - return {
2618 - thread: threadDetail(target, timeline.totalItems, shell, yield* Clock.currentTimeMillis),
2619 - recentRuns: target.runs
2620 - .toSorted((left, right) => right.ordinal - left.ordinal)
2621 - .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT)
2622 - .map(threadRun),
2623 - items: page.map((row) =>
2624 - timelineItem({
2625 - row,
2626 - maxChars,
2627 - messagesByThreadId,
2628 - ...(input.itemId === undefined ? {} : { textOffset: input.textOffset ?? 0 }),
2629 - }),
2630 - ),
2631 - nextPosition: page.at(-1)?.position ?? null,
2632 - hasMore: timeline.hasMore,
2633 - } satisfies OrchestratorMcpThreadReadResult;
2634 - }),
2635 - sendToThread: (scope, input) =>
2636 - Effect.gen(function* () {
2637 - const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId);
2638 - yield* assertLiveCallerForOtherThread(scope, parent, target);
2639 - yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode);
2640 - yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode);
2641 -
2642 - const mode = input.mode ?? "auto";
2643 - const key = yield* requestKey(input.clientRequestId);
2644 - const messageId = stableOperationMessageId({
2645 - scope,
2646 - requestKey: key,
2647 - operation: "thread-send",
2648 - });
2649 - const result = yield* threadManagement
2650 - .sendToThread({
2651 - projectId: target.thread.projectId,
2652 - commandId: stableCommandId({
2653 - scope,
2654 - requestKey: key,
2655 - operation: "thread-send",
2656 - }),
2657 - threadId: input.threadId,
2658 - ...(parent === undefined ? {} : { senderThreadId: parent.thread.id }),
2659 - messageId,
2660 - text: input.message,
2661 - attachments: [],
2662 - mode,
2663 - createdBy: "agent",
2664 - creationSource: "mcp",
2665 - })
2666 - .pipe(
2667 - Effect.mapError((error) =>
2668 - isThreadManagementError(error)
2669 - ? threadManagementFailure(error)
2670 - : failure(
2671 - "orchestration_error",
2672 - `Unable to send to thread ${input.threadId}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,
2673 - ),
2674 - ),
2675 - );
2676 - return {
2607 + }
2608 + return {
2609 + thread: threadDetail(target, timeline.totalItems, shell, yield* Clock.currentTimeMillis),
2610 + recentRuns: target.runs
2611 + .toSorted((left, right) => right.ordinal - left.ordinal)
2612 + .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT)
2613 + .map(threadRun),
2614 + items: page.map((row) =>
2615 + timelineItem({
2616 + row,
2617 + maxChars,
2618 + messagesByThreadId,
2619 + ...(input.itemId === undefined ? {} : { textOffset: input.textOffset ?? 0 }),
2620 + }),
2621 + ),
2622 + nextPosition: page.at(-1)?.position ?? null,
2623 + hasMore: timeline.hasMore,
2624 + } satisfies OrchestratorMcpThreadReadResult;
2625 + }),
2626 + sendToThread: Effect.fn("OrchestratorMcpService.sendToThread")(function* (scope, input) {
2627 + const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId);
2628 + yield* assertLiveCallerForOtherThread(scope, parent, target);
2629 + yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode);
2630 + yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode);
2631 +
2632 + const mode = input.mode ?? "auto";
2633 + const key = yield* requestKey(input.clientRequestId);
2634 + const messageId = stableOperationMessageId({
2635 + scope,
2636 + requestKey: key,
2637 + operation: "thread-send",
2638 + });
2639 + const result = yield* threadManagement
2640 + .sendToThread({
2641 + projectId: target.thread.projectId,
2642 + commandId: stableCommandId({
2643 + scope,
2644 + requestKey: key,
2645 + operation: "thread-send",
2646 + }),
2647 threadId: input.threadId,
2648 + ...(parent === undefined ? {} : { senderThreadId: parent.thread.id }),
2649 messageId,
2679 - runId: result.run.id,
2680 - ...(result.run.delegatedTaskId === undefined
2681 - ? {}
2682 - : { taskId: result.run.delegatedTaskId }),
2683 - status: result.run.status,
2684 - delivery: result.delivery,
2685 - } satisfies OrchestratorMcpThreadSendResult;
2686 - }),
2687 - waitForThread: (scope, input) =>
2688 - Effect.gen(function* () {
2689 - const { target } = yield* loadScopedThread(scope, input.threadId);
2690 - const result = yield* threadManagement
2691 - .waitForThread({
2692 - projectId: target.thread.projectId,
2693 - threadId: input.threadId,
2694 - ...(input.runId === undefined ? {} : { runId: input.runId }),
2695 - timeoutMs: Math.min(
2696 - MAX_WAIT_TIMEOUT_MS,
2697 - Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
2698 - ),
2699 - })
2700 - .pipe(Effect.mapError(threadManagementFailure));
2701 - return {
2650 + text: input.message,
2651 + attachments: [],
2652 + mode,
2653 + createdBy: "agent",
2654 + creationSource: "mcp",
2655 + })
2656 + .pipe(
2657 + Effect.mapError((error) =>
2658 + isThreadManagementError(error)
2659 + ? threadManagementFailure(error)
2660 + : failure(
2661 + "orchestration_error",
2662 + `Unable to send to thread ${input.threadId}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,
2663 + ),
2664 + ),
2665 + );
2666 + return {
2667 + threadId: input.threadId,
2668 + messageId,
2669 + runId: result.run.id,
2670 + ...(result.run.delegatedTaskId === undefined ? {} : { taskId: result.run.delegatedTaskId }),
2671 + status: result.run.status,
2672 + delivery: result.delivery,
2673 + } satisfies OrchestratorMcpThreadSendResult;
2674 + }),
2675 + waitForThread: Effect.fn("OrchestratorMcpService.waitForThread")(function* (scope, input) {
2676 + const { target } = yield* loadScopedThread(scope, input.threadId);
2677 + const result = yield* threadManagement
2678 + .waitForThread({
2679 + projectId: target.thread.projectId,
2680 threadId: input.threadId,
2703 - runId: result.run?.id ?? null,
2704 - status: result.run === null ? "idle" : runOutcome(result.run),
2705 - timedOut: result.timedOut,
2706 - } satisfies OrchestratorMcpThreadWaitResult;
2707 - }),
2708 - interruptThread: (scope, input) =>
2709 - Effect.gen(function* () {
2710 - const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId);
2711 - yield* assertLiveCallerForOtherThread(scope, parent, target);
2712 - yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode);
2713 - yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode);
2714 - const key = yield* requestKey(input.clientRequestId);
2715 - const result = yield* threadManagement
2716 - .interruptThread({
2717 - projectId: target.thread.projectId,
2718 - commandId: stableCommandId({
2719 - scope,
2720 - requestKey: key,
2721 - operation: "thread-interrupt",
2722 - }),
2723 - threadId: input.threadId,
2724 - ...(input.runId === undefined ? {} : { runId: input.runId }),
2725 - ...(input.reason === undefined ? {} : { reason: input.reason }),
2726 - })
2727 - .pipe(
2728 - Effect.mapError((error) =>
2729 - isThreadManagementError(error)
2730 - ? threadManagementFailure(error)
2731 - : failure(
2732 - "orchestration_error",
2733 - `Unable to interrupt thread ${input.threadId}: ${errorMessage(error)}`,
2734 - ),
2735 - ),
2736 - );
2737 - if (result.type === "no_active_run") {
2738 - return {
2739 - threadId: input.threadId,
2740 - runId: null,
2741 - status: "no_active_run",
2742 - } satisfies OrchestratorMcpThreadInterruptResult;
2743 - }
2681 + ...(input.runId === undefined ? {} : { runId: input.runId }),
2682 + timeoutMs: Math.min(
2683 + MAX_WAIT_TIMEOUT_MS,
2684 + Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
2685 + ),
2686 + })
2687 + .pipe(Effect.mapError(threadManagementFailure));
2688 + return {
2689 + threadId: input.threadId,
2690 + runId: result.run?.id ?? null,
2691 + status: result.run === null ? "idle" : runOutcome(result.run),
2692 + timedOut: result.timedOut,
2693 + } satisfies OrchestratorMcpThreadWaitResult;
2694 + }),
2695 + interruptThread: Effect.fn("OrchestratorMcpService.interruptThread")(function* (scope, input) {
2696 + const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId);
2697 + yield* assertLiveCallerForOtherThread(scope, parent, target);
2698 + yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode);
2699 + yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode);
2700 + const key = yield* requestKey(input.clientRequestId);
2701 + const result = yield* threadManagement
2702 + .interruptThread({
2703 + projectId: target.thread.projectId,
2704 + commandId: stableCommandId({
2705 + scope,
2706 + requestKey: key,
2707 + operation: "thread-interrupt",
2708 + }),
2709 + threadId: input.threadId,
2710 + ...(input.runId === undefined ? {} : { runId: input.runId }),
2711 + ...(input.reason === undefined ? {} : { reason: input.reason }),
2712 + })
2713 + .pipe(
2714 + Effect.mapError((error) =>
2715 + isThreadManagementError(error)
2716 + ? threadManagementFailure(error)
2717 + : failure(
2718 + "orchestration_error",
2719 + `Unable to interrupt thread ${input.threadId}: ${errorMessage(error)}`,
2720 + ),
2721 + ),
2722 + );
2723 + if (result.type === "no_active_run") {
2724 return {
2725 threadId: input.threadId,
2746 - runId: result.run.id,
2747 - status: result.type === "already_terminal" ? result.run.status : "interrupt_requested",
2726 + runId: null,
2727 + status: "no_active_run",
2728 } satisfies OrchestratorMcpThreadInterruptResult;
2749 - }),
2729 + }
2730 + return {
2731 + threadId: input.threadId,
2732 + runId: result.run.id,
2733 + status: result.type === "already_terminal" ? result.run.status : "interrupt_requested",
2734 + } satisfies OrchestratorMcpThreadInterruptResult;
2735 + }),
2736 });
2737 });
2738
apps/server/src/mcp/toolkits/device/handlers.ts
+32 -33
@@ -69,46 +69,45 @@ const requireDeviceAccess = McpInvocationContext.requireThreadMcpCapability("dev
69 ),
70 );
71
72 -const pickDevice = (
72 +const pickDevice = Effect.fn("handlers.pickDevice")(function* (
73 devices: ReadonlyArray<DeviceSummary>,
74 input: {
75 readonly deviceId?: DeviceId | undefined;
76 readonly platform?: DevicePlatform | undefined;
77 readonly hostId?: DeviceHostId | undefined;
78 },
79 -): Effect.Effect<DeviceSummary, DeviceToolUnavailableError> =>
80 - Effect.gen(function* () {
81 - const hostId = input.hostId ?? LOCAL_DEVICE_HOST_ID;
82 - if (input.deviceId !== undefined) {
83 - const match = devices.find(
84 - (device) => device.hostId === hostId && device.id === input.deviceId,
85 - );
86 - if (match) return match;
87 - return yield* new DeviceToolUnavailableError({
88 - reason: `No device ${input.deviceId} on host ${hostId}. Call device_list for current ids.`,
89 - });
90 - }
91 - const candidates = devices.filter(
92 - (device) =>
93 - device.hostId === hostId &&
94 - (input.platform === undefined || device.platform === input.platform),
79 +): Effect.fn.Return<DeviceSummary, DeviceToolUnavailableError> {
80 + const hostId = input.hostId ?? LOCAL_DEVICE_HOST_ID;
81 + if (input.deviceId !== undefined) {
82 + const match = devices.find(
83 + (device) => device.hostId === hostId && device.id === input.deviceId,
84 );
96 - if (candidates.length === 0) {
97 - return yield* new DeviceToolUnavailableError({
98 - reason:
99 - input.platform === undefined
100 - ? "No simulators or emulators were found. Call device_list to see why."
101 - : `No ${input.platform} devices were found on host ${hostId}. Call device_list to see why.`,
102 - });
103 - }
104 - const platforms = new Set(candidates.map((device) => device.platform));
105 - if (input.platform === undefined && platforms.size > 1) {
106 - return yield* new DeviceToolUnavailableError({
107 - reason: "Both iOS and Android devices are available; pass platform or deviceId.",
108 - });
109 - }
110 - return candidates.find((device) => device.booted) ?? candidates[0]!;
111 - });
85 + if (match) return match;
86 + return yield* new DeviceToolUnavailableError({
87 + reason: `No device ${input.deviceId} on host ${hostId}. Call device_list for current ids.`,
88 + });
89 + }
90 + const candidates = devices.filter(
91 + (device) =>
92 + device.hostId === hostId &&
93 + (input.platform === undefined || device.platform === input.platform),
94 + );
95 + if (candidates.length === 0) {
96 + return yield* new DeviceToolUnavailableError({
97 + reason:
98 + input.platform === undefined
99 + ? "No simulators or emulators were found. Call device_list to see why."
100 + : `No ${input.platform} devices were found on host ${hostId}. Call device_list to see why.`,
101 + });
102 + }
103 + const platforms = new Set(candidates.map((device) => device.platform));
104 + if (input.platform === undefined && platforms.size > 1) {
105 + return yield* new DeviceToolUnavailableError({
106 + reason: "Both iOS and Android devices are available; pass platform or deviceId.",
107 + });
108 + }
109 + return candidates.find((device) => device.booted) ?? candidates[0]!;
110 +});
111
112 const toolError = (error: DeviceError | DeviceToolUnavailableError) => error;
113
apps/server/src/preview/DesktopBrowserChannel.ts
+56 -57
@@ -130,65 +130,64 @@ const make = Effect.gen(function* () {
130 Effect.forkScoped,
131 );
132
133 - const endpoint = (key: DesktopTabKey) =>
134 - Effect.gen(function* () {
135 - const id = keyOf(key);
136 - const secret = NodeCrypto.randomBytes(24).toString("base64url");
137 - const server = yield* NodeSocketServer.makeWebSocket({
138 - host: "127.0.0.1",
139 - port: 0,
140 - path: `/${secret}`,
141 - }).pipe(Effect.orDie);
142 - const queue = yield* Queue.unbounded<string>();
143 - inbound.set(id, queue);
144 - // A detach before this registration shut down no queue, so check again.
145 - if (!attachedTabs.has(id)) {
146 - inbound.delete(id);
147 - return yield* Effect.die("The desktop tab detached before the server connected.");
148 - }
149 - yield* Effect.addFinalizer(() =>
133 + const endpoint = Effect.fn("DesktopBrowserChannel.endpoint")(function* (key: DesktopTabKey) {
134 + const id = keyOf(key);
135 + const secret = NodeCrypto.randomBytes(24).toString("base64url");
136 + const server = yield* NodeSocketServer.makeWebSocket({
137 + host: "127.0.0.1",
138 + port: 0,
139 + path: `/${secret}`,
140 + }).pipe(Effect.orDie);
141 + const queue = yield* Queue.unbounded<string>();
142 + inbound.set(id, queue);
143 + // A detach before this registration shut down no queue, so check again.
144 + if (!attachedTabs.has(id)) {
145 + inbound.delete(id);
146 + return yield* Effect.die("The desktop tab detached before the server connected.");
147 + }
148 + yield* Effect.addFinalizer(() =>
149 + Effect.gen(function* () {
150 + if (inbound.get(id) === queue) inbound.delete(id);
151 + yield* Queue.shutdown(queue);
152 + yield* command({ type: "release", ...key });
153 + }),
154 + );
155 + // The relay serves one Playwright connection; a second would see the first's sessions.
156 + let connected = false;
157 + yield* server
158 + .run((socket) =>
159 Effect.gen(function* () {
151 - if (inbound.get(id) === queue) inbound.delete(id);
152 - yield* Queue.shutdown(queue);
153 - yield* command({ type: "release", ...key });
154 - }),
155 - );
156 - // The relay serves one Playwright connection; a second would see the first's sessions.
157 - let connected = false;
158 - yield* server
159 - .run((socket) =>
160 - Effect.gen(function* () {
161 - if (connected) return;
162 - connected = true;
163 - const writer = yield* socket.writer;
164 - const reader = yield* socket.reader;
165 - yield* Stream.fromQueue(queue).pipe(
166 - Stream.runForEach((message) => writer.write(message)),
167 - Effect.forkScoped,
168 - );
169 - const decoder = new TextDecoder();
170 - return yield* reader.pull.pipe(
171 - Effect.flatMap((frames) =>
172 - Effect.forEach(
173 - frames,
174 - (frame) =>
175 - command({
176 - type: "cdp",
177 - ...key,
178 - message: typeof frame === "string" ? frame : decoder.decode(frame),
179 - }),
180 - { discard: true },
181 - ),
160 + if (connected) return;
161 + connected = true;
162 + const writer = yield* socket.writer;
163 + const reader = yield* socket.reader;
164 + yield* Stream.fromQueue(queue).pipe(
165 + Stream.runForEach((message) => writer.write(message)),
166 + Effect.forkScoped,
167 + );
168 + const decoder = new TextDecoder();
169 + return yield* reader.pull.pipe(
170 + Effect.flatMap((frames) =>
171 + Effect.forEach(
172 + frames,
173 + (frame) =>
174 + command({
175 + type: "cdp",
176 + ...key,
177 + message: typeof frame === "string" ? frame : decoder.decode(frame),
178 + }),
179 + { discard: true },
180 ),
183 - Effect.forever,
184 - );
185 - }).pipe(Effect.scoped, Effect.ignore),
186 - )
187 - .pipe(Effect.forkScoped);
188 - const address = server.address;
189 - if (address._tag !== "InetAddressV4") return yield* Effect.die("Unexpected relay address.");
190 - return `ws://127.0.0.1:${address.port}/${secret}`;
191 - });
181 + ),
182 + Effect.forever,
183 + );
184 + }).pipe(Effect.scoped, Effect.ignore),
185 + )
186 + .pipe(Effect.forkScoped);
187 + const address = server.address;
188 + if (address._tag !== "InetAddressV4") return yield* Effect.die("Unexpected relay address.");
189 + return `ws://127.0.0.1:${address.port}/${secret}`;
190 + });
191
192 return DesktopBrowserChannel.of({
193 available: true,
apps/server/src/preview/ServerBrowser.ts
+203 -204
@@ -1237,20 +1237,19 @@ const make = Effect.gen(function* () {
1237 return opening;
1238 };
1239
1240 - const findTab = (threadId: string, tabId: string) =>
1241 - Effect.gen(function* () {
1242 - const existing = tabs.get(tabKey(threadId, tabId));
1243 - if (existing) return existing;
1244 - const { sessions } = yield* manager.list({ threadId: ThreadId.make(threadId) });
1245 - const snapshot = sessions.find(
1246 - (session) => session.tabId === tabId && session.runtime === "server",
1247 - );
1248 - if (!snapshot) return yield* new ServerBrowserTabNotFoundError({ threadId, tabId });
1249 - return yield* Effect.tryPromise({
1250 - try: () => ensureTab(snapshot),
1251 - catch: (cause) => (isTabNotFound(cause) ? cause : new ServerBrowserLaunchError({ cause })),
1252 - });
1240 + const findTab = Effect.fn("ServerBrowser.findTab")(function* (threadId: string, tabId: string) {
1241 + const existing = tabs.get(tabKey(threadId, tabId));
1242 + if (existing) return existing;
1243 + const { sessions } = yield* manager.list({ threadId: ThreadId.make(threadId) });
1244 + const snapshot = sessions.find(
1245 + (session) => session.tabId === tabId && session.runtime === "server",
1246 + );
1247 + if (!snapshot) return yield* new ServerBrowserTabNotFoundError({ threadId, tabId });
1248 + return yield* Effect.tryPromise({
1249 + try: () => ensureTab(snapshot),
1250 + catch: (cause) => (isTabNotFound(cause) ? cause : new ServerBrowserLaunchError({ cause })),
1251 });
1252 + });
1253
1254 const atTabLimit = (agentSessionId: string) =>
1255 tabs.size + pendingTabs.size >= SERVER_TAB_LIMIT ||
@@ -2220,209 +2219,209 @@ const make = Effect.gen(function* () {
2219 }
2220 };
2221
2223 - const attachViewer: ServerBrowser["Service"]["attachViewer"] = (input) =>
2224 - Effect.gen(function* () {
2225 - const tab = yield* findTab(input.threadId, input.tabId);
2226 - const output = yield* Queue.make<ServerBrowserViewerOutput>({
2227 - capacity: VIEWER_OUTPUT_LIMIT,
2228 - strategy: "dropping",
2222 + const attachViewer: ServerBrowser["Service"]["attachViewer"] = Effect.fn(
2223 + "ServerBrowser.attachViewer",
2224 + )(function* (input) {
2225 + const tab = yield* findTab(input.threadId, input.tabId);
2226 + const output = yield* Queue.make<ServerBrowserViewerOutput>({
2227 + capacity: VIEWER_OUTPUT_LIMIT,
2228 + strategy: "dropping",
2229 + });
2230 + const session = yield* Effect.acquireRelease(
2231 + Effect.tryPromise({
2232 + try: () => tab.page.context().newCDPSession(tab.page),
2233 + catch: (cause) => new ServerBrowserLaunchError({ cause }),
2234 + }),
2235 + (session) =>
2236 + Effect.promise(() =>
2237 + session
2238 + .send("Page.stopScreencast")
2239 + .catch(constVoid)
2240 + .then(() => session.detach())
2241 + .catch(constVoid),
2242 + ),
2243 + );
2244 + const quality = Math.min(100, Math.max(1, Math.round(input.quality)));
2245 + // Chromium may drop the final frame during a burst; send a still when it settles.
2246 + let framesInFlight = 0;
2247 + let mayHaveDropped = false;
2248 + let motion = false;
2249 + const recentFrames: Array<number> = [];
2250 + let screencastParams = Promise.resolve();
2251 + let screencastScale = 1;
2252 + const startScreencast = (scale: number) => {
2253 + screencastScale = scale;
2254 + screencastParams = screencastParams.then(async () => {
2255 + if (tab.capturing > 0) return;
2256 + await session.send("Page.stopScreencast").catch(constVoid);
2257 + await session
2258 + .send("Page.startScreencast", {
2259 + format: "jpeg",
2260 + quality: screencastScale < 1 ? Math.min(quality, SCREENCAST_MOTION_QUALITY) : quality,
2261 + maxWidth: Math.max(1, Math.round(input.maxWidth * screencastScale)),
2262 + maxHeight: Math.max(1, Math.round(input.maxHeight * screencastScale)),
2263 + })
2264 + .catch(constVoid);
2265 });
2230 - const session = yield* Effect.acquireRelease(
2231 - Effect.tryPromise({
2232 - try: () => tab.page.context().newCDPSession(tab.page),
2233 - catch: (cause) => new ServerBrowserLaunchError({ cause }),
2234 - }),
2235 - (session) =>
2236 - Effect.promise(() =>
2237 - session
2238 - .send("Page.stopScreencast")
2239 - .catch(constVoid)
2240 - .then(() => session.detach())
2241 - .catch(constVoid),
2242 - ),
2243 - );
2244 - const quality = Math.min(100, Math.max(1, Math.round(input.quality)));
2245 - // Chromium may drop the final frame during a burst; send a still when it settles.
2246 - let framesInFlight = 0;
2247 - let mayHaveDropped = false;
2248 - let motion = false;
2249 - const recentFrames: Array<number> = [];
2250 - let screencastParams = Promise.resolve();
2251 - let screencastScale = 1;
2252 - const startScreencast = (scale: number) => {
2253 - screencastScale = scale;
2254 - screencastParams = screencastParams.then(async () => {
2255 - if (tab.capturing > 0) return;
2256 - await session.send("Page.stopScreencast").catch(constVoid);
2257 - await session
2258 - .send("Page.startScreencast", {
2259 - format: "jpeg",
2260 - quality: screencastScale < 1 ? Math.min(quality, SCREENCAST_MOTION_QUALITY) : quality,
2261 - maxWidth: Math.max(1, Math.round(input.maxWidth * screencastScale)),
2262 - maxHeight: Math.max(1, Math.round(input.maxHeight * screencastScale)),
2263 - })
2264 - .catch(constVoid);
2265 - });
2266 + return screencastParams;
2267 + };
2268 + const viewer: ViewerState = {
2269 + id: NodeCrypto.randomUUID(),
2270 + canOperate: input.canOperate,
2271 + pressedKeys: new Map(),
2272 + pressedButtons: new Map(),
2273 + push: (next) => {
2274 + // Dropped frames must still release Chromium.
2275 + if (Queue.offerUnsafe(output, next)) return;
2276 + if (next._tag === "frame") runFork(next.ack);
2277 + // State a stalled viewer cannot miss replaces its backlog. It runs
2278 + // synchronously so an older replacement can never land after a newer one.
2279 + else if (next._tag === "gone" || next._tag === "control" || next._tag === "fileChooser") {
2280 + const dropped = Effect.runSyncExit(Queue.clear(output));
2281 + if (dropped._tag === "Failure") return;
2282 + Queue.offerUnsafe(output, next);
2283 +
2284 + const chooser = next._tag === "control" ? fileChooserMessage(tab) : null;
2285 + if (chooser && tab.control.controller === viewer.id) Queue.offerUnsafe(output, chooser);
2286 + for (const item of dropped.value) if (item._tag === "frame") runFork(item.ack);
2287 + }
2288 + },
2289 + pause: () => {
2290 + screencastParams = screencastParams.then(() =>
2291 + session.send("Page.stopScreencast").then(constVoid, constVoid),
2292 + );
2293 return screencastParams;
2267 - };
2268 - const viewer: ViewerState = {
2269 - id: NodeCrypto.randomUUID(),
2270 - canOperate: input.canOperate,
2271 - pressedKeys: new Map(),
2272 - pressedButtons: new Map(),
2273 - push: (next) => {
2274 - // Dropped frames must still release Chromium.
2275 - if (Queue.offerUnsafe(output, next)) return;
2276 - if (next._tag === "frame") runFork(next.ack);
2277 - // State a stalled viewer cannot miss replaces its backlog. It runs
2278 - // synchronously so an older replacement can never land after a newer one.
2279 - else if (next._tag === "gone" || next._tag === "control" || next._tag === "fileChooser") {
2280 - const dropped = Effect.runSyncExit(Queue.clear(output));
2281 - if (dropped._tag === "Failure") return;
2282 - Queue.offerUnsafe(output, next);
2283 -
2284 - const chooser = next._tag === "control" ? fileChooserMessage(tab) : null;
2285 - if (chooser && tab.control.controller === viewer.id) Queue.offerUnsafe(output, chooser);
2286 - for (const item of dropped.value) if (item._tag === "frame") runFork(item.ack);
2287 - }
2288 - },
2289 - pause: () => {
2290 - screencastParams = screencastParams.then(() =>
2291 - session.send("Page.stopScreencast").then(constVoid, constVoid),
2292 - );
2293 - return screencastParams;
2294 - },
2295 - resume: () => startScreencast(screencastScale),
2296 - scrolledAt: 0,
2297 - requestedSize: null,
2298 - };
2299 - yield* Effect.acquireRelease(
2300 - Effect.sync(() => {
2301 - tab.viewers.add(viewer);
2294 + },
2295 + resume: () => startScreencast(screencastScale),
2296 + scrolledAt: 0,
2297 + requestedSize: null,
2298 + };
2299 + yield* Effect.acquireRelease(
2300 + Effect.sync(() => {
2301 + tab.viewers.add(viewer);
2302 + reportLiveTabs();
2303 + }),
2304 + () =>
2305 + Effect.promise(async () => {
2306 + await tab.control.disconnect(viewer.id, () => releaseViewerInput(viewer, session));
2307 + tab.viewers.delete(viewer);
2308 + broadcastControl(tab);
2309 reportLiveTabs();
2310 }),
2304 - () =>
2305 - Effect.promise(async () => {
2306 - await tab.control.disconnect(viewer.id, () => releaseViewerInput(viewer, session));
2307 - tab.viewers.delete(viewer);
2308 - broadcastControl(tab);
2309 - reportLiveTabs();
2310 - }),
2311 - );
2312 - if (input.canOperate && tab.control.agentId === null && tab.control.controller === null) {
2313 - yield* Effect.promise(() => tab.control.take(viewer.id));
2314 - }
2315 - broadcastControl(tab);
2316 - pushFileChooser(tab);
2317 - // Full scale: a scaled capture would flash in every other viewer.
2318 - const pushStill = async () => {
2319 - const data = await withCaptureLock(tab, () =>
2320 - ServerBrowserPage.captureViewport(tab.page, session, {
2321 - format: "jpeg",
2322 - quality,
2323 - scale: 1,
2324 - }),
2325 - ).catch(() => null);
2326 - if (data)
2327 - viewer.push({ _tag: "frame", data: Buffer.from(data, "base64"), ack: Effect.void });
2328 - };
2329 - let settleTimer: ReturnType<typeof setTimeout> | null = null;
2330 - yield* Effect.addFinalizer(() =>
2331 - Effect.sync(() => {
2332 - if (settleTimer !== null) clearTimeout(settleTimer);
2311 + );
2312 + if (input.canOperate && tab.control.agentId === null && tab.control.controller === null) {
2313 + yield* Effect.promise(() => tab.control.take(viewer.id));
2314 + }
2315 + broadcastControl(tab);
2316 + pushFileChooser(tab);
2317 + // Full scale: a scaled capture would flash in every other viewer.
2318 + const pushStill = async () => {
2319 + const data = await withCaptureLock(tab, () =>
2320 + ServerBrowserPage.captureViewport(tab.page, session, {
2321 + format: "jpeg",
2322 + quality,
2323 + scale: 1,
2324 }),
2334 - );
2335 - let screencastStarted = false;
2336 - session.on("Page.screencastFrame", (frame) => {
2337 - screencastStarted = true;
2338 - if (framesInFlight > 0) mayHaveDropped = true;
2339 - framesInFlight += 1;
2340 - const arrivedAt = Date.now();
2341 - recentFrames.push(arrivedAt);
2342 - while (recentFrames[0]! < arrivedAt - SCREENCAST_MOTION_WINDOW_MS) recentFrames.shift();
2343 - if (
2344 - !motion &&
2345 - recentFrames.length >= SCREENCAST_MOTION_FRAMES &&
2346 - arrivedAt - viewer.scrolledAt < SCREENCAST_MOTION_WINDOW_MS
2347 - ) {
2348 - motion = true;
2349 - void startScreencast(0.5);
2350 - } else if (motion && arrivedAt - viewer.scrolledAt > SCREENCAST_SETTLE_MS) {
2325 + ).catch(() => null);
2326 + if (data) viewer.push({ _tag: "frame", data: Buffer.from(data, "base64"), ack: Effect.void });
2327 + };
2328 + let settleTimer: ReturnType<typeof setTimeout> | null = null;
2329 + yield* Effect.addFinalizer(() =>
2330 + Effect.sync(() => {
2331 + if (settleTimer !== null) clearTimeout(settleTimer);
2332 + }),
2333 + );
2334 + let screencastStarted = false;
2335 + session.on("Page.screencastFrame", (frame) => {
2336 + screencastStarted = true;
2337 + if (framesInFlight > 0) mayHaveDropped = true;
2338 + framesInFlight += 1;
2339 + const arrivedAt = Date.now();
2340 + recentFrames.push(arrivedAt);
2341 + while (recentFrames[0]! < arrivedAt - SCREENCAST_MOTION_WINDOW_MS) recentFrames.shift();
2342 + if (
2343 + !motion &&
2344 + recentFrames.length >= SCREENCAST_MOTION_FRAMES &&
2345 + arrivedAt - viewer.scrolledAt < SCREENCAST_MOTION_WINDOW_MS
2346 + ) {
2347 + motion = true;
2348 + void startScreencast(0.5);
2349 + } else if (motion && arrivedAt - viewer.scrolledAt > SCREENCAST_SETTLE_MS) {
2350 + motion = false;
2351 + recentFrames.length = 0;
2352 + void startScreencast(1);
2353 + }
2354 + if (settleTimer !== null) clearTimeout(settleTimer);
2355 + settleTimer = setTimeout(() => {
2356 + settleTimer = null;
2357 + if (!motion && !mayHaveDropped) return;
2358 + mayHaveDropped = false;
2359 + if (motion) {
2360 motion = false;
2361 recentFrames.length = 0;
2362 void startScreencast(1);
2363 }
2355 - if (settleTimer !== null) clearTimeout(settleTimer);
2356 - settleTimer = setTimeout(() => {
2357 - settleTimer = null;
2358 - if (!motion && !mayHaveDropped) return;
2359 - mayHaveDropped = false;
2360 - if (motion) {
2361 - motion = false;
2362 - recentFrames.length = 0;
2363 - void startScreencast(1);
2364 - }
2365 - void pushStill();
2366 - }, SCREENCAST_SETTLE_MS);
2367 - viewer.push({
2368 - _tag: "frame",
2369 - data: Buffer.from(frame.data, "base64"),
2370 - ack: Effect.promise(() =>
2371 - sleepUntil(arrivedAt + SCREENCAST_ACK_PACE_MS).then(() => {
2372 - framesInFlight -= 1;
2373 - return session
2374 - .send("Page.screencastFrameAck", { sessionId: frame.sessionId })
2375 - .catch(constVoid);
2376 - }),
2377 - ),
2378 - });
2364 + void pushStill();
2365 + }, SCREENCAST_SETTLE_MS);
2366 + viewer.push({
2367 + _tag: "frame",
2368 + data: Buffer.from(frame.data, "base64"),
2369 + ack: Effect.promise(() =>
2370 + sleepUntil(arrivedAt + SCREENCAST_ACK_PACE_MS).then(() => {
2371 + framesInFlight -= 1;
2372 + return session
2373 + .send("Page.screencastFrameAck", { sessionId: frame.sessionId })
2374 + .catch(constVoid);
2375 + }),
2376 + ),
2377 });
2380 - broadcastViewport(tab);
2381 - yield* Effect.promise(() => startScreencast(1));
2382 - // An idle page does not repaint for a new screencast, so the viewer
2383 - // starts from a still unless a live frame beat it.
2384 - if (!screencastStarted) yield* Effect.promise(pushStill);
2385 - return {
2386 - output,
2387 - input: (raw: unknown) =>
2388 - Effect.promise(async () => {
2389 - if (!viewer.canOperate) return;
2390 - const message = asRecord(raw);
2391 - if (!message) return;
2392 - try {
2393 - if (message.type === "takeControl") {
2394 - const taking = tab.control.take(viewer.id);
2395 - broadcastControl(tab);
2396 - await taking;
2397 - pushFileChooser(tab);
2398 - } else if (message.type === "releaseControl") {
2399 - const releasing = tab.control.release(viewer.id, () =>
2400 - releaseViewerInput(viewer, session),
2401 - );
2402 - broadcastControl(tab);
2403 - await releasing;
2404 - } else if (
2405 - message.type === "dialog" &&
2406 - tab.control.controller === viewer.id &&
2407 - typeof message.accept === "boolean"
2408 - ) {
2409 - await resolveDialog(tab, {
2410 - accept: message.accept,
2411 - ...(typeof message.promptText === "string"
2412 - ? { promptText: message.promptText }
2413 - : {}),
2414 - });
2415 - } else {
2416 - await tab.control.human(viewer.id, () =>
2417 - dispatchViewerInput(tab, session, viewer, message),
2418 - );
2419 - }
2420 - } catch {
2378 + });
2379 + broadcastViewport(tab);
2380 + yield* Effect.promise(() => startScreencast(1));
2381 + // An idle page does not repaint for a new screencast, so the viewer
2382 + // starts from a still unless a live frame beat it.
2383 + if (!screencastStarted) yield* Effect.promise(pushStill);
2384 + return {
2385 + output,
2386 + input: (raw: unknown) =>
2387 + Effect.promise(async () => {
2388 + if (!viewer.canOperate) return;
2389 + const message = asRecord(raw);
2390 + if (!message) return;
2391 + try {
2392 + if (message.type === "takeControl") {
2393 + const taking = tab.control.take(viewer.id);
2394 + broadcastControl(tab);
2395 + await taking;
2396 + pushFileChooser(tab);
2397 + } else if (message.type === "releaseControl") {
2398 + const releasing = tab.control.release(viewer.id, () =>
2399 + releaseViewerInput(viewer, session),
2400 + );
2401 broadcastControl(tab);
2402 + await releasing;
2403 + } else if (
2404 + message.type === "dialog" &&
2405 + tab.control.controller === viewer.id &&
2406 + typeof message.accept === "boolean"
2407 + ) {
2408 + await resolveDialog(tab, {
2409 + accept: message.accept,
2410 + ...(typeof message.promptText === "string"
2411 + ? { promptText: message.promptText }
2412 + : {}),
2413 + });
2414 + } else {
2415 + await tab.control.human(viewer.id, () =>
2416 + dispatchViewerInput(tab, session, viewer, message),
2417 + );
2418 }
2423 - }),
2424 - } satisfies ServerBrowserViewer;
2425 - });
2419 + } catch {
2420 + broadcastControl(tab);
2421 + }
2422 + }),
2423 + } satisfies ServerBrowserViewer;
2424 + });
2425
2426 yield* manager.events.pipe(Stream.runForEach(mirrorManagerEvent), Effect.forkScoped);
2427 if (
apps/server/src/preview/ServerBrowserStream.ts
+178 -172
@@ -51,164 +51,164 @@ const parseMessage = (chunk: Uint8Array | string): unknown => {
51 }
52 };
53
54 -const makeHandler = (browser: ServerBrowser.ServerBrowser["Service"]) =>
55 - Effect.gen(function* () {
56 - const request = yield* HttpServerRequest.HttpServerRequest;
57 - const url = HttpServerRequest.toURL(request);
58 - if (Option.isNone(url)) return HttpServerResponse.text("Bad Request", { status: 400 });
59 - if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/download`) {
60 - return yield* serveDownload(browser, url.value.searchParams);
61 - }
62 - if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/upload`) {
63 - return request.method === "POST"
64 - ? yield* receiveUpload(browser, url.value.searchParams)
65 - : HttpServerResponse.text("Method Not Allowed", { status: 405 });
66 - }
67 - if (
68 - url.value.pathname !== `${PREVIEW_STREAM_ROUTE_PREFIX}/ws` ||
69 - request.headers.upgrade?.toLowerCase() !== "websocket"
70 - ) {
71 - return HttpServerResponse.text("Not Found", { status: 404 });
72 - }
73 - const session = yield* authenticateMediaRequest(AuthOrchestrationReadScope);
74 - const params = url.value.searchParams;
75 - const canOperate =
76 - session.scopes.includes(AuthPreviewOperateScope) && params.get("interactive") !== "false";
77 - const threadId = params.get("threadId") ?? "";
78 - const tabId = params.get("tabId") ?? "";
79 - if (threadId.length === 0 || tabId.length === 0) {
80 - return HttpServerResponse.text("Not Found", { status: 404 });
81 - }
82 - return yield* Effect.scoped(
83 - Effect.gen(function* () {
84 - const attached = yield* browser
85 - .attachViewer({
86 - threadId,
87 - tabId,
88 - canOperate,
89 - maxWidth: intParam(params, "maxWidth", 1280, 7680),
90 - maxHeight: intParam(params, "maxHeight", 800, 4320),
91 - quality: intParam(params, "quality", DEFAULT_QUALITY, 100),
92 - })
93 - .pipe(
94 - Effect.map((viewer) => ({ _tag: "attached" as const, viewer })),
95 - Effect.catchTags({
96 - ServerBrowserTabNotFoundError: () => Effect.succeed({ _tag: "gone" as const }),
97 - ServerBrowserLaunchError: (error) => {
98 - const setup = hostSetup(error.cause);
99 - return setup === undefined
100 - ? Effect.fail(error)
101 - : Effect.succeed({ _tag: "hostSetup" as const, reason: encodeHostSetup(setup) });
102 - },
103 - }),
104 - );
105 - const incoming = NodeHttpServerRequest.toIncomingMessage(request);
106 - // JPEGs are already compressed. Disabling deflate also keeps all
107 - // pending writes in the socket buffer we bound below, not a zlib queue.
108 - delete incoming.headers["sec-websocket-extensions"];
109 - const transport = incoming.socket;
110 - const socket = yield* request.upgrade;
111 - const reader = yield* socket.reader;
112 - const writer = yield* socket.writer;
113 - // A refused upgrade reads as an auth failure to ticket clients, so a
114 - // missing tab is a close code they stop on.
115 - const gone = writer.write(new Socket.CloseEvent(TAB_GONE_CODE, "tab closed"));
116 - if (attached._tag === "gone") {
117 - yield* gone;
118 - return HttpServerResponse.empty();
119 - }
120 - if (attached._tag === "hostSetup") {
121 - yield* writer.write(
122 - new Socket.CloseEvent(PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE, attached.reason),
123 - );
124 - return HttpServerResponse.empty();
125 - }
126 - const viewer = attached.viewer;
127 - // `write` returns once the frame is queued, so Chromium's ack for each
128 - // frame waits for the viewer's `ack` message instead. Only one frame
129 - // is on the wire and only the newest waits behind it, so replies never
130 - // queue behind stale images on a slow link.
131 - let inFlight: Effect.Effect<void> | null = null;
132 - let pending: Frame | null = null;
133 - const disconnectSlowViewer = Effect.sync(() => transport.destroy()).pipe(
134 - Effect.andThen(Effect.interrupt),
54 +// Request middleware owns tracing, including long-lived WebSocket sessions.
55 +const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBrowser["Service"]) {
56 + const request = yield* HttpServerRequest.HttpServerRequest;
57 + const url = HttpServerRequest.toURL(request);
58 + if (Option.isNone(url)) return HttpServerResponse.text("Bad Request", { status: 400 });
59 + if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/download`) {
60 + return yield* serveDownload(browser, url.value.searchParams);
61 + }
62 + if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/upload`) {
63 + return request.method === "POST"
64 + ? yield* receiveUpload(browser, url.value.searchParams)
65 + : HttpServerResponse.text("Method Not Allowed", { status: 405 });
66 + }
67 + if (
68 + url.value.pathname !== `${PREVIEW_STREAM_ROUTE_PREFIX}/ws` ||
69 + request.headers.upgrade?.toLowerCase() !== "websocket"
70 + ) {
71 + return HttpServerResponse.text("Not Found", { status: 404 });
72 + }
73 + const session = yield* authenticateMediaRequest(AuthOrchestrationReadScope);
74 + const params = url.value.searchParams;
75 + const canOperate =
76 + session.scopes.includes(AuthPreviewOperateScope) && params.get("interactive") !== "false";
77 + const threadId = params.get("threadId") ?? "";
78 + const tabId = params.get("tabId") ?? "";
79 + if (threadId.length === 0 || tabId.length === 0) {
80 + return HttpServerResponse.text("Not Found", { status: 404 });
81 + }
82 + return yield* Effect.scoped(
83 + Effect.gen(function* () {
84 + const attached = yield* browser
85 + .attachViewer({
86 + threadId,
87 + tabId,
88 + canOperate,
89 + maxWidth: intParam(params, "maxWidth", 1280, 7680),
90 + maxHeight: intParam(params, "maxHeight", 800, 4320),
91 + quality: intParam(params, "quality", DEFAULT_QUALITY, 100),
92 + })
93 + .pipe(
94 + Effect.map((viewer) => ({ _tag: "attached" as const, viewer })),
95 + Effect.catchTags({
96 + ServerBrowserTabNotFoundError: () => Effect.succeed({ _tag: "gone" as const }),
97 + ServerBrowserLaunchError: (error) => {
98 + const setup = hostSetup(error.cause);
99 + return setup === undefined
100 + ? Effect.fail(error)
101 + : Effect.succeed({ _tag: "hostSetup" as const, reason: encodeHostSetup(setup) });
102 + },
103 + }),
104 + );
105 + const incoming = NodeHttpServerRequest.toIncomingMessage(request);
106 + // JPEGs are already compressed. Disabling deflate also keeps all
107 + // pending writes in the socket buffer we bound below, not a zlib queue.
108 + delete incoming.headers["sec-websocket-extensions"];
109 + const transport = incoming.socket;
110 + const socket = yield* request.upgrade;
111 + const reader = yield* socket.reader;
112 + const writer = yield* socket.writer;
113 + // A refused upgrade reads as an auth failure to ticket clients, so a
114 + // missing tab is a close code they stop on.
115 + const gone = writer.write(new Socket.CloseEvent(TAB_GONE_CODE, "tab closed"));
116 + if (attached._tag === "gone") {
117 + yield* gone;
118 + return HttpServerResponse.empty();
119 + }
120 + if (attached._tag === "hostSetup") {
121 + yield* writer.write(
122 + new Socket.CloseEvent(PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE, attached.reason),
123 );
136 - const write = (data: Uint8Array | string) =>
137 - Effect.suspend(() => {
138 - const bytes = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength;
139 - if (transport.writableLength + bytes + 14 > MAX_SOCKET_BUFFER_BYTES) {
140 - return disconnectSlowViewer;
124 + return HttpServerResponse.empty();
125 + }
126 + const viewer = attached.viewer;
127 + // `write` returns once the frame is queued, so Chromium's ack for each
128 + // frame waits for the viewer's `ack` message instead. Only one frame
129 + // is on the wire and only the newest waits behind it, so replies never
130 + // queue behind stale images on a slow link.
131 + let inFlight: Effect.Effect<void> | null = null;
132 + let pending: Frame | null = null;
133 + const disconnectSlowViewer = Effect.sync(() => transport.destroy()).pipe(
134 + Effect.andThen(Effect.interrupt),
135 + );
136 + const write = (data: Uint8Array | string) =>
137 + Effect.suspend(() => {
138 + const bytes = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength;
139 + if (transport.writableLength + bytes + 14 > MAX_SOCKET_BUFFER_BYTES) {
140 + return disconnectSlowViewer;
141 + }
142 + return writer.write(data);
143 + });
144 + const sendFrame = (frame: Frame) => {
145 + inFlight = frame.ack;
146 + return write(frame.data);
147 + };
148 + const sendOutput = Queue.take(viewer.output).pipe(
149 + Effect.flatMap((output) => {
150 + switch (output._tag) {
151 + case "frame": {
152 + if (inFlight === null) return sendFrame(output);
153 + const superseded = pending;
154 + pending = output;
155 + // Never sent, but Chromium still waits for its ack.
156 + return superseded ? Effect.forkScoped(superseded.ack) : Effect.void;
157 }
142 - return writer.write(data);
143 - });
144 - const sendFrame = (frame: Frame) => {
145 - inFlight = frame.ack;
146 - return write(frame.data);
147 - };
148 - const sendOutput = Queue.take(viewer.output).pipe(
149 - Effect.flatMap((output) => {
150 - switch (output._tag) {
151 - case "frame": {
152 - if (inFlight === null) return sendFrame(output);
153 - const superseded = pending;
154 - pending = output;
155 - // Never sent, but Chromium still waits for its ack.
156 - return superseded ? Effect.forkScoped(superseded.ack) : Effect.void;
157 - }
158 - case "viewport":
159 - case "control":
160 - case "clipboard":
161 - case "download":
162 - case "fileChooser":
163 - case "fileChooserClosed":
164 - case "popup":
165 - case "pointer":
166 - case "probe": {
167 - const { _tag: type, ...data } = output;
168 - return write(JSON.stringify({ type, ...data }));
169 - }
170 - case "gone":
171 - return gone.pipe(Effect.andThen(Effect.interrupt));
172 - case "reconnect":
173 - return writer
174 - .write(new Socket.CloseEvent(1012, "reconnect"))
175 - .pipe(Effect.andThen(Effect.interrupt));
158 + case "viewport":
159 + case "control":
160 + case "clipboard":
161 + case "download":
162 + case "fileChooser":
163 + case "fileChooserClosed":
164 + case "popup":
165 + case "pointer":
166 + case "probe": {
167 + const { _tag: type, ...data } = output;
168 + return write(JSON.stringify({ type, ...data }));
169 }
177 - }),
178 - );
179 - const receive = (chunk: Uint8Array | string) => {
180 - const message = parseMessage(chunk);
181 - // Ownership serializes actions in the service. Keep reading so dialog
182 - // replies and takeover can unblock an action already waiting on the page.
183 - if (!isAck(message))
184 - return canOperate
185 - ? viewer.input(message).pipe(Effect.forkScoped, Effect.asVoid)
186 - : Effect.void;
187 - const ack = inFlight;
188 - const next = pending;
189 - inFlight = null;
190 - pending = null;
191 - // Forked: Chromium acks are paced and must not hold up input.
192 - return Effect.andThen(
193 - ack ? Effect.forkScoped(ack) : Effect.void,
194 - next ? sendFrame(next) : Effect.void,
195 - );
196 - };
197 - const receiveInput = reader.pull.pipe(
198 - Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })),
170 + case "gone":
171 + return gone.pipe(Effect.andThen(Effect.interrupt));
172 + case "reconnect":
173 + return writer
174 + .write(new Socket.CloseEvent(1012, "reconnect"))
175 + .pipe(Effect.andThen(Effect.interrupt));
176 + }
177 + }),
178 + );
179 + const receive = (chunk: Uint8Array | string) => {
180 + const message = parseMessage(chunk);
181 + // Ownership serializes actions in the service. Keep reading so dialog
182 + // replies and takeover can unblock an action already waiting on the page.
183 + if (!isAck(message))
184 + return canOperate
185 + ? viewer.input(message).pipe(Effect.forkScoped, Effect.asVoid)
186 + : Effect.void;
187 + const ack = inFlight;
188 + const next = pending;
189 + inFlight = null;
190 + pending = null;
191 + // Forked: Chromium acks are paced and must not hold up input.
192 + return Effect.andThen(
193 + ack ? Effect.forkScoped(ack) : Effect.void,
194 + next ? sendFrame(next) : Effect.void,
195 );
200 - return yield* Effect.raceFirst(Effect.forever(sendOutput), Effect.forever(receiveInput));
201 - }),
202 - ).pipe(
203 - Effect.catchTags({
204 - ServerBrowserLaunchError: (error) =>
205 - Effect.logWarning("server preview browser failed to start", { cause: error.cause }).pipe(
206 - Effect.as(HttpServerResponse.text("Service Unavailable", { status: 503 })),
207 - ),
208 - }),
209 - Effect.catch(() => Effect.succeed(HttpServerResponse.empty())),
210 - );
211 - });
196 + };
197 + const receiveInput = reader.pull.pipe(
198 + Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })),
199 + );
200 + return yield* Effect.raceFirst(Effect.forever(sendOutput), Effect.forever(receiveInput));
201 + }),
202 + ).pipe(
203 + Effect.catchTags({
204 + ServerBrowserLaunchError: (error) =>
205 + Effect.logWarning("server preview browser failed to start", { cause: error.cause }).pipe(
206 + Effect.as(HttpServerResponse.text("Service Unavailable", { status: 503 })),
207 + ),
208 + }),
209 + Effect.catch(() => Effect.succeed(HttpServerResponse.empty())),
210 + );
211 +});
212
213 const hostSetup = (cause: unknown): PreviewStreamHostSetup | undefined =>
214 isSandboxError(cause)
@@ -220,28 +220,32 @@ const isSandboxError = Schema.is(PreviewBrowserHost.PreviewBrowserSandboxError);
220 const isLibrariesError = Schema.is(PreviewBrowserHost.PreviewBrowserLibrariesError);
221 const encodeHostSetup = Schema.encodeSync(Schema.fromJsonString(PreviewStreamHostSetup));
222
223 -const serveDownload = (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) =>
224 - Effect.gen(function* () {
225 - yield* authenticateMediaRequest(AuthOrchestrationReadScope);
226 - const download = yield* browser.openDownload({
227 - threadId: params.get("threadId") ?? "",
228 - tabId: params.get("tabId") ?? "",
229 - downloadId: params.get("id") ?? "",
230 - });
231 - if (Option.isNone(download)) return HttpServerResponse.text("Not Found", { status: 404 });
232 - return yield* HttpServerResponse.file(download.value.path, {
233 - headers: assetResponseHeaders(download.value.path, {
234 - download: true,
235 - fileName: download.value.fileName,
236 - }),
237 - });
223 +// The request span already covers this download route.
224 +const serveDownload = Effect.fnUntraced(function* (
225 + browser: ServerBrowser.ServerBrowser["Service"],
226 + params: URLSearchParams,
227 +) {
228 + yield* authenticateMediaRequest(AuthOrchestrationReadScope);
229 + const download = yield* browser.openDownload({
230 + threadId: params.get("threadId") ?? "",
231 + tabId: params.get("tabId") ?? "",
232 + downloadId: params.get("id") ?? "",
233 + });
234 + if (Option.isNone(download)) return HttpServerResponse.text("Not Found", { status: 404 });
235 + return yield* HttpServerResponse.file(download.value.path, {
236 + headers: assetResponseHeaders(download.value.path, {
237 + download: true,
238 + fileName: download.value.fileName,
239 + }),
240 });
241 +});
242
243 const UPLOAD_MAX_FILE_BYTES = 100 * 1024 * 1024;
244 const UPLOAD_MAX_FILES = 20;
245
243 -const receiveUpload = (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) =>
244 - Effect.gen(function* () {
246 +// The request span already covers this upload route.
247 +const receiveUpload = Effect.fnUntraced(
248 + function* (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) {
249 yield* authenticateMediaRequest(AuthPreviewOperateScope);
250 const request = yield* HttpServerRequest.HttpServerRequest;
251 const fs = yield* FileSystem.FileSystem;
@@ -276,7 +280,9 @@ const receiveUpload = (browser: ServerBrowser.ServerBrowser["Service"], params:
280 return answered
281 ? HttpServerResponse.empty({ status: 204 })
282 : HttpServerResponse.text("The page's file picker is no longer open.", { status: 409 });
279 - }).pipe(Effect.scoped);
283 + },
284 + (effect, _browser, _params) => effect.pipe(Effect.scoped),
285 +);
286
287 export const routeLayer = HttpRouter.use((router) =>
288 Effect.gen(function* () {
apps/server/src/serverRuntimeStartup.ts
+301 -302
@@ -109,37 +109,39 @@ export const makeCommandGate = Effect.gen(function* () {
109 );
110 yield* Effect.forkScoped(commandWorker);
111
112 + const enqueueCommand = Effect.fn("serverRuntimeStartup.enqueueCommand")(function* <A, E>(
113 + effect: Effect.Effect<A, E>,
114 + ): Effect.fn.Return<A, E | ServerRuntimeStartupError> {
115 + const readinessState = yield* Ref.get(commandReadinessState);
116 + if (readinessState === "ready") {
117 + return yield* effect;
118 + }
119 + if (readinessState !== "pending") {
120 + return yield* readinessState;
121 + }
122 +
123 + const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
124 + yield* Queue.offer(commandQueue, {
125 + run: Deferred.await(commandReady).pipe(
126 + Effect.flatMap(() => effect),
127 + Effect.exit,
128 + Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
129 + ),
130 + });
131 + return yield* Deferred.await(result);
132 + });
133 +
134 return {
135 awaitCommandReady: Deferred.await(commandReady),
136 signalCommandReady: Effect.gen(function* () {
137 yield* Ref.set(commandReadinessState, "ready");
138 yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
139 }),
118 - failCommandReady: (error) =>
119 - Effect.gen(function* () {
120 - yield* Ref.set(commandReadinessState, error);
121 - yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
122 - }),
123 - enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>
124 - Effect.gen(function* () {
125 - const readinessState = yield* Ref.get(commandReadinessState);
126 - if (readinessState === "ready") {
127 - return yield* effect;
128 - }
129 - if (readinessState !== "pending") {
130 - return yield* readinessState;
131 - }
132 -
133 - const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
134 - yield* Queue.offer(commandQueue, {
135 - run: Deferred.await(commandReady).pipe(
136 - Effect.flatMap(() => effect),
137 - Effect.exit,
138 - Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
139 - ),
140 - });
141 - return yield* Deferred.await(result);
142 - }),
140 + failCommandReady: Effect.fn("serverRuntimeStartup.failCommandReady")(function* (error) {
141 + yield* Ref.set(commandReadinessState, error);
142 + yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
143 + }),
144 + enqueueCommand,
145 } satisfies CommandGate;
146 });
147
@@ -358,21 +360,22 @@ export const logBrowserAutoOpenUnavailable = Effect.logInfo("browser auto-open u
360 hint: "Open the pairing URL above in your browser.",
361 });
362
361 -export const maybeOpenBrowser = (target: string) =>
362 - Effect.gen(function* () {
363 - const serverConfig = yield* ServerConfig.ServerConfig;
364 - if (serverConfig.noBrowser) {
365 - return;
366 - }
367 - const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
363 +export const maybeOpenBrowser = Effect.fn("serverRuntimeStartup.maybeOpenBrowser")(function* (
364 + target: string,
365 +) {
366 + const serverConfig = yield* ServerConfig.ServerConfig;
367 + if (serverConfig.noBrowser) {
368 + return;
369 + }
370 + const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
371
369 - yield* externalLauncher.launchBrowser(target).pipe(
370 - // The target carries the pairing token, and a failed launch records its
371 - // command line on the span, so this call stays out of traces.
372 - Effect.withTracerEnabled(false),
373 - Effect.catch(() => logBrowserAutoOpenUnavailable),
374 - );
375 - });
372 + yield* externalLauncher.launchBrowser(target).pipe(
373 + // The target carries the pairing token, and a failed launch records its
374 + // command line on the span, so this call stays out of traces.
375 + Effect.withTracerEnabled(false),
376 + Effect.catch(() => logBrowserAutoOpenUnavailable),
377 + );
378 +});
379
380 const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
381 effect.pipe(
@@ -413,7 +416,9 @@ export const startEffectWorkerWithRelay = Effect.fn(
416 );
417 });
418
416 -export function runOrderedV2StartupPhases<
419 +export const runOrderedV2StartupPhases = Effect.fn(
420 + "serverRuntimeStartup.runOrderedV2StartupPhases",
421 +)(function* <
422 Import,
423 Recovery,
424 Bootstrap,
@@ -434,292 +439,286 @@ export function runOrderedV2StartupPhases<
439 readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
440 readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
441 }) {
437 - return Effect.gen(function* () {
438 - yield* input.importLegacyShells;
439 - const recovery = yield* input.recover;
440 - yield* input.recoverDelegatedTasks;
441 - yield* input.startEffectWorker;
442 - const bootstrap = yield* input.autoBootstrap;
443 - return { recovery, bootstrap } as const;
444 - });
445 -}
442 + yield* input.importLegacyShells;
443 + const recovery = yield* input.recover;
444 + yield* input.recoverDelegatedTasks;
445 + yield* input.startEffectWorker;
446 + const bootstrap = yield* input.autoBootstrap;
447 + return { recovery, bootstrap } as const;
448 +});
449
447 -const make = (options?: StartupOptions) =>
448 - Effect.gen(function* () {
449 - const serverConfig = yield* ServerConfig.ServerConfig;
450 - const keybindings = yield* Keybindings.Keybindings;
451 - const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
452 - const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
453 - const orchestrator = yield* Orchestrator.OrchestratorV2;
454 - const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
455 - const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
456 - const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
457 - const serverSettings = yield* ServerSettings.ServerSettingsService;
458 - const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
459 - const crypto = yield* Crypto.Crypto;
460 - const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
461 -
462 - const commandGate = yield* makeCommandGate;
463 - const httpListening = yield* Deferred.make<void>();
464 - const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
465 -
466 - yield* Effect.addFinalizer(() =>
467 - Effect.gen(function* () {
468 - yield* commandGate.failCommandReady(
469 - new ServerRuntimeStartupError({
470 - mode: serverConfig.mode,
471 - host: serverConfig.host ?? null,
472 - port: serverConfig.port,
473 - cause: "Server runtime is shutting down.",
474 - }),
475 - );
476 - const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
477 - if (workerFiber !== null) {
478 - yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
479 - }
480 - yield* providerRuntimeRecovery.prepareForShutdown.pipe(
481 - Effect.ensuring(providerSessions.shutdown),
482 - );
483 - const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
484 - yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
485 - }).pipe(
486 - Effect.catchCause((cause) =>
487 - Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
488 - cause: Cause.pretty(cause),
450 +const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: StartupOptions) {
451 + const serverConfig = yield* ServerConfig.ServerConfig;
452 + const keybindings = yield* Keybindings.Keybindings;
453 + const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
454 + const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
455 + const orchestrator = yield* Orchestrator.OrchestratorV2;
456 + const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
457 + const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
458 + const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
459 + const serverSettings = yield* ServerSettings.ServerSettingsService;
460 + const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
461 + const crypto = yield* Crypto.Crypto;
462 + const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
463 +
464 + const commandGate = yield* makeCommandGate;
465 + const httpListening = yield* Deferred.make<void>();
466 + const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
467 +
468 + yield* Effect.addFinalizer(() =>
469 + Effect.gen(function* () {
470 + yield* commandGate.failCommandReady(
471 + new ServerRuntimeStartupError({
472 + mode: serverConfig.mode,
473 + host: serverConfig.host ?? null,
474 + port: serverConfig.port,
475 + cause: "Server runtime is shutting down.",
476 + }),
477 + );
478 + const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
479 + if (workerFiber !== null) {
480 + yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
481 + }
482 + yield* providerRuntimeRecovery.prepareForShutdown.pipe(
483 + Effect.ensuring(providerSessions.shutdown),
484 + );
485 + const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
486 + yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
487 + }).pipe(
488 + Effect.catchCause((cause) =>
489 + Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
490 + cause: Cause.pretty(cause),
491 + }),
492 + ),
493 + ),
494 + );
495 +
496 + const startup = Effect.gen(function* () {
497 + yield* Effect.logDebug("startup phase: starting keybindings runtime");
498 + yield* runStartupPhase(
499 + "keybindings.start",
500 + keybindings.start.pipe(
501 + Effect.catch((error) =>
502 + Effect.logWarning("failed to start keybindings runtime", {
503 + path: error.configPath,
504 + detail: error.detail,
505 + cause: error.cause,
506 }),
507 ),
508 ),
509 );
510
494 - const startup = Effect.gen(function* () {
495 - yield* Effect.logDebug("startup phase: starting keybindings runtime");
496 - yield* runStartupPhase(
497 - "keybindings.start",
498 - keybindings.start.pipe(
499 - Effect.catch((error) =>
500 - Effect.logWarning("failed to start keybindings runtime", {
501 - path: error.configPath,
502 - detail: error.detail,
503 - cause: error.cause,
504 - }),
505 - ),
511 + yield* Effect.logDebug("startup phase: starting server settings runtime");
512 + yield* runStartupPhase(
513 + "settings.start",
514 + serverSettings.start.pipe(
515 + Effect.catch((error) =>
516 + Effect.logWarning("failed to start server settings runtime", {
517 + path: error.settingsPath,
518 + operation: error.operation,
519 + providerInstanceId: error.providerInstanceId,
520 + environmentVariable: error.environmentVariable,
521 + cause: error.cause,
522 + }),
523 ),
507 - );
524 + ),
525 + );
526
509 - yield* Effect.logDebug("startup phase: starting server settings runtime");
510 - yield* runStartupPhase(
511 - "settings.start",
512 - serverSettings.start.pipe(
513 - Effect.catch((error) =>
514 - Effect.logWarning("failed to start server settings runtime", {
515 - path: error.settingsPath,
516 - operation: error.operation,
517 - providerInstanceId: error.providerInstanceId,
518 - environmentVariable: error.environmentVariable,
519 - cause: error.cause,
520 - }),
527 + const welcomeBase = yield* resolveWelcomeBase;
528 + const environment = yield* serverEnvironment.getDescriptor;
529 + const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
530 + if (legacyMigrationThreadCount > 0) {
531 + yield* lifecycleEvents.publish({
532 + version: 1,
533 + type: "legacyThreadMigration",
534 + payload: {
535 + status: "running",
536 + totalThreadCount: legacyMigrationThreadCount,
537 + },
538 + });
539 + }
540 + const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
541 + importLegacyShells: runStartupPhase(
542 + "orchestration-v2.legacy-v1.import-shells",
543 + legacyV1ThreadImporter.reconcileShells.pipe(
544 + Effect.tap((summary) =>
545 + summary.importedThreadCount === 0
546 + ? Effect.void
547 + : Effect.logInfo("Imported legacy v1 thread shells", summary),
548 ),
549 ),
523 - );
550 + ),
551 + recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
552 + recoverDelegatedTasks: runStartupPhase(
553 + "orchestration-v2.delegated-tasks.recover",
554 + orchestrator.recoverDelegatedTasks,
555 + ),
556 + startEffectWorker: runStartupPhase(
557 + "orchestration-v2.effect-worker.start",
558 + startEffectWorkerWithRelay({
559 + runWorker: EffectWorker.runDaemon,
560 + startRelay: agentAwarenessRelay.start(),
561 + workerFiberRef: effectWorkerFiber,
562 + }),
563 + ),
564 + autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
565 + ? runStartupPhase(
566 + "welcome.autobootstrap",
567 + resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),
568 + )
569 + : Effect.succeed({})
570 + ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
571 + });
572 + yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
573 + // Runs after activation: the status check fetches every enabled project's
574 + // remote, and awaiting it here held command readiness for that long.
575 + yield* runStartupPhase(
576 + "projects.auto-pull",
577 + Effect.gen(function* () {
578 + const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells();
579 + const settings = yield* serverSettings.getSettings;
580 + yield* autoPullProjects(projects, settings);
581 + }),
582 + ).pipe(
583 + Effect.catch((cause) =>
584 + Effect.logWarning("Failed to load projects for automatic pull", { cause }),
585 + ),
586 + forkParked,
587 + );
588
525 - const welcomeBase = yield* resolveWelcomeBase;
526 - const environment = yield* serverEnvironment.getDescriptor;
527 - const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
528 - if (legacyMigrationThreadCount > 0) {
529 - yield* lifecycleEvents.publish({
530 - version: 1,
531 - type: "legacyThreadMigration",
532 - payload: {
533 - status: "running",
534 - totalThreadCount: legacyMigrationThreadCount,
535 - },
536 - });
537 - }
538 - const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
539 - importLegacyShells: runStartupPhase(
540 - "orchestration-v2.legacy-v1.import-shells",
541 - legacyV1ThreadImporter.reconcileShells.pipe(
542 - Effect.tap((summary) =>
543 - summary.importedThreadCount === 0
544 - ? Effect.void
545 - : Effect.logInfo("Imported legacy v1 thread shells", summary),
589 + const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
590 + Effect.tap((summary) =>
591 + summary.importedThreadCount === 0
592 + ? Effect.void
593 + : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
594 + ),
595 + );
596 + yield* (
597 + legacyMigrationThreadCount > 0
598 + ? importPendingTranscripts.pipe(
599 + Effect.tap(() =>
600 + lifecycleEvents.publish({
601 + version: 1,
602 + type: "legacyThreadMigration",
603 + payload: {
604 + status: "complete",
605 + totalThreadCount: legacyMigrationThreadCount,
606 + },
607 + }),
608 ),
547 - ),
548 - ),
549 - recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
550 - recoverDelegatedTasks: runStartupPhase(
551 - "orchestration-v2.delegated-tasks.recover",
552 - orchestrator.recoverDelegatedTasks,
553 - ),
554 - startEffectWorker: runStartupPhase(
555 - "orchestration-v2.effect-worker.start",
556 - startEffectWorkerWithRelay({
557 - runWorker: EffectWorker.runDaemon,
558 - startRelay: agentAwarenessRelay.start(),
559 - workerFiberRef: effectWorkerFiber,
560 - }),
561 - ),
562 - autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
563 - ? runStartupPhase(
564 - "welcome.autobootstrap",
565 - resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)),
566 - )
567 - : Effect.succeed({})
568 - ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
569 - });
570 - yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
571 - // Runs after activation: the status check fetches every enabled project's
572 - // remote, and awaiting it here held command readiness for that long.
573 - yield* runStartupPhase(
574 - "projects.auto-pull",
575 - Effect.gen(function* () {
576 - const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells();
577 - const settings = yield* serverSettings.getSettings;
578 - yield* autoPullProjects(projects, settings);
579 - }),
580 - ).pipe(
581 - Effect.catch((cause) =>
582 - Effect.logWarning("Failed to load projects for automatic pull", { cause }),
583 - ),
584 - forkParked,
585 - );
609 + )
610 + : importPendingTranscripts
611 + ).pipe(forkParked);
612
587 - const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
588 - Effect.tap((summary) =>
589 - summary.importedThreadCount === 0
590 - ? Effect.void
591 - : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
592 - ),
593 - );
594 - yield* (
595 - legacyMigrationThreadCount > 0
596 - ? importPendingTranscripts.pipe(
597 - Effect.tap(() =>
598 - lifecycleEvents.publish({
599 - version: 1,
600 - type: "legacyThreadMigration",
601 - payload: {
602 - status: "complete",
603 - totalThreadCount: legacyMigrationThreadCount,
604 - },
605 - }),
606 - ),
607 - )
608 - : importPendingTranscripts
609 - ).pipe(forkParked);
610 -
611 - yield* forkParked(
612 - Effect.gen(function* () {
613 - yield* Effect.logDebug("startup phase: recording startup heartbeat");
614 - yield* recordStartupHeartbeat.pipe(
615 - Effect.withSpan("server.startup.heartbeat.record", {
616 - attributes: { "startup.phase": "heartbeat.record" },
617 - }),
618 - Effect.ignoreCause({ log: true }),
613 + yield* forkParked(
614 + Effect.gen(function* () {
615 + yield* Effect.logDebug("startup phase: recording startup heartbeat");
616 + yield* recordStartupHeartbeat.pipe(
617 + Effect.withSpan("server.startup.heartbeat.record", {
618 + attributes: { "startup.phase": "heartbeat.record" },
619 + }),
620 + Effect.ignoreCause({ log: true }),
621 + );
622 + if (serverConfig.startupPresentation === "headless") {
623 + yield* Effect.logDebug("startup phase: headless access info");
624 + const accessInfo = yield* issueHeadlessServeAccessInfo();
625 + yield* runStartupPhase(
626 + "headless.output",
627 + Console.log(formatHeadlessServeOutput(accessInfo)),
628 );
620 - if (serverConfig.startupPresentation === "headless") {
621 - yield* Effect.logDebug("startup phase: headless access info");
622 - const accessInfo = yield* issueHeadlessServeAccessInfo();
623 - yield* runStartupPhase(
624 - "headless.output",
625 - Console.log(formatHeadlessServeOutput(accessInfo)),
626 - );
627 - } else {
628 - yield* Effect.logDebug("startup phase: browser open check");
629 - const startupBrowserTarget = yield* resolveStartupBrowserTarget;
630 - if (serverConfig.mode !== "desktop") {
631 - yield* announceStartupPairingUrl(startupBrowserTarget);
632 - }
633 - yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
629 + } else {
630 + yield* Effect.logDebug("startup phase: browser open check");
631 + const startupBrowserTarget = yield* resolveStartupBrowserTarget;
632 + if (serverConfig.mode !== "desktop") {
633 + yield* announceStartupPairingUrl(startupBrowserTarget);
634 }
635 - }),
636 - );
637 -
638 - yield* Effect.logDebug("startup phase: waiting for http listener");
639 - yield* runStartupPhase("http.wait", Deferred.await(httpListening));
640 - yield* runStartupPhase(
641 - "auxiliary-roots.parked",
642 - options?.awaitAuxiliaryParked ?? Effect.void,
643 - );
635 + yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
636 + }
637 + }),
638 + );
639
645 - const updateOutcome = yield* launcher.prepareTrial;
640 + yield* Effect.logDebug("startup phase: waiting for http listener");
641 + yield* runStartupPhase("http.wait", Deferred.await(httpListening));
642 + yield* runStartupPhase("auxiliary-roots.parked", options?.awaitAuxiliaryParked ?? Effect.void);
643
647 - yield* Effect.logDebug("startup phase: publishing welcome event", {
648 - environmentId: environment.environmentId,
649 - cwd: welcomeBase.cwd,
650 - projectName: welcomeBase.projectName,
651 - bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
652 - bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
653 - });
654 - yield* runStartupPhase(
655 - "welcome.publish",
656 - lifecycleEvents.publish({
657 - version: 1,
658 - type: "welcome",
659 - payload: {
660 - environment,
661 - ...welcomeBase,
662 - ...bootstrapTargets,
663 - },
664 - }),
665 - );
644 + const updateOutcome = yield* launcher.prepareTrial;
645
667 - yield* options?.activate ?? Effect.void;
668 - yield* Effect.logDebug("Accepting commands");
669 - yield* commandGate.signalCommandReady;
670 - yield* Effect.logDebug("startup phase: publishing ready event");
671 - yield* runStartupPhase(
672 - "ready.publish",
673 - lifecycleEvents.publish({
674 - version: 1,
675 - type: "ready",
676 - payload: {
677 - at: DateTime.formatIso(yield* DateTime.now),
678 - environment,
679 - ...(updateOutcome === undefined ? {} : { updateOutcome }),
680 - },
681 - }),
682 - );
683 - yield* Effect.logDebug("startup phase: complete");
684 - yield* flushCompileCache;
685 - }).pipe(
686 - Effect.withSpan("server.startup", {
687 - kind: "server",
688 - root: true,
689 - attributes: {
690 - "server.mode": serverConfig.mode,
691 - "server.port": serverConfig.port,
692 - "server.host": serverConfig.host ?? "default",
646 + yield* Effect.logDebug("startup phase: publishing welcome event", {
647 + environmentId: environment.environmentId,
648 + cwd: welcomeBase.cwd,
649 + projectName: welcomeBase.projectName,
650 + bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
651 + bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
652 + });
653 + yield* runStartupPhase(
654 + "welcome.publish",
655 + lifecycleEvents.publish({
656 + version: 1,
657 + type: "welcome",
658 + payload: {
659 + environment,
660 + ...welcomeBase,
661 + ...bootstrapTargets,
662 },
663 }),
664 );
665
697 - yield* Effect.forkScoped(
698 - Effect.exit(startup).pipe(
699 - Effect.flatMap((startupExit) => {
700 - if (Exit.isSuccess(startupExit)) return Effect.void;
701 - const error = new ServerRuntimeStartupError({
702 - mode: serverConfig.mode,
703 - host: serverConfig.host ?? null,
704 - port: serverConfig.port,
705 - cause: startupExit.cause,
706 - });
707 - return Effect.logError("server runtime startup failed", {
708 - cause: Cause.pretty(startupExit.cause),
709 - }).pipe(
710 - Effect.andThen(commandGate.failCommandReady(error)),
711 - Effect.andThen(options?.abort?.(error) ?? Effect.void),
712 - );
713 - }),
714 - ),
666 + yield* options?.activate ?? Effect.void;
667 + yield* Effect.logDebug("Accepting commands");
668 + yield* commandGate.signalCommandReady;
669 + yield* Effect.logDebug("startup phase: publishing ready event");
670 + yield* runStartupPhase(
671 + "ready.publish",
672 + lifecycleEvents.publish({
673 + version: 1,
674 + type: "ready",
675 + payload: {
676 + at: DateTime.formatIso(yield* DateTime.now),
677 + environment,
678 + ...(updateOutcome === undefined ? {} : { updateOutcome }),
679 + },
680 + }),
681 );
682 + yield* Effect.logDebug("startup phase: complete");
683 + yield* flushCompileCache;
684 + }).pipe(
685 + Effect.withSpan("server.startup", {
686 + kind: "server",
687 + root: true,
688 + attributes: {
689 + "server.mode": serverConfig.mode,
690 + "server.port": serverConfig.port,
691 + "server.host": serverConfig.host ?? "default",
692 + },
693 + }),
694 + );
695
717 - return {
718 - awaitCommandReady: commandGate.awaitCommandReady,
719 - markHttpListening: Deferred.succeed(httpListening, undefined),
720 - enqueueCommand: commandGate.enqueueCommand,
721 - } satisfies ServerRuntimeStartup["Service"];
722 - });
696 + yield* Effect.forkScoped(
697 + Effect.exit(startup).pipe(
698 + Effect.flatMap((startupExit) => {
699 + if (Exit.isSuccess(startupExit)) return Effect.void;
700 + const error = new ServerRuntimeStartupError({
701 + mode: serverConfig.mode,
702 + host: serverConfig.host ?? null,
703 + port: serverConfig.port,
704 + cause: startupExit.cause,
705 + });
706 + return Effect.logError("server runtime startup failed", {
707 + cause: Cause.pretty(startupExit.cause),
708 + }).pipe(
709 + Effect.andThen(commandGate.failCommandReady(error)),
710 + Effect.andThen(options?.abort?.(error) ?? Effect.void),
711 + );
712 + }),
713 + ),
714 + );
715 +
716 + return {
717 + awaitCommandReady: commandGate.awaitCommandReady,
718 + markHttpListening: Deferred.succeed(httpListening, undefined),
719 + enqueueCommand: commandGate.enqueueCommand,
720 + } satisfies ServerRuntimeStartup["Service"];
721 +});
722
723 export const layerWithOptions = (options?: StartupOptions) =>
724 Layer.effect(ServerRuntimeStartup, make(options));
apps/server/src/ws.ts
+140 -131
@@ -279,24 +279,23 @@ type EditorDiscovery = Pick<
279 "resolveAvailableEditors" | "resolveFileManagerRevealKind"
280 >;
281
282 -const resolveEditorConfig = <E, R>(
282 +const resolveEditorConfig = Effect.fn("ws.resolveEditorConfig")(function* <E, R>(
283 availableEditors: ReadonlyArray<EditorId>,
284 revealKind: Effect.Effect<FileManagerRevealKind | undefined, E, R>,
285 -) =>
286 - Effect.gen(function* () {
287 - const fileManagerRevealKind = availableEditors.includes("file-manager")
288 - ? yield* revealKind
289 - : undefined;
290 - return {
291 - availableEditors,
292 - ...(fileManagerRevealKind === undefined
293 - ? {}
294 - : {
295 - shellRevealInFileManager: true,
296 - shellRevealInFileManagerKind: fileManagerRevealKind,
297 - }),
298 - };
299 - });
285 +) {
286 + const fileManagerRevealKind = availableEditors.includes("file-manager")
287 + ? yield* revealKind
288 + : undefined;
289 + return {
290 + availableEditors,
291 + ...(fileManagerRevealKind === undefined
292 + ? {}
293 + : {
294 + shellRevealInFileManager: true,
295 + shellRevealInFileManagerKind: fileManagerRevealKind,
296 + }),
297 + };
298 +});
299
300 export const withLateEditorConfig = <E, R>(
301 config: ClientServerConfig,
@@ -1642,64 +1641,63 @@ const layerWsRpc = (
1641 ),
1642 );
1643
1645 - const loadServerConfig = (options: { readonly usageLimitsCommand: boolean }) =>
1646 - Effect.gen(function* () {
1647 - const keybindingsConfig = yield* keybindings.loadConfigState;
1648 - const currentProviders = yield* providerRegistry.getProviders;
1649 - const providers = options.usageLimitsCommand
1650 - ? withUsageLimitsCommands(currentProviders, yield* usageLimitSources.current)
1651 - : currentProviders;
1652 - const settings = ServerSettings.redactServerSettingsForClient(
1653 - yield* serverSettings.getSettings,
1654 - );
1655 - const environment = yield* serverEnvironment.getDescriptor;
1656 - const auth = yield* serverAuth.getDescriptor();
1657 - const scratchWorkspaceRoot = yield* managedFolders.scratchRoot;
1658 - const editorConfig = yield* resolveEditorConfig(
1659 - yield* resolveAvailableEditorsForConfig(externalLauncher.resolveAvailableEditors()),
1660 - resolveFileManagerRevealKindForConfig(externalLauncher.resolveFileManagerRevealKind()),
1661 - );
1644 + const loadServerConfig = Effect.fn("ws.loadServerConfig")(function* (options: {
1645 + readonly usageLimitsCommand: boolean;
1646 + }) {
1647 + const keybindingsConfig = yield* keybindings.loadConfigState;
1648 + const currentProviders = yield* providerRegistry.getProviders;
1649 + const providers = options.usageLimitsCommand
1650 + ? withUsageLimitsCommands(currentProviders, yield* usageLimitSources.current)
1651 + : currentProviders;
1652 + const settings = ServerSettings.redactServerSettingsForClient(
1653 + yield* serverSettings.getSettings,
1654 + );
1655 + const environment = yield* serverEnvironment.getDescriptor;
1656 + const auth = yield* serverAuth.getDescriptor();
1657 + const scratchWorkspaceRoot = yield* managedFolders.scratchRoot;
1658 + const editorConfig = yield* resolveEditorConfig(
1659 + yield* resolveAvailableEditorsForConfig(externalLauncher.resolveAvailableEditors()),
1660 + resolveFileManagerRevealKindForConfig(externalLauncher.resolveFileManagerRevealKind()),
1661 + );
1662
1663 - return {
1664 - environment,
1665 - auth,
1666 - cwd: config.cwd,
1667 - keybindingsConfigPath: config.keybindingsConfigPath,
1668 - keybindings: keybindingsConfig.keybindings,
1669 - issues: keybindingsConfig.issues,
1670 - providers,
1671 - ...editorConfig,
1672 - remoteOpenTargets: yield* resolveAvailableEditorsForConfig(
1673 - remoteOpenTargets.resolveTargets(),
1674 - ),
1675 - directEndpoints: yield* resolveAvailableEditorsForConfig(directEndpoints.resolve()),
1676 - observability: {
1677 - logsDirectoryPath: config.logsDir,
1678 - localTracingEnabled: true,
1679 - ...(config.otlpTracesUrl !== undefined
1680 - ? { otlpTracesUrl: config.otlpTracesUrl }
1681 - : {}),
1682 - otlpTracesEnabled: config.otlpTracesUrl !== undefined,
1683 - ...(config.otlpMetricsUrl !== undefined
1684 - ? { otlpMetricsUrl: config.otlpMetricsUrl }
1685 - : {}),
1686 - otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,
1687 - ...(config.otlpLogsUrl !== undefined ? { otlpLogsUrl: config.otlpLogsUrl } : {}),
1688 - otlpLogsEnabled: config.otlpLogsUrl !== undefined,
1689 - },
1690 - settings,
1691 - shellResumeCompletionMarker: true,
1692 - threadResumeCompletionMarker: true,
1693 - threadSnapshotPagination: true,
1694 - threadFind: true,
1695 - threadFindProgressive: true,
1696 - ...Option.match(scratchWorkspaceRoot, {
1697 - onNone: () => ({}),
1698 - onSome: (root) => ({ scratchWorkspaceRoot: root }),
1699 - }),
1700 - newProjectsRoot: managedFolders.namedProjectsRoot,
1701 - };
1702 - });
1663 + return {
1664 + environment,
1665 + auth,
1666 + cwd: config.cwd,
1667 + keybindingsConfigPath: config.keybindingsConfigPath,
1668 + keybindings: keybindingsConfig.keybindings,
1669 + issues: keybindingsConfig.issues,
1670 + providers,
1671 + ...editorConfig,
1672 + remoteOpenTargets: yield* resolveAvailableEditorsForConfig(
1673 + remoteOpenTargets.resolveTargets(),
1674 + ),
1675 + directEndpoints: yield* resolveAvailableEditorsForConfig(directEndpoints.resolve()),
1676 + observability: {
1677 + logsDirectoryPath: config.logsDir,
1678 + localTracingEnabled: true,
1679 + ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),
1680 + otlpTracesEnabled: config.otlpTracesUrl !== undefined,
1681 + ...(config.otlpMetricsUrl !== undefined
1682 + ? { otlpMetricsUrl: config.otlpMetricsUrl }
1683 + : {}),
1684 + otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,
1685 + ...(config.otlpLogsUrl !== undefined ? { otlpLogsUrl: config.otlpLogsUrl } : {}),
1686 + otlpLogsEnabled: config.otlpLogsUrl !== undefined,
1687 + },
1688 + settings,
1689 + shellResumeCompletionMarker: true,
1690 + threadResumeCompletionMarker: true,
1691 + threadSnapshotPagination: true,
1692 + threadFind: true,
1693 + threadFindProgressive: true,
1694 + ...Option.match(scratchWorkspaceRoot, {
1695 + onNone: () => ({}),
1696 + onSome: (root) => ({ scratchWorkspaceRoot: root }),
1697 + }),
1698 + newProjectsRoot: managedFolders.namedProjectsRoot,
1699 + };
1700 + });
1701
1702 const refreshGitStatus = (cwd: string) =>
1703 vcsStatusBroadcaster
@@ -2150,8 +2148,9 @@ const layerWsRpc = (
2148 }),
2149 ),
2150 ),
2153 - [WS_METHODS.serverRefreshProviders]: (input) =>
2154 - Effect.gen(function* () {
2151 + [WS_METHODS.serverRefreshProviders]:
2152 + /* Request instrumentation already owns the span; keep this helper in that context. */
2153 + Effect.fnUntraced(function* (input) {
2154 if (input.refreshModels) {
2155 yield* modelManifest.forceRefresh;
2156 const instances = yield* providerInstances.listInstances;
@@ -2225,59 +2224,65 @@ const layerWsRpc = (
2224 [WS_METHODS.mcpAppsToolInfo]: (input) => mcpAppRequests.toolInfo(input),
2225 [WS_METHODS.mcpAppsUpdateModelContext]: (input) => mcpAppRequests.updateModelContext(input),
2226 [WS_METHODS.mcpAppsReadResource]: (input) => mcpAppRequests.readResource(input),
2228 - [WS_METHODS.providerUploadFeedback]: (input) =>
2229 - Effect.gen(function* () {
2230 - const projection = yield* threadManagement.getThreadRecords(input.threadId, [
2231 - "providerThreads",
2232 - ]);
2233 - const providerThread =
2234 - projection.providerThreads.find(
2235 - (candidate) => candidate.id === projection.thread.activeProviderThreadId,
2236 - ) ?? projection.providerThreads.at(-1);
2237 - const providerSessionId = providerThread?.providerSessionId ?? null;
2238 - if (providerThread === undefined || providerSessionId === null) {
2239 - return yield* Effect.fail(
2240 - new ProviderUploadFeedbackError({
2241 - threadId: input.threadId,
2242 - cause: "No provider session has run in this thread yet.",
2243 - }),
2244 - );
2245 - }
2246 - const runtime = Option.getOrNull(yield* providerSessionsV2.get(providerSessionId));
2247 - if (runtime === null) {
2248 - return yield* Effect.fail(
2249 - new ProviderUploadFeedbackError({
2250 - threadId: input.threadId,
2251 - cause: "The provider session is no longer running. Send a message first.",
2252 - }),
2253 - );
2254 - }
2255 - if (runtime.uploadFeedback === undefined) {
2256 - return yield* Effect.fail(
2257 - new ProviderUploadFeedbackError({
2258 - threadId: input.threadId,
2259 - cause: `Provider '${runtime.driver}' does not support feedback uploads.`,
2260 - }),
2261 - );
2262 - }
2263 - return yield* runtime.uploadFeedback({
2264 - providerThread,
2265 - ...(input.reason === undefined ? {} : { reason: input.reason }),
2266 - });
2267 - }).pipe(
2268 - Effect.mapError((cause) =>
2269 - isProviderUploadFeedbackError(cause)
2270 - ? cause
2271 - : new ProviderUploadFeedbackError({
2227 + [WS_METHODS.providerUploadFeedback]:
2228 + /* Request instrumentation already owns the span; keep this helper in that context. */
2229 + Effect.fnUntraced(
2230 + function* (input) {
2231 + const projection = yield* threadManagement.getThreadRecords(input.threadId, [
2232 + "providerThreads",
2233 + ]);
2234 + const providerThread =
2235 + projection.providerThreads.find(
2236 + (candidate) => candidate.id === projection.thread.activeProviderThreadId,
2237 + ) ?? projection.providerThreads.at(-1);
2238 + const providerSessionId = providerThread?.providerSessionId ?? null;
2239 + if (providerThread === undefined || providerSessionId === null) {
2240 + return yield* Effect.fail(
2241 + new ProviderUploadFeedbackError({
2242 threadId: input.threadId,
2273 - cause,
2243 + cause: "No provider session has run in this thread yet.",
2244 }),
2275 - ),
2245 + );
2246 + }
2247 + const runtime = Option.getOrNull(yield* providerSessionsV2.get(providerSessionId));
2248 + if (runtime === null) {
2249 + return yield* Effect.fail(
2250 + new ProviderUploadFeedbackError({
2251 + threadId: input.threadId,
2252 + cause: "The provider session is no longer running. Send a message first.",
2253 + }),
2254 + );
2255 + }
2256 + if (runtime.uploadFeedback === undefined) {
2257 + return yield* Effect.fail(
2258 + new ProviderUploadFeedbackError({
2259 + threadId: input.threadId,
2260 + cause: `Provider '${runtime.driver}' does not support feedback uploads.`,
2261 + }),
2262 + );
2263 + }
2264 + return yield* runtime.uploadFeedback({
2265 + providerThread,
2266 + ...(input.reason === undefined ? {} : { reason: input.reason }),
2267 + });
2268 + },
2269 + (effect, input) =>
2270 + effect.pipe(
2271 + Effect.mapError((cause) =>
2272 + isProviderUploadFeedbackError(cause)
2273 + ? cause
2274 + : new ProviderUploadFeedbackError({
2275 + threadId: input.threadId,
2276 + cause,
2277 + }),
2278 + ),
2279 + ),
2280 ),
2281 [WS_METHODS.serverUpdateProvider]: (input) =>
2282 providerMaintenanceRunner.updateProvider(input),
2279 - [WS_METHODS.providerConsumeResetCredit]: (input) =>
2280 - Effect.gen(function* () {
2283 + [WS_METHODS.providerConsumeResetCredit]:
2284 + /* Request instrumentation already owns the span; keep this helper in that context. */
2285 + Effect.fnUntraced(function* (input) {
2286 if ("sourceId" in input) return yield* usageLimitSources.consumeResetCredit(input);
2287 const instance = yield* providerInstances.getInstance(input.instanceId);
2288 if (instance === undefined || !instance.enabled) {
@@ -2332,13 +2337,15 @@ const layerWsRpc = (
2337 ServerSelfUpdate.updateProgressStream(serverSelfUpdate, input),
2338 [WS_METHODS.serverCommitDesktopUpdate]: (input) =>
2339 serverSelfUpdate.commitDesktopUpdate(input.requestId),
2335 - [WS_METHODS.serverUpsertKeybinding]: (rule) =>
2336 - Effect.gen(function* () {
2340 + [WS_METHODS.serverUpsertKeybinding]:
2341 + /* Request instrumentation already owns the span; keep this helper in that context. */
2342 + Effect.fnUntraced(function* (rule) {
2343 const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
2344 return { keybindings: keybindingsConfig, issues: [] };
2345 }),
2340 - [WS_METHODS.serverRemoveKeybinding]: (rule) =>
2341 - Effect.gen(function* () {
2346 + [WS_METHODS.serverRemoveKeybinding]:
2347 + /* Request instrumentation already owns the span; keep this helper in that context. */
2348 + Effect.fnUntraced(function* (rule) {
2349 const keybindingsConfig = yield* keybindings.removeKeybindingRule(rule);
2350 return { keybindings: keybindingsConfig, issues: [] };
2351 }),
@@ -2347,8 +2354,9 @@ const layerWsRpc = (
2354 [WS_METHODS.serverGetDatabaseStorage]: () => databaseStorage.status,
2355 [WS_METHODS.serverGetSettings]: (_input) =>
2356 serverSettings.getSettings.pipe(Effect.map(ServerSettings.redactServerSettingsForClient)),
2350 - [WS_METHODS.serverUpdateSettings]: ({ patch, providerInstanceMutation }) =>
2351 - Effect.gen(function* () {
2357 + [WS_METHODS.serverUpdateSettings]:
2358 + /* Request instrumentation already owns the span; keep this helper in that context. */
2359 + Effect.fnUntraced(function* ({ patch, providerInstanceMutation }) {
2360 const deviceHosts = patch.deviceHosts
2361 ? yield* remoteSshDeviceHosts(patch.deviceHosts).pipe(
2362 Effect.provide(deviceHostContext),
@@ -2659,8 +2667,9 @@ const layerWsRpc = (
2667 [WS_METHODS.agentSessionsScan]: () => agentSessionScanner.scan,
2668 [WS_METHODS.agentSessionsImport]: (input) =>
2669 agentSessionImporter.importRecentAgentThreads(input),
2662 - [WS_METHODS.assetsCreateUrl]: (input) =>
2663 - Effect.gen(function* () {
2670 + [WS_METHODS.assetsCreateUrl]:
2671 + /* Request instrumentation already owns the span; keep this helper in that context. */
2672 + Effect.fnUntraced(function* (input) {
2673 const path = yield* Path.Path;
2674 if (
2675 input.resource._tag === "attachment" ||