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

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

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

Synced Nov 21, 03:37 UTC

main
ts 3,840 lines 153 KB
Raw
1 import {
2 CommandId,
3 type RunId,
4 isProviderAvailable,
5 MessageId,
6 type ModelSelection,
7 NodeId,
8 ORCHESTRATOR_MCP_RUNNING_TASK_NEXT,
9 TurnItemId,
10 type OrchestrationV2Run,
11 type OrchestrationV2Subagent,
12 type OrchestrationV2ThreadProjection,
13 type OrchestrationV2ThreadShell,
14 type OrchestrationV2ThreadLaunchWorkspaceStrategy,
15 type OrchestrationV2TurnItem,
16 OrchestratorMcpFailure,
17 type OrchestratorMcpCapabilitiesInput,
18 type OrchestratorMcpCapabilitiesResult,
19 type OrchestratorMcpModelOption,
20 type OrchestratorMcpCreateThreadsInput,
21 type OrchestratorMcpCreateThreadsResult,
22 type OrchestratorMcpCreatedThread,
23 type OrchestratorMcpDelegateTaskInput,
24 type OrchestratorMcpDelegateTaskResult,
25 type OrchestratorMcpDeleteScheduledTaskInput,
26 type OrchestratorMcpRequestSecretInput,
27 type OrchestratorMcpRequestSecretResult,
28 type OrchestratorMcpDeleteScheduledTaskResult,
29 type OrchestratorMcpListScheduledTasksResult,
30 type OrchestratorMcpScheduledTask,
31 type OrchestratorMcpScheduleTaskInput,
32 type OrchestratorMcpScheduleTaskResult,
33 type OrchestratorMcpTarget,
34 type OrchestratorMcpTaskCancelInput,
35 type OrchestratorMcpTaskCancelResult,
36 type OrchestratorMcpUpdateScheduledTaskInput,
37 type OrchestratorMcpListScheduledTasksInput,
38 type ProjectId,
39 type OrchestratorMcpThreadDetail,
40 type OrchestratorMcpThreadInterruptInput,
41 type OrchestratorMcpThreadInterruptResult,
42 type OrchestratorMcpThreadListInput,
43 type OrchestratorMcpThreadListItem,
44 type OrchestratorMcpThreadListResult,
45 type OrchestratorMcpThreadReadInput,
46 type OrchestratorMcpThreadReadResult,
47 type OrchestratorMcpThreadRun,
48 type OrchestratorMcpThreadSendInput,
49 type OrchestratorMcpThreadSendResult,
50 type OrchestratorMcpThreadTimelineItem,
51 type OrchestratorMcpThreadWaitInput,
52 type OrchestratorMcpThreadWaitResult,
53 type ProviderInteractionMode,
54 type ProviderOptionDescriptor,
55 type ProviderOptionSelection,
56 ProviderRequestKind,
57 type RuntimeMode,
58 type ScheduledTask,
59 type ScheduledTaskUpsertInput,
60 scheduledTaskThreadMode,
61 type ServerProvider,
62 type ServerProviderModel,
63 ThreadId,
64 isOrchestrationV2WorkActive,
65 latestProviderTurnForAttempt,
66 resolveProjectProviderInstanceEnabled,
67 SECRET_REQUEST_UNSAVED_NOTE,
68 } from "@t3tools/contracts";
69 import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model";
70 import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
71 import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
72 import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
73 import { formatThreadLink } from "@t3tools/shared/threadLinks";
74 import { threadPullRequestUpdatedAtMs } from "@t3tools/shared/threadPullRequests";
75 import {
76 normalizeThreadPullRequestKey,
77 visibleThreadPullRequests,
78 } from "../sourceControl/threadPullRequests.ts";
79 import * as Clock from "effect/Clock";
80 import * as Context from "effect/Context";
81 import * as SecureRandom from "effect/crypto/SecureRandom";
82 import * as DateTime from "effect/DateTime";
83 import * as Duration from "effect/Duration";
84 import * as Effect from "effect/Effect";
85 import * as Exit from "effect/Exit";
86 import * as Layer from "effect/Layer";
87 import * as Option from "effect/Option";
88 import * as Ref from "effect/Ref";
89 import * as Schema from "effect/Schema";
90 import * as Stream from "effect/Stream";
91
92 import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
93 import {
94 subagentResultForRun,
95 delegatedTaskProgress,
96 delegatedTaskReportRuns,
97 } from "@t3tools/provider-core/server/subagentProjection";
98 import {
99 DispatchModeLimit,
100 type DispatchModeRefusal,
101 } from "../orchestration-v2/DispatchModeLimit.ts";
102 import type {
103 ProjectionRecordField,
104 ProjectionRecordFilter,
105 } from "../orchestration-v2/ProjectionStore.ts";
106 import {
107 delegatedTaskAwaitsWork,
108 delegatedTaskResultRun,
109 delegatedTaskRuns,
110 runOutcome,
111 } from "../orchestration-v2/RestartBackgroundNote.ts";
112 import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
113 import { placeholderThreadTitle } from "../orchestration-v2/placeholderThreadTitle.ts";
114 import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
115 import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
116 import { isSnoozed } from "../orchestration-v2/ThreadSettlementService.ts";
117 import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts";
118 import * as ProjectService from "../project/ProjectService.ts";
119 import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
120 import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
121 import * as ServerSettings from "../serverSettings.ts";
122 import {
123 clientModeCeiling,
124 type McpInvocationScope,
125 type McpThreadInvocationScope,
126 requireThreadScope,
127 threadLinkFor,
128 } from "./McpInvocationContext.ts";
129 import * as Metrics from "../observability/Metrics.ts";
130 import {
131 interactionModeRank,
132 resolveInteractionMode,
133 resolveRuntimeMode,
134 runtimeModeRank,
135 taskPrompt,
136 } from "./delegatedTaskModes.ts";
137 import { assertTargetWithinLimits, isLiveCallerShell, threadNotFound } from "./threadAccess.ts";
138 import * as SecretRequests from "../secrets/SecretRequests.ts";
139 import * as PeerForwarding from "../peer/PeerForwarding.ts";
140 import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
141
142 // Return recoverable handles before common MCP client timeouts expire.
143 const DEFAULT_WAIT_TIMEOUT_MS = 30_000;
144 const MAX_WAIT_TIMEOUT_MS = 45_000;
145 const DEFAULT_SECRET_REQUEST_TIMEOUT_MS = 10 * 60 * 1_000;
146 const MAX_SECRET_REQUEST_TIMEOUT_MS = 60 * 60 * 1_000;
147 const TASK_WAKE_EVENTS = [
148 { thread: "parent", eventType: "subagent.updated" },
149 { thread: "child", eventType: "run.updated" },
150 { thread: "child", eventType: "subagent.updated" },
151 { thread: "child", eventType: "provider-thread.updated" },
152 { thread: "child", eventType: "runtime-request.updated" },
153 ] as const;
154 const SECRET_REQUEST_POLL_INTERVAL_MS = 500;
155 const DEFAULT_THREAD_LIST_LIMIT = 10;
156 const DEFAULT_THREAD_READ_LIMIT = 10;
157 const DEFAULT_THREAD_RUN_LIMIT = 10;
158 const DEFAULT_THREAD_ITEM_MAX_CHARS = 500;
159 const THREAD_PULL_REQUEST_PREVIEW_LIMIT = 5;
160 // Claude Code saves MCP results over ~25k tokens to a file instead of showing them. Bytes, not
161 // chars: CJK text runs near one token per char, which a char budget lets through at 30k tokens.
162 const THREAD_READ_RESULT_MAX_BYTES = 30_000;
163
164 interface ResolvedTarget {
165 readonly modelSelection: ModelSelection;
166 readonly supportedRuntimeModes: ReadonlyArray<RuntimeMode> | undefined;
167 }
168
169 type TerminalTaskStatus = Extract<
170 OrchestratorMcpDelegateTaskResult["status"],
171 "completed" | "failed" | "cancelled" | "interrupted"
172 >;
173
174 export interface OrchestratorMcpServiceShape {
175 readonly capabilities: (
176 scope: McpInvocationScope,
177 input?: OrchestratorMcpCapabilitiesInput,
178 ) => Effect.Effect<OrchestratorMcpCapabilitiesResult, OrchestratorMcpFailure>;
179 readonly delegateTask: (
180 scope: McpInvocationScope,
181 input: OrchestratorMcpDelegateTaskInput,
182 ) => Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure>;
183 readonly taskStatus: (
184 scope: McpInvocationScope,
185 taskId: NodeId,
186 ) => Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure>;
187 readonly cancelTask: (
188 scope: McpInvocationScope,
189 input: OrchestratorMcpTaskCancelInput,
190 ) => Effect.Effect<OrchestratorMcpTaskCancelResult, OrchestratorMcpFailure>;
191 readonly createThreads: (
192 scope: McpInvocationScope,
193 input: OrchestratorMcpCreateThreadsInput,
194 ) => Effect.Effect<OrchestratorMcpCreateThreadsResult, OrchestratorMcpFailure>;
195 readonly scheduleTask: (
196 scope: McpInvocationScope,
197 input: OrchestratorMcpScheduleTaskInput,
198 ) => Effect.Effect<OrchestratorMcpScheduleTaskResult, OrchestratorMcpFailure>;
199 readonly listScheduledTasks: (
200 scope: McpInvocationScope,
201 input: OrchestratorMcpListScheduledTasksInput,
202 ) => Effect.Effect<OrchestratorMcpListScheduledTasksResult, OrchestratorMcpFailure>;
203 readonly updateScheduledTask: (
204 scope: McpInvocationScope,
205 input: OrchestratorMcpUpdateScheduledTaskInput,
206 ) => Effect.Effect<OrchestratorMcpScheduleTaskResult, OrchestratorMcpFailure>;
207 readonly deleteScheduledTask: (
208 scope: McpInvocationScope,
209 input: OrchestratorMcpDeleteScheduledTaskInput,
210 ) => Effect.Effect<OrchestratorMcpDeleteScheduledTaskResult, OrchestratorMcpFailure>;
211 /** Only status reaches the agent, never this value. */
212 readonly requestSecret: (
213 scope: McpInvocationScope,
214 input: OrchestratorMcpRequestSecretInput,
215 ) => Effect.Effect<OrchestratorMcpRequestSecretResult, OrchestratorMcpFailure>;
216 readonly listThreads: (
217 scope: McpInvocationScope,
218 input: OrchestratorMcpThreadListInput,
219 ) => Effect.Effect<OrchestratorMcpThreadListResult, OrchestratorMcpFailure>;
220 readonly readThread: (
221 scope: McpInvocationScope,
222 input: OrchestratorMcpThreadReadInput,
223 ) => Effect.Effect<OrchestratorMcpThreadReadResult, OrchestratorMcpFailure>;
224 readonly sendToThread: (
225 scope: McpInvocationScope,
226 input: OrchestratorMcpThreadSendInput,
227 ) => Effect.Effect<OrchestratorMcpThreadSendResult, OrchestratorMcpFailure>;
228 readonly waitForThread: (
229 scope: McpInvocationScope,
230 input: OrchestratorMcpThreadWaitInput,
231 ) => Effect.Effect<OrchestratorMcpThreadWaitResult, OrchestratorMcpFailure>;
232 readonly interruptThread: (
233 scope: McpInvocationScope,
234 input: OrchestratorMcpThreadInterruptInput,
235 ) => Effect.Effect<OrchestratorMcpThreadInterruptResult, OrchestratorMcpFailure>;
236 }
237
238 export class OrchestratorMcpService extends Context.Service<
239 OrchestratorMcpService,
240 OrchestratorMcpServiceShape
241 >()("t3/mcp/OrchestratorMcpService") {}
242
243 export const isThreadManagementError = Schema.is(ThreadManagementService.ThreadManagementError);
244
245 function failure(code: OrchestratorMcpFailure["code"], message: string): OrchestratorMcpFailure {
246 return new OrchestratorMcpFailure({ code, message });
247 }
248
249 export function threadManagementFailure(error: unknown): OrchestratorMcpFailure {
250 if (!isThreadManagementError(error)) return failure("orchestration_error", errorMessage(error));
251 switch (error._tag) {
252 case "ThreadManagementThreadNotFoundError":
253 return failure("thread_not_found", error.message);
254 case "ThreadManagementRunNotFoundError":
255 return failure("run_not_found", error.message);
256 case "ThreadManagementThreadArchivedError":
257 case "ThreadManagementWorktreeRestoreError":
258 return failure("thread_not_sendable", error.message);
259 case "ThreadManagementNoSteerableRunError":
260 return failure(
261 "thread_not_sendable",
262 `${error.message} Send with mode: "auto" or "queue" to start a new turn there.`,
263 );
264 case "ThreadManagementRunOutputRejectedError":
265 return failure("invalid_request", error.message);
266 case "ThreadManagementThreadNotInterruptibleError":
267 return failure("thread_not_interruptible", error.message);
268 case "ThreadManagementProjectionLoadError":
269 case "ThreadManagementProjectThreadsListError":
270 case "ThreadManagementDurableRunProjectionError":
271 return failure("orchestration_error", error.message);
272 case "ThreadManagementProviderInstanceDisabledError":
273 return failure("invalid_request", error.message);
274 }
275 }
276
277 // Without a reason, a Stop reads as the user's (see RunExecutionService.USER_STOP_REASON).
278 function agentStopReason(reason: string | undefined): string {
279 return reason === undefined ? "Stopped by an agent" : `Stopped by an agent: ${reason}`;
280 }
281
282 function errorMessage(error: unknown): string {
283 return error instanceof Error ? error.message : String(error);
284 }
285
286 function scheduledTaskSummary(task: ScheduledTask, mayRun: boolean): OrchestratorMcpScheduledTask {
287 return {
288 scheduledTaskId: task.id,
289 title: task.title,
290 prompt: task.prompt,
291 enabled: task.enabled,
292 projectId: task.projectId,
293 boundThreadId: task.threadId,
294 freshSession: scheduledTaskThreadMode(task) === "fresh_session",
295 schedule: task.schedule,
296 nextRunAt: task.nextRunAt,
297 lastRunStatus: task.lastRunStatus,
298 ...(task.webhook?.url == null || !mayRun || task.blockedByPolicy !== undefined
299 ? {}
300 : { webhookUrl: task.webhook.url }),
301 ...(task.webhook === undefined
302 ? {}
303 : { webhookSignature: task.webhook.hasSecret ? "set" : "none" }),
304 ...(task.blockedByPolicy === undefined ? {} : { blockedByPolicy: task.blockedByPolicy }),
305 };
306 }
307
308 /**
309 * Large catalogs (OpenCode, Cursor, Pi) can list hundreds of models, so agents
310 * get a short list by default and search for the rest. These providers have
311 * small official catalogs, so all their current models are listed.
312 */
313 const FULL_CATALOG_DRIVERS: ReadonlySet<string> = new Set(["codex", "claudeAgent", "muse", "grok"]);
314 const LISTED_MODEL_LIMIT = 8;
315
316 /**
317 * Lists visible models, keeping pinned models and limiting large catalogs by default.
318 * Whole provider words select the provider; partial words filter models when any match.
319 */
320 function listCapabilityModels(input: {
321 readonly provider: ServerProvider;
322 readonly preferences:
323 | { readonly hiddenModels: ReadonlyArray<string>; readonly modelOrder: ReadonlyArray<string> }
324 | undefined;
325 readonly isPinned: (model: ServerProviderModel) => boolean;
326 readonly searchTerms: ReadonlyArray<string>;
327 }) {
328 const rank = new Map(input.preferences?.modelOrder.map((slug, index) => [slug, index]));
329 const visible = input.provider.models
330 .filter((model) => model.isCustom || !input.preferences?.hiddenModels.includes(model.slug))
331 .toSorted((a, b) => (rank.get(a.slug) ?? rank.size) - (rank.get(b.slug) ?? rank.size));
332 const { instanceId, driver, displayName } = input.provider;
333 const providerText = `${instanceId} ${driver} ${displayName ?? ""}`.toLowerCase();
334 // Whole ids like "codex-work" and their parts both name the provider.
335 const providerWords = new Set([
336 ...providerText.split(/\s+/),
337 ...providerText.split(/[^\p{L}\p{N}]+/u),
338 ]);
339 const modelText = (model: ServerProviderModel) =>
340 `${model.slug} ${model.name} ${model.subProvider ?? ""}`.toLowerCase();
341 // Part of a provider word ("agent" in "claudeAgent") names the provider unless a model matches it.
342 const modelTerms = input.searchTerms.filter(
343 (term) =>
344 !providerWords.has(term) &&
345 (!providerText.includes(term) || visible.some((model) => modelText(model).includes(term))),
346 );
347 if (modelTerms.length > 0) {
348 const matches = visible.filter((model) => {
349 const text = modelText(model);
350 return modelTerms.every((term) => text.includes(term));
351 });
352 const listed = matches.slice(0, LISTED_MODEL_LIMIT);
353 return { listed, omitted: matches.length - listed.length };
354 }
355 const current = visible.filter((model) => !model.isLegacy);
356 const shown = new Set(
357 FULL_CATALOG_DRIVERS.has(input.provider.driver)
358 ? current
359 : current.slice(0, LISTED_MODEL_LIMIT),
360 );
361 const listed = visible.filter((model) => input.isPinned(model) || shown.has(model));
362 return { listed, omitted: visible.length - listed.length };
363 }
364
365 /** Names advertised slugs to retry with: same last `/` segment first, else a short list. */
366 function advertisedModelsHint(models: ReadonlyArray<ServerProviderModel>, requested: string) {
367 const lastSegment = (slug: string) => slug.slice(slug.lastIndexOf("/") + 1).toLowerCase();
368 const wanted = lastSegment(requested);
369 const close = models.filter((model) => lastSegment(model.slug) === wanted);
370 if (close.length > 0) {
371 return `Did you mean ${close
372 .slice(0, LISTED_MODEL_LIMIT)
373 .map((model) => model.slug)
374 .join(", ")}?`;
375 }
376 const listed = models
377 .toSorted((a, b) => Number(a.isLegacy ?? false) - Number(b.isLegacy ?? false))
378 .slice(0, LISTED_MODEL_LIMIT);
379 const omitted = models.length - listed.length;
380 return `Advertised models: ${listed.map((model) => model.slug).join(", ")}${
381 omitted > 0 ? ` and ${omitted} more; orchestrator_capabilities with search finds them` : ""
382 }.`;
383 }
384
385 /** Option ids and allowed values are all a delegating agent needs; labels are UI copy. */
386 function capabilityModelOption(descriptor: ProviderOptionDescriptor): OrchestratorMcpModelOption {
387 const defaultValue = getProviderOptionCurrentValue(descriptor);
388 return {
389 id: descriptor.id,
390 values:
391 descriptor.type === "boolean" ? [false, true] : descriptor.options.map((choice) => choice.id),
392 ...(defaultValue === undefined ? {} : { default: defaultValue }),
393 };
394 }
395
396 const advertisedModel = (provider: ServerProvider, model: string) =>
397 provider.models.find((candidate) => candidate.slug === model) ??
398 provider.models.find((candidate) =>
399 candidate.aliases?.some((alias) => alias.toLowerCase() === model.toLowerCase()),
400 );
401
402 /** Antigravity 1.3 IDs append the thinking level (`gemini-3.8-flash-high`); the agent still accepts them. */
403 function antigravitySuffixedModel(provider: ServerProvider, model: string) {
404 if (provider.driver !== "antigravity" || advertisedModel(provider, model)) return;
405 const separator = model.lastIndexOf("-");
406 if (separator === -1) return;
407 const family = model.slice(0, separator);
408 const value = model.slice(separator + 1);
409 const thinking = provider.models
410 .find((candidate) => candidate.slug === family)
411 ?.capabilities?.optionDescriptors?.find(
412 (descriptor) => descriptor.type === "select" && descriptor.role === "reasoning",
413 );
414 if (thinking?.type === "select" && thinking.options.some((choice) => choice.id === value)) {
415 return { model: family, thinking: { id: thinking.id, value } };
416 }
417 }
418
419 /** A folder's own provider config can add models that only its workspace snapshot lists. */
420 export const withWorkspaceModels = (
421 providers: ReadonlyArray<ServerProvider>,
422 cwd: string | undefined,
423 ): ReadonlyArray<ServerProvider> =>
424 cwd === undefined
425 ? providers
426 : providers.map((provider) => {
427 const models = provider.workspaceSnapshots?.find(
428 (snapshot) => snapshot.cwd === cwd,
429 )?.models;
430 return models === undefined ? provider : { ...provider, models };
431 });
432
433 const withV = (version: string) => (version.startsWith("v") ? version : `v${version}`);
434
435 /** A provider that lists no models accepts any slug. */
436 export const requireAdvertisedModel = (provider: ServerProvider, model: string) => {
437 if (provider.models.length === 0 || advertisedModel(provider, model) !== undefined) {
438 return Effect.void;
439 }
440 const updateRequired = provider.updateRequiredModels?.find(
441 (candidate) => candidate.slug === model,
442 );
443 const detectedVersion = provider.installedVersion ?? provider.version;
444 return Effect.fail(
445 failure(
446 "model_unavailable",
447 updateRequired === undefined
448 ? `Model ${model} is not advertised by provider ${provider.instanceId}. ${advertisedModelsHint(provider.models, model)}`
449 : `Model ${model} needs provider ${provider.instanceId} at ${withV(updateRequired.minVersion)} or newer, but the detected CLI is ${detectedVersion === null ? "an unknown version" : withV(detectedVersion)}. Ask the user to update it or point the provider's binary path at a newer install.`,
450 ),
451 );
452 };
453
454 function providerConstraints(
455 provider: ServerProvider | undefined,
456 supportsOrchestrationV2: boolean,
457 ): ReadonlyArray<string> {
458 const constraints: Array<string> = [];
459 if (!supportsOrchestrationV2) {
460 constraints.push("No V2 provider adapter is registered.");
461 }
462 if (provider === undefined) return constraints;
463 if (!isProviderAvailable(provider)) {
464 constraints.push(provider.unavailableReason ?? "Provider driver is unavailable.");
465 }
466 if (!provider.enabled) {
467 constraints.push("Provider instance is disabled.");
468 // Disabled snapshots contain placeholders for installation, health, and auth.
469 return constraints;
470 }
471 if (!provider.installed) constraints.push("Provider executable is not installed.");
472 if (provider.status === "error" || provider.status === "disabled") {
473 constraints.push(provider.message ?? `Provider status is ${provider.status}.`);
474 }
475 if (provider.auth.status === "unauthenticated") {
476 constraints.push("Provider is not authenticated.");
477 }
478 return constraints;
479 }
480
481 /** t3_thread_launch keeps a selection as given, so it can hold options its model does not have. */
482 function knownOptions(
483 options: ReadonlyArray<ProviderOptionSelection> | undefined,
484 descriptors: ReadonlyArray<ProviderOptionDescriptor> | undefined,
485 ): ReadonlyArray<ProviderOptionSelection> | undefined {
486 if (options === undefined || descriptors === undefined) return options;
487 return options.filter((option) => descriptors.some((descriptor) => descriptor.id === option.id));
488 }
489
490 /** Skip checks without descriptors; reject duplicate IDs because consumers disagree on precedence. */
491 function invalidOptionSelections(
492 selections: ReadonlyArray<ProviderOptionSelection>,
493 descriptors: ReadonlyArray<ProviderOptionDescriptor> | undefined,
494 ): ReadonlyArray<string> {
495 const problems: Array<string> = [];
496 const seen = new Set<string>();
497 for (const selection of selections) {
498 if (seen.has(selection.id)) {
499 problems.push(`Option ${selection.id} was specified more than once.`);
500 continue;
501 }
502 seen.add(selection.id);
503 if (descriptors === undefined) continue;
504 const descriptor = descriptors.find((candidate) => candidate.id === selection.id);
505 if (descriptor === undefined) {
506 const known = descriptors.map((candidate) => candidate.id).join(", ");
507 problems.push(`Unknown option ${selection.id}; supported options: ${known || "none"}.`);
508 continue;
509 }
510 if (descriptor.type === "boolean" && typeof selection.value !== "boolean") {
511 problems.push(`Option ${selection.id} expects a boolean value.`);
512 continue;
513 }
514 if (
515 descriptor.type === "select" &&
516 !descriptor.options.some((choice) => choice.id === selection.value)
517 ) {
518 const choices = descriptor.options.map((choice) => choice.id).join(", ");
519 problems.push(`Option ${selection.id} must be one of: ${choices}.`);
520 }
521 }
522 return problems;
523 }
524
525 function taskStatusForRun(
526 run: Pick<OrchestrationV2Run, "status" | "restartCancelledBackgroundWork"> | undefined,
527 ): OrchestratorMcpDelegateTaskResult["status"] {
528 switch (run === undefined ? undefined : runOutcome(run)) {
529 case "queued":
530 return "queued";
531 case "starting":
532 return "starting";
533 case "waiting":
534 return "waiting";
535 case "completed":
536 return "completed";
537 case "failed":
538 return "failed";
539 case "cancelled":
540 case "rolled_back":
541 return "cancelled";
542 case "interrupted":
543 return "interrupted";
544 case "preparing":
545 case "running":
546 case undefined:
547 return "running";
548 }
549 }
550
551 function delegatedTaskRun(
552 childProjection: Pick<OrchestrationV2ThreadProjection, "runs" | "contextTransfers">,
553 task: OrchestrationV2Subagent,
554 ): OrchestrationV2Run | undefined {
555 const taskRun = childProjection.runs.find((run) => run.delegatedTaskId === task.id);
556 if (taskRun !== undefined) return taskRun;
557 const spawnTransfer = childProjection.contextTransfers.find(
558 (transfer) =>
559 transfer.type === "subagent_spawn" &&
560 transfer.sourceThreadId === task.threadId &&
561 transfer.targetThreadId === task.childThreadId,
562 );
563 if (spawnTransfer === undefined) {
564 return childProjection.runs[0];
565 }
566 return spawnTransfer.targetRunId === null
567 ? undefined
568 : childProjection.runs.find((run) => run.id === spawnTransfer.targetRunId);
569 }
570
571 function hasPendingChildRuns(
572 childProjection: Pick<OrchestrationV2ThreadProjection, "runs">,
573 delegatedRun: OrchestrationV2Run | undefined,
574 ): boolean {
575 return childProjection.runs.some(
576 (run) =>
577 !ThreadManagementService.isTerminalRunStatus(run.status) &&
578 !(run.status === "queued" && run.queueHeld === true) &&
579 (delegatedRun === undefined || run.ordinal > delegatedRun.ordinal),
580 );
581 }
582
583 function isTerminalTaskStatus(
584 status: OrchestratorMcpDelegateTaskResult["status"],
585 ): status is TerminalTaskStatus {
586 return (
587 status === "completed" ||
588 status === "failed" ||
589 status === "cancelled" ||
590 status === "interrupted"
591 );
592 }
593
594 function endsTaskWait(result: OrchestratorMcpDelegateTaskResult): boolean {
595 return (
596 result.hasPendingQuestion ||
597 result.pendingApproval !== null ||
598 isTerminalTaskStatus(result.status)
599 );
600 }
601
602 const isApprovalRequestKind = Schema.is(ProviderRequestKind);
603
604 function pendingTaskApproval(
605 child: Pick<OrchestrationV2ThreadProjection, "runs" | "nodes" | "runtimeRequests">,
606 taskId: NodeId,
607 originalRun: OrchestrationV2Run | undefined,
608 ) {
609 const taskRunIds = new Set(
610 child.runs
611 .filter(
612 (run) =>
613 !ThreadManagementService.isTerminalRunStatus(run.status) &&
614 (run.delegatedTaskId === taskId ||
615 // Legacy tasks own only their original run, not later turns in the child thread.
616 (run.delegatedTaskId === undefined && run.id === originalRun?.id)),
617 )
618 .map((run) => run.id),
619 );
620 let approval: OrchestratorMcpDelegateTaskResult["pendingApproval"] = null;
621 let oldestCreatedAt = Infinity;
622 for (const request of child.runtimeRequests) {
623 if (
624 request.status !== "pending" ||
625 request.responseCapability.type !== "live" ||
626 !isApprovalRequestKind(request.kind)
627 ) {
628 continue;
629 }
630 const runId = child.nodes.find((node) => node.id === request.nodeId)?.runId;
631 if (runId === undefined || runId === null || !taskRunIds.has(runId)) continue;
632 const createdAt = DateTime.toEpochMillis(request.createdAt);
633 if (createdAt < oldestCreatedAt) {
634 oldestCreatedAt = createdAt;
635 approval = { requestId: request.id, kind: request.kind, runId };
636 }
637 }
638 return approval;
639 }
640
641 /** Every task `directAppOwnedChildTasks` can return, so callers load only those. */
642 function directChildTaskIds(
643 target: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,
644 returnedRunIds: ReadonlySet<RunId | null>,
645 ): ReadonlyArray<NodeId> {
646 const ids = new Set<NodeId>();
647 if (target.thread.forkedFrom?.type === "node") ids.add(target.thread.forkedFrom.nodeId);
648 for (const run of target.runs) {
649 if (returnedRunIds.has(run.id) && run.delegatedTaskId !== undefined) {
650 ids.add(run.delegatedTaskId);
651 }
652 }
653 return [...ids];
654 }
655
656 function directAppOwnedChildTasks(
657 parent: Pick<OrchestrationV2ThreadProjection, "thread" | "subagents">,
658 target: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,
659 returnedRunIds: ReadonlySet<RunId | null>,
660 ): ReadonlyArray<OrchestrationV2Subagent> {
661 if (
662 target.thread.lineage.parentThreadId !== parent.thread.id ||
663 target.thread.lineage.relationshipToParent !== "subagent"
664 ) {
665 return [];
666 }
667 const original = parent.subagents.find(
668 (task) =>
669 task.origin === "app_owned" &&
670 task.threadId === parent.thread.id &&
671 task.id ===
672 (target.thread.forkedFrom?.type === "node" ? target.thread.forkedFrom.nodeId : undefined) &&
673 task.childThreadId === target.thread.id,
674 );
675 const taskIds = new Set(
676 target.runs
677 .filter((run) => returnedRunIds.has(run.id))
678 .map((run) => run.delegatedTaskId ?? original?.id),
679 );
680 return parent.subagents.filter(
681 (task) =>
682 taskIds.has(task.id) &&
683 task.origin === "app_owned" &&
684 task.childThreadId === target.thread.id,
685 );
686 }
687
688 // The child's transfers include the results it sent, so the parent's transfers are never read.
689 function taskResultTransfer(
690 parentThreadId: ThreadId,
691 child: Pick<OrchestrationV2ThreadProjection, "runs" | "contextTransfers">,
692 task: OrchestrationV2Subagent,
693 ) {
694 const originalRun = delegatedTaskRun(child, task);
695 const resultRunIds = new Set(
696 child.runs
697 .filter(
698 (run) =>
699 run.delegatedTaskId === task.id ||
700 (originalRun?.delegatedTaskId === undefined && run.delegatedTaskId === undefined),
701 )
702 .map((run) => run.id),
703 );
704 if (originalRun !== undefined) resultRunIds.add(originalRun.id);
705 return child.contextTransfers.find(
706 (transfer) =>
707 transfer.type === "subagent_result" &&
708 transfer.sourceThreadId === task.childThreadId &&
709 transfer.targetThreadId === parentThreadId &&
710 ((transfer.sourcePoint.runId !== undefined && resultRunIds.has(transfer.sourcePoint.runId)) ||
711 (transfer.sourcePoint.runId === undefined && originalRun?.delegatedTaskId === undefined)),
712 );
713 }
714
715 function pageIncludesTerminalTaskResult(input: {
716 readonly parentThreadId: ThreadId;
717 readonly items: ReadonlyArray<OrchestratorMcpThreadTimelineItem>;
718 readonly task: OrchestrationV2Subagent;
719 readonly target: Pick<
720 OrchestrationV2ThreadProjection,
721 "thread" | "runs" | "contextTransfers" | "messages" | "turnItems" | "providerTurns"
722 >;
723 }): boolean {
724 const transfer = taskResultTransfer(input.parentThreadId, input.target, input.task);
725 if (transfer === undefined) return false;
726 const run =
727 transfer.sourcePoint.runId === undefined
728 ? delegatedTaskRun(input.target, input.task)
729 : input.target.runs.find((run) => run.id === transfer.sourcePoint.runId);
730 if (run === undefined || !isTerminalTaskStatus(taskStatusForRun(run))) return false;
731
732 const result = subagentResultForRun(input.target, run);
733 if (result.messageId === null && result.turnItemId === null) return false;
734
735 return input.items.some((item) => {
736 if (item.sourceThreadId !== input.target.thread.id) return false;
737 const matchesResult =
738 (result.turnItemId !== null && item.itemId === result.turnItemId) ||
739 (result.messageId !== null &&
740 item.type === "assistant_message" &&
741 item.messageId === result.messageId);
742 return matchesResult && item.text !== null && !item.textTruncated;
743 });
744 }
745
746 function latestTerminalResultRun(
747 projection: Pick<OrchestrationV2ThreadProjection, "messages" | "runs">,
748 delegatedRun: OrchestrationV2Run | undefined,
749 awaitingContinuationRun: OrchestrationV2Run | undefined,
750 ): OrchestrationV2Run | undefined {
751 const monitorRunIds = new Set(
752 projection.messages
753 .filter((message) => message.notification?.source.kind === "monitor")
754 .map((message) => message.runId),
755 );
756 // A restart-cut run, and each cut run before it in the chain, has no outcome while a
757 // continuation is pending, live, or ran to a result.
758 const runsById = new Map(projection.runs.map((run) => [run.id, run]));
759 const supersededRunIds = new Set<RunId>();
760 const supersede = (runId: RunId | undefined) => {
761 let id = runId;
762 while (id !== undefined && !supersededRunIds.has(id)) {
763 supersededRunIds.add(id);
764 id = runsById.get(id)?.restartContinuationOfRunId;
765 }
766 };
767 supersede(awaitingContinuationRun?.id);
768 for (const run of projection.runs) {
769 if (
770 !ThreadManagementService.isTerminalRunStatus(run.status) ||
771 (run.status !== "rolled_back" && run.startedAt !== null)
772 )
773 supersede(run.restartContinuationOfRunId);
774 }
775 return projection.runs
776 .filter(
777 (run) =>
778 ThreadManagementService.isTerminalRunStatus(run.status) &&
779 !monitorRunIds.has(run.id) &&
780 !supersededRunIds.has(run.id) &&
781 run.status !== "rolled_back" &&
782 (run.id === delegatedRun?.id || run.startedAt !== null),
783 )
784 .reduce<OrchestrationV2Run | undefined>(
785 (latest, run) => (latest === undefined || runRanAfter(run, latest) ? run : latest),
786 undefined,
787 );
788 }
789
790 function canExposeTaskRunResult(run: OrchestrationV2Run | undefined): run is OrchestrationV2Run {
791 return (
792 run !== undefined && run.status !== "rolled_back" && isTerminalTaskStatus(taskStatusForRun(run))
793 );
794 }
795
796 function stablePart(value: string): string {
797 return encodeURIComponent(value);
798 }
799
800 function stableCommandId(input: {
801 readonly scope: McpInvocationScope;
802 readonly requestKey: string;
803 readonly operation: string;
804 readonly index?: number;
805 }): CommandId {
806 return CommandId.make(
807 [
808 "command",
809 "mcp",
810 stablePart(input.scope.requestNamespace),
811 stablePart(input.operation),
812 stablePart(input.requestKey),
813 ...(input.index === undefined ? [] : [String(input.index)]),
814 ].join(":"),
815 );
816 }
817
818 function stableThreadId(input: {
819 readonly scope: McpInvocationScope;
820 readonly requestKey: string;
821 readonly index: number;
822 }): ThreadId {
823 return ThreadId.make(
824 [
825 "thread",
826 "mcp",
827 stablePart(input.scope.requestNamespace),
828 stablePart(input.requestKey),
829 String(input.index),
830 ].join(":"),
831 );
832 }
833
834 function stableMessageId(input: {
835 readonly scope: McpInvocationScope;
836 readonly requestKey: string;
837 readonly index: number;
838 }): MessageId {
839 return MessageId.make(
840 [
841 "message",
842 "mcp",
843 stablePart(input.scope.requestNamespace),
844 stablePart(input.requestKey),
845 String(input.index),
846 ].join(":"),
847 );
848 }
849
850 function stableOperationMessageId(input: {
851 readonly scope: McpInvocationScope;
852 readonly requestKey: string;
853 readonly operation: string;
854 }): MessageId {
855 return MessageId.make(
856 [
857 "message",
858 "mcp",
859 stablePart(input.scope.requestNamespace),
860 stablePart(input.operation),
861 stablePart(input.requestKey),
862 ].join(":"),
863 );
864 }
865
866 function threadTitle(input: {
867 readonly parentTitle: string;
868 readonly prompt: string | undefined;
869 readonly title: string | undefined;
870 readonly index: number;
871 }): string {
872 const detail = input.title?.trim() || input.prompt?.trim();
873 if (!detail) return placeholderThreadTitle(input.parentTitle, input.index);
874 if (detail.length <= 80) return detail;
875 let end = 77;
876 const previous = detail.charCodeAt(end - 1);
877 const next = detail.charCodeAt(end);
878 if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
879 end -= 1;
880 }
881 return `${detail.slice(0, end)}...`;
882 }
883
884 function threadSettlement(
885 thread: Pick<OrchestrationV2ThreadShell, "settledOverride" | "settledAt">,
886 ): Pick<OrchestratorMcpThreadListItem, "settled" | "settledAt"> {
887 const settled = thread.settledOverride === "settled";
888 return {
889 settled,
890 settledAt: settled && thread.settledAt !== null ? DateTime.formatIso(thread.settledAt) : null,
891 };
892 }
893
894 function threadSnooze(
895 thread: Parameters<typeof isSnoozed>[0],
896 nowMs: number,
897 ): Pick<OrchestratorMcpThreadListItem, "snoozed" | "snoozedUntil"> {
898 const snoozed = isSnoozed(thread, nowMs);
899 return {
900 snoozed,
901 snoozedUntil:
902 snoozed && thread.snoozedUntil != null ? DateTime.formatIso(thread.snoozedUntil) : null,
903 };
904 }
905
906 // Provider-internal links (parentTaskId, providerInstanceId) stay out of agent results.
907 function threadBackgroundWork(
908 thread: Pick<OrchestrationV2ThreadShell, "blockedOnThreadWait" | "pendingBackgroundTasks">,
909 ): Required<Pick<OrchestratorMcpThreadListItem, "blockedOnThreadWait" | "pendingBackgroundTasks">> {
910 return {
911 blockedOnThreadWait: thread.blockedOnThreadWait === true,
912 pendingBackgroundTasks: (thread.pendingBackgroundTasks ?? []).map((task) => ({
913 taskId: task.taskId,
914 kind: task.kind,
915 ...(task.description === undefined ? {} : { description: task.description }),
916 ...(task.awaited === undefined ? {} : { awaited: task.awaited }),
917 ...(task.kind === "subagent" && task.childThreadId !== undefined
918 ? { childThreadId: task.childThreadId }
919 : {}),
920 })),
921 };
922 }
923
924 function threadPullRequests(
925 links: OrchestrationV2ThreadShell["pullRequests"],
926 includeLinks = true,
927 ): Pick<
928 OrchestratorMcpThreadListItem,
929 "pullRequests" | "pullRequestCount" | "openPullRequestCount"
930 > {
931 const visible = visibleThreadPullRequests(links ?? []);
932 if (!includeLinks) return { pullRequestCount: visible.length };
933 const open = visible.filter(
934 (link) => link.snapshot?.state !== "merged" && link.snapshot?.state !== "closed",
935 );
936 return {
937 pullRequests: open
938 .toSorted(
939 (left, right) =>
940 Number(right.watch !== undefined) - Number(left.watch !== undefined) ||
941 threadPullRequestUpdatedAtMs(right) - threadPullRequestUpdatedAtMs(left),
942 )
943 .slice(0, THREAD_PULL_REQUEST_PREVIEW_LIMIT)
944 .map((link) => ({
945 host: normalizeThreadPullRequestKey(link).host,
946 repository: link.repository,
947 number: link.number,
948 url: link.url,
949 source: link.source,
950 state: link.snapshot?.state ?? null,
951 watching: link.watch !== undefined,
952 watchStartedAt: link.watch?.startedAt ?? null,
953 })),
954 pullRequestCount: visible.length,
955 openPullRequestCount: open.length,
956 };
957 }
958
959 // Awaited background work keeps a thread live after its turn ends, as auto-settle and the sidebar treat it.
960 function threadStatus(
961 activeStatus: OrchestratorMcpThreadListItem["status"] | null | undefined,
962 settledStatus: OrchestratorMcpThreadListItem["status"],
963 pendingBackgroundTasks: OrchestrationV2ThreadShell["pendingBackgroundTasks"],
964 ) {
965 if (activeStatus != null) return activeStatus;
966 if (settledStatus === "failed") return settledStatus;
967 return backgroundWorkHoldsCompletion(pendingBackgroundTasks ?? []) ? "waiting" : settledStatus;
968 }
969
970 const LIVE_LISTED_THREAD_STATUSES: ReadonlySet<OrchestratorMcpThreadListItem["status"]> = new Set([
971 "queued",
972 "preparing",
973 "starting",
974 "running",
975 "waiting",
976 ]);
977
978 function listedThreadStatus(shell: OrchestrationV2ThreadShell) {
979 return threadStatus(shell.activityRunStatus, shell.status, shell.pendingBackgroundTasks);
980 }
981
982 function listItemFromShell(
983 scope: McpInvocationScope,
984 shell: OrchestrationV2ThreadShell,
985 nowMs: number,
986 ): OrchestratorMcpThreadListItem {
987 return {
988 threadId: shell.id,
989 projectId: shell.projectId,
990 title: shell.title,
991 link: threadLinkFor(scope, shell.id, shell.title),
992 createdBy: shell.createdBy,
993 creationSource: shell.creationSource,
994 status: listedThreadStatus(shell),
995 latestRunId: shell.latestRunId,
996 providerInstanceId: shell.modelSelection.instanceId,
997 model: shell.modelSelection.model,
998 runtimeMode: shell.runtimeMode,
999 interactionMode: shell.interactionMode,
1000 linkedPullRequest: shell.linkedPullRequest ?? null,
1001 ...threadPullRequests(shell.pullRequests),
1002 ...threadSettlement(shell),
1003 ...threadSnooze(shell, nowMs),
1004 pinned: shell.pinnedAt != null,
1005 ...threadBackgroundWork(shell),
1006 parentThreadId: shell.lineage.parentThreadId,
1007 relationshipToParent: shell.lineage.relationshipToParent,
1008 ...(shell.delegatedFrom == null ? {} : { delegatedFrom: shell.delegatedFrom }),
1009 itemCount: shell.visibleItemCount,
1010 createdAt: DateTime.formatIso(shell.createdAt),
1011 updatedAt: DateTime.formatIso(shell.updatedAt),
1012 };
1013 }
1014
1015 function threadDetail(
1016 scope: McpInvocationScope,
1017 projection: Pick<OrchestrationV2ThreadProjection, "thread" | "runs" | "runtimeRequests">,
1018 runCount: number,
1019 itemCount: number,
1020 shell: OrchestrationV2ThreadShell,
1021 nowMs: number,
1022 firstPage: boolean,
1023 ): OrchestratorMcpThreadDetail {
1024 const latest = ThreadManagementService.latestRun(projection);
1025 const active = ThreadManagementService.latestActiveRun(projection);
1026 return {
1027 threadId: projection.thread.id,
1028 projectId: projection.thread.projectId,
1029 title: projection.thread.title,
1030 link: threadLinkFor(scope, projection.thread.id, projection.thread.title),
1031 createdBy: projection.thread.createdBy,
1032 creationSource: projection.thread.creationSource,
1033 status: threadStatus(active?.status, latest?.status ?? "idle", shell.pendingBackgroundTasks),
1034 latestRunId: latest?.id ?? null,
1035 activeRunId: active?.id ?? null,
1036 providerInstanceId: projection.thread.modelSelection.instanceId,
1037 model: projection.thread.modelSelection.model,
1038 runtimeMode: projection.thread.runtimeMode,
1039 interactionMode: projection.thread.interactionMode,
1040 linkedPullRequest: projection.thread.linkedPullRequest ?? null,
1041 ...threadPullRequests(projection.thread.pullRequests, firstPage),
1042 titleRegeneration:
1043 projection.thread.titleRegeneration === undefined ||
1044 projection.thread.titleRegeneration === null
1045 ? null
1046 : {
1047 requestId: projection.thread.titleRegeneration.requestId,
1048 startedAt: DateTime.formatIso(projection.thread.titleRegeneration.startedAt),
1049 },
1050 lastTitleRegeneration:
1051 projection.thread.lastTitleRegeneration == null
1052 ? null
1053 : {
1054 ...projection.thread.lastTitleRegeneration,
1055 completedAt: DateTime.formatIso(projection.thread.lastTitleRegeneration.completedAt),
1056 },
1057 branch: projection.thread.branch,
1058 worktreePath: projection.thread.worktreePath,
1059 parentThreadId: projection.thread.lineage.parentThreadId,
1060 relationshipToParent: projection.thread.lineage.relationshipToParent,
1061 ...(projection.thread.delegatedFrom == null
1062 ? {}
1063 : { delegatedFrom: projection.thread.delegatedFrom }),
1064 runCount,
1065 itemCount,
1066 pendingRequestCount: projection.runtimeRequests.filter(
1067 (request) => request.status === "pending",
1068 ).length,
1069 archived: projection.thread.archivedAt !== null,
1070 ...threadSettlement(projection.thread),
1071 ...threadSnooze(shell, nowMs),
1072 pinned: shell.pinnedAt != null,
1073 ...threadBackgroundWork(shell),
1074 createdAt: DateTime.formatIso(projection.thread.createdAt),
1075 updatedAt: DateTime.formatIso(projection.thread.updatedAt),
1076 };
1077 }
1078
1079 function runExecutedModel(
1080 projection: Pick<OrchestrationV2ThreadProjection, "providerTurns">,
1081 run: Pick<OrchestrationV2Run, "activeAttemptId"> | undefined,
1082 ): string | null {
1083 return run === undefined
1084 ? null
1085 : (latestProviderTurnForAttempt(projection.providerTurns, run.activeAttemptId)?.model ?? null);
1086 }
1087
1088 function threadRun(
1089 projection: Pick<OrchestrationV2ThreadProjection, "providerTurns">,
1090 run: OrchestrationV2Run,
1091 ): OrchestratorMcpThreadRun {
1092 return {
1093 runId: run.id,
1094 ordinal: run.ordinal,
1095 status: run.status,
1096 providerInstanceId: run.modelSelection.instanceId,
1097 model: run.modelSelection.model,
1098 executedModel: runExecutedModel(projection, run),
1099 requestedAt: DateTime.formatIso(run.requestedAt),
1100 startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt),
1101 completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt),
1102 };
1103 }
1104
1105 function jsonText(value: unknown): string {
1106 try {
1107 return JSON.stringify(value, null, 2);
1108 } catch {
1109 return String(value);
1110 }
1111 }
1112
1113 function turnItemText(item: OrchestrationV2TurnItem): string | null {
1114 switch (item.type) {
1115 case "notification":
1116 return [item.summary, item.detail].filter((part) => part !== undefined).join("\n");
1117 case "user_message":
1118 case "assistant_message":
1119 case "reasoning":
1120 return item.text;
1121 case "proposed_plan":
1122 return item.markdown;
1123 case "todo_list":
1124 return [item.explanation, ...item.steps.map((step) => `[${step.status}] ${step.text}`)]
1125 .filter((line): line is string => line !== undefined)
1126 .join("\n");
1127 case "user_input_request":
1128 return jsonText(item.questions);
1129 case "file_change":
1130 return [
1131 item.fileName,
1132 item.additions === undefined && item.deletions === undefined
1133 ? undefined
1134 : `+${item.additions ?? 0} -${item.deletions ?? 0}`,
1135 item.diffStr ?? item.newStr,
1136 ]
1137 .filter((line): line is string => line !== undefined)
1138 .join("\n");
1139 case "command_execution":
1140 return [`$ ${item.input}`, item.output]
1141 .filter((line): line is string => line !== undefined)
1142 .join("\n");
1143 case "file_search":
1144 return jsonText({ pattern: item.pattern, results: item.results });
1145 case "web_search":
1146 return jsonText({ patterns: item.patterns, results: item.results });
1147 case "approval_request":
1148 return [item.prompt ?? item.requestKind, item.reason]
1149 .filter((line): line is string => line !== undefined)
1150 .join("\n");
1151 case "checkpoint":
1152 return jsonText(item.files);
1153 case "run_interrupt_request":
1154 case "run_interrupt_result":
1155 case "system_notice":
1156 return item.message;
1157 case "error":
1158 return item.failure.message;
1159 case "compaction":
1160 return item.summary ?? null;
1161 case "handoff":
1162 return item.summary ?? `${item.strategy} handoff to ${item.toProviderInstanceId}`;
1163 case "fork":
1164 return `Forked to thread ${item.targetThreadId}.`;
1165 case "thread_created":
1166 return `Created thread ${item.targetThreadId} with ${item.targetProviderInstanceId} (${item.targetModel}).`;
1167 case "secret_request":
1168 return `Asked the user for ${item.label}: ${item.secretStatus}.`;
1169 case "link_request":
1170 return item.linkStatus === "linked"
1171 ? `Linked ${item.linkedLabel ?? item.url ?? "an environment"} (${item.linkedAccess}).`
1172 : `Asked the user to link ${item.url ?? "an environment"}: ${item.linkStatus}.`;
1173 case "subagent":
1174 return item.result ?? item.progress ?? item.prompt;
1175 case "dynamic_tool":
1176 return jsonText({ toolName: item.toolName, input: item.input, output: item.output });
1177 }
1178 }
1179
1180 /** A cut inside a surrogate pair would leave half an emoji on each page. */
1181 function textPageEnd(text: string | null, offset: number, maxChars: number): number {
1182 const end = offset + maxChars;
1183 if (text === null || end >= text.length) return end;
1184 const last = text.charCodeAt(end - 1);
1185 if (last < 0xd800 || last > 0xdbff) return end;
1186 return end - 1 > offset ? end - 1 : end + 1;
1187 }
1188
1189 function timelineItem(input: {
1190 readonly row: OrchestrationV2ThreadProjection["visibleTurnItems"][number];
1191 readonly maxChars: number;
1192 readonly textOffset?: number;
1193 readonly messagesByThreadId: ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection["messages"]>;
1194 }): OrchestratorMcpThreadTimelineItem {
1195 const text = turnItemText(input.row.item);
1196 const offset = input.textOffset ?? 0;
1197 const end = textPageEnd(text, offset, input.maxChars);
1198 const textTruncated = text !== null && text.length > end;
1199 const messageId =
1200 input.row.item.type === "user_message" || input.row.item.type === "assistant_message"
1201 ? input.row.item.messageId
1202 : null;
1203 const message =
1204 messageId === null
1205 ? undefined
1206 : input.messagesByThreadId
1207 .get(input.row.sourceThreadId)
1208 ?.find((candidate) => candidate.id === messageId);
1209 return {
1210 position: input.row.position,
1211 visibility: input.row.visibility,
1212 sourceThreadId: input.row.sourceThreadId,
1213 itemId: input.row.sourceItemId,
1214 ...(input.row.item.type === "subagent" ? { subagentId: input.row.item.subagentId } : {}),
1215 runId: input.row.item.runId,
1216 messageId,
1217 createdBy: message?.createdBy ?? null,
1218 creationSource: message?.creationSource ?? null,
1219 ...(message?.senderThreadId === undefined ? {} : { senderThreadId: message.senderThreadId }),
1220 type: input.row.item.type,
1221 status: input.row.item.status,
1222 title: input.row.item.title,
1223 text: text === null ? null : text.slice(offset, end),
1224 textTruncated,
1225 nextTextOffset: textTruncated ? end : null,
1226 updatedAt: DateTime.formatIso(input.row.item.updatedAt),
1227 };
1228 }
1229
1230 const jsonBytes = (value: unknown) => Buffer.byteLength(JSON.stringify(value), "utf8");
1231
1232 /** The longest prefix length in [low, high] that `fits`, or `low - 1`. */
1233 function longestFitting(low: number, high: number, fits: (length: number) => boolean): number {
1234 let best = low - 1;
1235 while (low <= high) {
1236 const mid = Math.floor((low + high) / 2);
1237 if (fits(mid)) {
1238 best = mid;
1239 low = mid + 1;
1240 } else {
1241 high = mid - 1;
1242 }
1243 }
1244 return best;
1245 }
1246
1247 /** The item with its text cut, and an oversized title too, until its JSON fits `maxBytes`. */
1248 function timelineItemWithin(
1249 input: Parameters<typeof timelineItem>[0],
1250 maxBytes: number,
1251 ): OrchestratorMcpThreadTimelineItem {
1252 const longestText = (title: string | null) => {
1253 const withText = (maxChars: number) => ({ ...timelineItem({ ...input, maxChars }), title });
1254 const chars = longestFitting(2, input.maxChars - 1, (n) => jsonBytes(withText(n)) <= maxBytes);
1255 return withText(Math.max(chars, 1));
1256 };
1257 const item = longestText(input.row.item.title);
1258 const title = item.title;
1259 if (title === null || jsonBytes(item) <= maxBytes) return item;
1260 // Half the budget for the title keeps `textOffset` pages of the text useful.
1261 const cutTitle = (chars: number) =>
1262 title.slice(0, chars === 0 ? 0 : textPageEnd(title, 0, chars));
1263 const titleChars = longestFitting(
1264 1,
1265 title.length - 1,
1266 (n) => jsonBytes({ ...item, title: cutTitle(n) }) <= maxBytes / 2,
1267 );
1268 return longestText(cutTitle(Math.max(titleChars, 0)));
1269 }
1270
1271 /**
1272 * The items, read from the end the caller pages toward, whose result fits
1273 * THREAD_READ_RESULT_MAX_BYTES; `start` is the first kept index. Never empty for a non-empty page.
1274 */
1275 function timelineItemsWithinBudget(
1276 envelope: Omit<OrchestratorMcpThreadReadResult, "items">,
1277 inputs: ReadonlyArray<Parameters<typeof timelineItem>[0]>,
1278 newestFirst: boolean,
1279 ): { readonly items: Array<OrchestratorMcpThreadTimelineItem>; readonly start: number } {
1280 // An oversized envelope (say, a huge thread title) must not starve items to one char per read.
1281 const budget = Math.max(
1282 THREAD_READ_RESULT_MAX_BYTES - jsonBytes({ ...envelope, items: [] }),
1283 THREAD_READ_RESULT_MAX_BYTES / 2,
1284 );
1285 const items: Array<OrchestratorMcpThreadTimelineItem> = [];
1286 let bytes = 0;
1287 for (const input of newestFirst ? inputs.toReversed() : inputs) {
1288 const item = timelineItem(input);
1289 bytes += jsonBytes(item) + (items.length === 0 ? 0 : 1);
1290 if (bytes <= budget) {
1291 items.push(item);
1292 continue;
1293 }
1294 if (items.length === 0) items.push(timelineItemWithin(input, budget));
1295 break;
1296 }
1297 return newestFirst
1298 ? { items: items.toReversed(), start: inputs.length - items.length }
1299 : { items, start: 0 };
1300 }
1301
1302 const make = Effect.gen(function* () {
1303 const random = yield* SecureRandom.SecureRandom;
1304 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
1305 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
1306 const providerAdapters = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2;
1307 const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
1308 const projects = yield* ProjectService.ProjectService;
1309 const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
1310 const gitDriver = yield* GitVcsDriver.GitVcsDriver;
1311 const serverSettings = yield* ServerSettings.ServerSettingsService;
1312 const remoteDelegation = yield* RemoteDelegation.RemoteDelegation;
1313
1314 const requireProject = (projectId: ProjectId) =>
1315 projects.getById(projectId).pipe(
1316 Effect.mapError((error) =>
1317 failure("orchestration_error", `Unable to read project ${projectId}: ${error.message}`),
1318 ),
1319 Effect.flatMap(
1320 Option.match({
1321 onNone: () =>
1322 Effect.fail(failure("invalid_request", `Project ${projectId} was not found.`)),
1323 onSome: Effect.succeed,
1324 }),
1325 ),
1326 );
1327
1328 const projectDefaultModelSelection = Effect.fn(
1329 "OrchestratorMcpService.projectDefaultModelSelection",
1330 )(function* (project: Effect.Success<ReturnType<typeof requireProject>>) {
1331 const settings = yield* serverSettings.getSettings.pipe(
1332 Effect.mapError(() => failure("orchestration_error", "Unable to read server settings.")),
1333 );
1334 const selection = resolveProjectSettings(settings, project.id, project).settings
1335 .defaultModelSelection;
1336 if (selection === null)
1337 return yield* failure(
1338 "invalid_request",
1339 `Project ${project.id} has no default model, so this caller cannot pick one for it.`,
1340 );
1341 return selection;
1342 });
1343 const secretRequests = yield* SecretRequests.SecretRequests;
1344
1345 const requireCapability = (scope: McpInvocationScope) =>
1346 scope.capabilities.has("orchestration")
1347 ? Effect.void
1348 : Effect.fail(
1349 failure(
1350 "capability_denied",
1351 "This MCP credential does not grant orchestration capabilities.",
1352 ),
1353 );
1354
1355 const loadThreadRecords = <K extends ProjectionRecordField>(
1356 threadId: ThreadId,
1357 fields: ReadonlyArray<K>,
1358 filter?: ProjectionRecordFilter,
1359 ) =>
1360 threadManagement
1361 .getThreadRecords(threadId, fields, filter)
1362 .pipe(
1363 Effect.mapError((error) =>
1364 failure(
1365 "orchestration_error",
1366 `Unable to read thread ${threadId}: ${errorMessage(error)}`,
1367 ),
1368 ),
1369 );
1370
1371 // Runs on every MCP call, and long threads hold thousands of records; callers need only active runs.
1372 const loadCallerRecords = <K extends "runs">(threadId: ThreadId, fields: ReadonlyArray<K>) =>
1373 loadThreadRecords(threadId, fields, {
1374 runStatuses: ThreadManagementService.ACTIVE_RUN_STATUSES,
1375 });
1376
1377 // A dispatcher thread holds thousands of tasks, each with its full prompt; read only the ones named.
1378 const loadTasks = (threadId: ThreadId, taskIds: ReadonlyArray<NodeId>) =>
1379 threadManagement.getThreadRecords(threadId, ["subagents"], { subagentIds: taskIds }).pipe(
1380 Effect.map(({ subagents }) => subagents),
1381 Effect.mapError((error) =>
1382 failure("orchestration_error", `Unable to read thread ${threadId}: ${errorMessage(error)}`),
1383 ),
1384 );
1385
1386 const loadCaller = Effect.fn("OrchestratorMcpService.loadCaller")(function* <K extends "runs">(
1387 scope: McpInvocationScope,
1388 fields: ReadonlyArray<K>,
1389 ) {
1390 yield* requireCapability(scope);
1391 if (scope.thread === undefined) {
1392 return {
1393 parent: undefined,
1394 limits: clientModeCeiling(scope.client),
1395 } as const;
1396 }
1397 const parent = yield* loadCallerRecords(scope.thread.threadId, fields);
1398 return {
1399 parent,
1400 limits: {
1401 runtimeMode: parent.thread.runtimeMode,
1402 interactionMode: parent.thread.interactionMode,
1403 },
1404 } as const;
1405 });
1406
1407 const loadThreadCaller = Effect.fn("OrchestratorMcpService.loadThreadCaller")(function* (
1408 scope: McpInvocationScope,
1409 operation: string,
1410 ) {
1411 yield* requireCapability(scope);
1412 const threadScope = yield* requireThreadScope(scope, operation);
1413 const parent = yield* loadCallerRecords(threadScope.thread.threadId, ["runs"]);
1414 return { scope: threadScope, parent } as const;
1415 });
1416
1417 const resolveProjectTarget = (
1418 parent: Pick<OrchestrationV2ThreadProjection, "thread"> | undefined,
1419 projectId: ProjectId | undefined,
1420 missingMessage = "Pass projectId: this MCP client is not running inside a T3 thread.",
1421 ) =>
1422 projectId !== undefined
1423 ? Effect.succeed(projectId)
1424 : parent !== undefined
1425 ? Effect.succeed(parent.thread.projectId)
1426 : Effect.fail(failure("target_required", missingMessage));
1427
1428 const loadTargetThread = Effect.fn("OrchestratorMcpService.loadTargetThread")(function* (
1429 scope: McpInvocationScope,
1430 threadId: ThreadId,
1431 ) {
1432 const shell = yield* threadManagement
1433 .getThreadShell(threadId)
1434 .pipe(Effect.mapError(threadManagementFailure));
1435 if (shell === null || shell.deletedAt !== null) {
1436 return yield* threadNotFound(
1437 threadManagement,
1438 scope,
1439 threadId,
1440 `Thread ${threadId} was not found.`,
1441 );
1442 }
1443 // Keeps legacy import and project validation; callers read only the thread row.
1444 return yield* threadManagement
1445 .getProjectThreadRecords({ projectId: shell.projectId, threadId }, [])
1446 .pipe(Effect.mapError(threadManagementFailure));
1447 });
1448
1449 const loadScopedThread = Effect.fn("OrchestratorMcpService.loadScopedThread")(function* <
1450 K extends "runs",
1451 >(scope: McpInvocationScope, threadId: ThreadId, callerFields: ReadonlyArray<K>) {
1452 const caller = yield* loadCaller(scope, callerFields);
1453 // Only the thread row: the caller's own record holds just its active runs.
1454 const target: Pick<OrchestrationV2ThreadProjection, "thread"> =
1455 caller.parent !== undefined && threadId === caller.parent.thread.id
1456 ? caller.parent
1457 : yield* loadTargetThread(scope, threadId);
1458 return { ...caller, target } as const;
1459 });
1460
1461 /** Cross-thread writes require a live caller run; stale session credentials cannot authorize them. */
1462 const assertLiveCallerForOtherThread = (
1463 scope: McpInvocationScope,
1464 parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs"> | undefined,
1465 target: Pick<OrchestrationV2ThreadProjection, "thread">,
1466 ) =>
1467 parent === undefined || target.thread.id === parent.thread.id
1468 ? Effect.void
1469 : assertLiveCaller(scope, parent);
1470
1471 const assertLiveCallerForOtherProject = (
1472 scope: McpInvocationScope,
1473 parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs"> | undefined,
1474 projectId: ProjectId,
1475 ) =>
1476 parent === undefined || projectId === parent.thread.projectId
1477 ? Effect.void
1478 : assertLiveCaller(scope, parent);
1479
1480 const assertLiveCaller = (
1481 scope: McpInvocationScope,
1482 parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,
1483 ) => {
1484 const notActive = failure(
1485 "parent_not_active",
1486 "The calling provider no longer owns an active thread run.",
1487 );
1488 const activeRun = ThreadManagementService.latestActiveRun(parent);
1489 if (parent.thread.archivedAt === null && activeRun === undefined) {
1490 // Decide from this one fresh snapshot: a run may have started since `parent` was read.
1491 return threadManagement.getThreadShell(parent.thread.id).pipe(
1492 Effect.mapError(threadManagementFailure),
1493 Effect.flatMap((shell) =>
1494 isLiveCallerShell(shell, scope.thread?.providerInstanceId)
1495 ? Effect.void
1496 : Effect.fail(notActive),
1497 ),
1498 );
1499 }
1500 return parent.thread.archivedAt !== null ||
1501 activeRun === undefined ||
1502 activeRun.providerInstanceId !== scope.thread?.providerInstanceId
1503 ? Effect.fail(notActive)
1504 : Effect.void;
1505 };
1506
1507 // A background subagent keeps calling tools after the run that started it settles. Its
1508 // delegations join that latest run, whose completion cohort wakes the thread once they finish.
1509 const backgroundSubagentRun = Effect.fn("OrchestratorMcpService.backgroundSubagentRun")(
1510 function* (scope: McpInvocationScope, threadId: ThreadId) {
1511 const shell = yield* threadManagement
1512 .getThreadShell(threadId)
1513 .pipe(Effect.mapError(threadManagementFailure));
1514 if (
1515 shell?.activeRunId !== null ||
1516 shell.latestRunId === null ||
1517 !isLiveCallerShell(shell, scope.thread?.providerInstanceId)
1518 ) {
1519 return undefined;
1520 }
1521 const { runs } = yield* loadThreadRecords(threadId, ["runs"], {
1522 runIds: [shell.latestRunId],
1523 });
1524 return runs[0];
1525 },
1526 );
1527
1528 const loadReadableThread = Effect.fn("OrchestratorMcpService.loadReadableThread")(function* (
1529 scope: McpInvocationScope,
1530 threadId: ThreadId,
1531 runLimit: number,
1532 ) {
1533 const { parent } = yield* loadCaller(scope, []);
1534 const shell = yield* threadManagement
1535 .getThreadShell(threadId)
1536 .pipe(Effect.mapError(threadManagementFailure));
1537 if (shell === null || shell.deletedAt !== null) {
1538 return yield* threadNotFound(
1539 threadManagement,
1540 scope,
1541 threadId,
1542 `Thread ${threadId} is no longer available.`,
1543 );
1544 }
1545 const input = { projectId: shell.projectId, threadId };
1546 // Acknowledging a caller's child-task result matches it against every run and transfer.
1547 if (
1548 parent !== undefined &&
1549 shell.lineage.parentThreadId === parent.thread.id &&
1550 shell.lineage.relationshipToParent === "subagent"
1551 ) {
1552 const target = yield* threadManagement
1553 .getProjectThreadRecords(input, [
1554 "runs",
1555 "providerTurns",
1556 "runtimeRequests",
1557 "contextTransfers",
1558 ])
1559 .pipe(Effect.mapError(threadManagementFailure));
1560 return { parent, target, shell, runCount: target.runs.length } as const;
1561 }
1562 // Long threads hold thousands of runs; the read shows only the recent and active ones.
1563 const [records, runCount] = yield* Effect.all([
1564 threadManagement.getProjectThreadRecords(input, ["runs", "runtimeRequests"], {
1565 latestRunLimit: runLimit,
1566 runStatuses: ThreadManagementService.ACTIVE_RUN_STATUSES,
1567 runtimeRequestStatuses: ["pending"],
1568 }),
1569 threadManagement.getRunCount(threadId),
1570 ]).pipe(Effect.mapError(threadManagementFailure));
1571 const { providerTurns } = yield* threadManagement
1572 .getProjectThreadRecords(input, ["providerTurns"], {
1573 providerTurnAttemptIds: records.runs.flatMap((run) => run.activeAttemptId ?? []),
1574 })
1575 .pipe(Effect.mapError(threadManagementFailure));
1576 const target = { ...records, providerTurns, contextTransfers: [] };
1577 return { parent, target, shell, runCount } as const;
1578 });
1579
1580 const loadProviders = providerRegistry.getProviders;
1581
1582 /** The folder the composer's model picker scans for this thread. */
1583 const parentWorkspaceCwd = (parent: Pick<OrchestrationV2ThreadProjection, "thread">) =>
1584 parent.thread.worktreePath
1585 ? Effect.succeed(parent.thread.worktreePath)
1586 : projects.getById(parent.thread.projectId).pipe(
1587 Effect.map((project) =>
1588 Option.getOrUndefined(Option.map(project, ({ workspaceRoot }) => workspaceRoot)),
1589 ),
1590 Effect.orElseSucceed(() => undefined),
1591 );
1592
1593 const scanWorkspace = (instanceId: ServerProvider["instanceId"], cwd: string) =>
1594 projects
1595 .workspaceScanDirectory(cwd)
1596 .pipe(
1597 Effect.flatMap((scanCwd) =>
1598 providerRegistry.refreshWorkspaceSnapshot({ instanceId, cwd, scanCwd }),
1599 ),
1600 );
1601
1602 const loadOrchestrationCapableInstanceIds = () =>
1603 providerAdapters.list().pipe(Effect.map((instanceIds) => new Set(instanceIds)));
1604
1605 /** Background agents miss foreground-only health probes; re-probe once before refusing. */
1606 const assertTargetEnabledForProject = (
1607 parent: Pick<OrchestrationV2ThreadProjection, "thread">,
1608 commandId: CommandId,
1609 target: ResolvedTarget,
1610 ) =>
1611 threadManagement
1612 .assertProviderInstanceEnabled({
1613 projectId: parent.thread.projectId,
1614 commandId,
1615 instanceId: target.modelSelection.instanceId,
1616 })
1617 .pipe(Effect.mapError(threadManagementFailure));
1618
1619 const resolveTargetRechecking = (
1620 input: Parameters<typeof resolveTarget>[0] & { readonly cwd: string | undefined },
1621 ) => {
1622 const instanceId =
1623 input.target?.providerInstanceId ??
1624 (input.target?.driverKind === undefined
1625 ? input.parent.thread.modelSelection.instanceId
1626 : undefined);
1627 const resolved = resolveTarget({
1628 ...input,
1629 providers: withWorkspaceModels(input.providers, input.cwd),
1630 });
1631 if (instanceId === undefined) return resolved;
1632 return resolved.pipe(
1633 Effect.catchIf(
1634 (error) => error.code === "provider_unavailable" || error.code === "model_unavailable",
1635 () =>
1636 (input.cwd === undefined
1637 ? providerRegistry.refreshInstance(instanceId)
1638 : providerRegistry
1639 .refreshInstance(instanceId)
1640 .pipe(Effect.andThen(scanWorkspace(instanceId, input.cwd)))
1641 ).pipe(
1642 Effect.flatMap((providers) =>
1643 resolveTarget({ ...input, providers: withWorkspaceModels(providers, input.cwd) }),
1644 ),
1645 ),
1646 ),
1647 );
1648 };
1649
1650 const resolveTarget = Effect.fn("OrchestratorMcpService.resolveTarget")(function* (input: {
1651 readonly parent: Pick<OrchestrationV2ThreadProjection, "thread">;
1652 readonly target: OrchestratorMcpTarget | undefined;
1653 readonly providers: ReadonlyArray<ServerProvider>;
1654 /** Receipt replays bypass current settings because they start no work. Dispatch must reuse the checked command ID. */
1655 readonly skipProjectEnablementFilter?: boolean;
1656 }): Effect.fn.Return<ResolvedTarget, OrchestratorMcpFailure> {
1657 const requestedInstanceId = input.target?.providerInstanceId;
1658 const requestedDriver = input.target?.driverKind;
1659 const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds();
1660 let instanceId = requestedInstanceId;
1661
1662 if (instanceId === undefined && requestedDriver !== undefined) {
1663 const candidates = input.providers.filter(
1664 (provider) =>
1665 provider.driver === requestedDriver &&
1666 orchestrationCapableInstanceIds.has(provider.instanceId),
1667 );
1668 if (candidates.length === 0) {
1669 return yield* failure(
1670 "provider_unavailable",
1671 `No V2 provider adapter is registered for driver ${requestedDriver}.`,
1672 );
1673 }
1674 const healthyCandidates = candidates.filter(
1675 (candidate) => providerConstraints(candidate, true).length === 0,
1676 );
1677 const inheritedCandidate = healthyCandidates.find(
1678 (candidate) => candidate.instanceId === input.parent.thread.modelSelection.instanceId,
1679 );
1680 const orderedCandidates = [
1681 ...(inheritedCandidate === undefined ? [] : [inheritedCandidate]),
1682 ...healthyCandidates.filter((candidate) => candidate !== inheritedCandidate),
1683 ];
1684 for (const candidate of orderedCandidates) {
1685 const enabledForProject =
1686 input.skipProjectEnablementFilter === true ||
1687 (yield* threadManagement.isProviderInstanceEnabledForProject({
1688 projectId: input.parent.thread.projectId,
1689 instanceId: candidate.instanceId,
1690 }));
1691 if (enabledForProject) {
1692 instanceId = candidate.instanceId;
1693 break;
1694 }
1695 }
1696 if (instanceId === undefined) {
1697 return yield* failure(
1698 "provider_unavailable",
1699 healthyCandidates.length === 0
1700 ? `No available V2 provider instance for driver ${requestedDriver}.`
1701 : `No instance of driver ${requestedDriver} is enabled for this project.`,
1702 );
1703 }
1704 }
1705 instanceId ??= input.parent.thread.modelSelection.instanceId;
1706
1707 const provider = input.providers.find((candidate) => candidate.instanceId === instanceId);
1708 if (provider === undefined) {
1709 return yield* failure(
1710 "provider_unavailable",
1711 `Provider instance ${instanceId} is not registered.`,
1712 );
1713 }
1714 if (requestedDriver !== undefined && provider.driver !== requestedDriver) {
1715 return yield* failure(
1716 "invalid_request",
1717 `Provider instance ${instanceId} uses driver ${provider.driver}, not ${requestedDriver}.`,
1718 );
1719 }
1720 const constraints = providerConstraints(
1721 provider,
1722 orchestrationCapableInstanceIds.has(provider.instanceId),
1723 );
1724 if (constraints.length > 0) {
1725 return yield* failure(
1726 "provider_unavailable",
1727 `Provider ${instanceId} cannot run a child task: ${constraints.join(" ")}`,
1728 );
1729 }
1730
1731 const inheritedSelection = input.parent.thread.modelSelection;
1732 const requestedModel = input.target?.model;
1733 const antigravityTarget =
1734 requestedModel === undefined ? undefined : antigravitySuffixedModel(provider, requestedModel);
1735 const model =
1736 antigravityTarget?.model ??
1737 requestedModel ??
1738 (instanceId === inheritedSelection.instanceId
1739 ? inheritedSelection.model
1740 : provider.models[0]?.slug);
1741 if (model === undefined) {
1742 return yield* failure(
1743 "model_unavailable",
1744 `Provider ${instanceId} has no model available for inheritance.`,
1745 );
1746 }
1747 if (requestedModel !== undefined) yield* requireAdvertisedModel(provider, model);
1748 const advertised = advertisedModel(provider, model);
1749 const descriptors = advertised?.capabilities?.optionDescriptors;
1750 const requestedOptions = withLegacyUltracodeEffort(descriptors, input.target?.options);
1751 if (requestedOptions !== undefined) {
1752 const invalid = invalidOptionSelections(requestedOptions, descriptors);
1753 if (invalid.length > 0) {
1754 return yield* failure(
1755 "invalid_request",
1756 `Model ${model} on provider ${instanceId} rejected options: ${invalid.join(" ")}`,
1757 );
1758 }
1759 }
1760
1761 const inheritsOptions =
1762 instanceId === inheritedSelection.instanceId &&
1763 (advertised?.slug ?? model) ===
1764 (advertisedModel(provider, inheritedSelection.model)?.slug ?? inheritedSelection.model);
1765 let options = inheritsOptions
1766 ? knownOptions(
1767 withLegacyUltracodeEffort(descriptors, inheritedSelection.options),
1768 descriptors,
1769 )
1770 : undefined;
1771 if (requestedOptions !== undefined || antigravityTarget !== undefined) {
1772 const selections = new Map(
1773 (requestedOptions?.length === 0 ? [] : (options ?? [])).map((selection) => [
1774 selection.id,
1775 selection,
1776 ]),
1777 );
1778 if (antigravityTarget !== undefined && requestedOptions?.length !== 0) {
1779 selections.set(antigravityTarget.thinking.id, antigravityTarget.thinking);
1780 }
1781 for (const selection of requestedOptions ?? []) {
1782 selections.set(selection.id, selection);
1783 }
1784 options = [...selections.values()];
1785 }
1786 return {
1787 modelSelection: { instanceId, model, ...(options === undefined ? {} : { options }) },
1788 supportedRuntimeModes: provider.supportedRuntimeModes,
1789 };
1790 });
1791
1792 const requestKey = (clientRequestId: string | undefined): Effect.Effect<string> =>
1793 clientRequestId === undefined ? random.uuidV4() : Effect.succeed(clientRequestId);
1794
1795 const readTask = Effect.fn("OrchestratorMcpService.readTask")(function* (
1796 scope: McpThreadInvocationScope,
1797 taskId: NodeId,
1798 waitTimedOut = false,
1799 acknowledgeTerminal = false,
1800 acknowledgementOperation = "task-status-acknowledge",
1801 ): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {
1802 yield* requireCapability(scope);
1803 const task = (yield* loadTasks(scope.thread.threadId, [taskId])).find(
1804 (candidate) =>
1805 candidate.id === taskId &&
1806 candidate.origin === "app_owned" &&
1807 candidate.threadId === scope.thread.threadId,
1808 );
1809 if (task === undefined || (task.childThreadId === null && task.remoteChild === undefined)) {
1810 return yield* failure(
1811 "task_not_found",
1812 `Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`,
1813 );
1814 }
1815 if (task.childThreadId === null) {
1816 return yield* readRemoteTask(scope, task, waitTimedOut, acknowledgeTerminal);
1817 }
1818 const childControls = yield* threadManagement
1819 .getThreadRecords(
1820 task.childThreadId,
1821 [
1822 "runs",
1823 "messages",
1824 "contextTransfers",
1825 "subagents",
1826 "providerThreads",
1827 "providerTurns",
1828 "runtimeRequests",
1829 "nodes",
1830 ],
1831 // Progress reads only active or undelivered tasks under the child.
1832 { messageRoles: ["user"], omitSettledLeafNodes: true, omitSettledSubagents: true },
1833 )
1834 .pipe(Effect.mapError(threadManagementFailure));
1835 const childRun = delegatedTaskRun(childControls, task);
1836 const progress = delegatedTaskProgress(childControls);
1837 const followupRuns =
1838 childRun?.delegatedTaskId === task.id ? delegatedTaskRuns(childControls, task.id) : undefined;
1839 const taskResultRun =
1840 followupRuns === undefined ? progress.resultRun : delegatedTaskResultRun(followupRuns);
1841 const taskWorkState =
1842 followupRuns === undefined
1843 ? progress.state
1844 : !isTerminalTaskStatus(taskStatusForRun(taskResultRun))
1845 ? "working"
1846 : delegatedTaskAwaitsWork(followupRuns, childControls)
1847 ? "waiting_for_children"
1848 : "result_available";
1849 const heldForRestart =
1850 task.result === null &&
1851 taskWorkState === "result_available" &&
1852 (yield* threadManagement
1853 .delegatedTaskResultPending(task.childThreadId, childRun?.delegatedTaskId)
1854 .pipe(Effect.mapError(threadManagementFailure)));
1855 const terminalRun = latestTerminalResultRun(
1856 childControls,
1857 childRun,
1858 heldForRestart ? taskResultRun : undefined,
1859 );
1860 // Only the task's own result looks back for its report, and only among its own runs.
1861 const reportRuns =
1862 task.result === null && taskResultRun !== undefined
1863 ? delegatedTaskReportRuns(childControls, taskResultRun)
1864 : [];
1865 const resultRunIds = [
1866 ...new Set(
1867 [taskResultRun?.id, terminalRun?.id, ...reportRuns.map((run) => run.id)].filter(
1868 (id): id is RunId => id !== undefined,
1869 ),
1870 ),
1871 ];
1872 const resultRecords = yield* threadManagement
1873 .getThreadRecords(task.childThreadId, ["messages", "turnItems"], {
1874 messageRoles: ["assistant"],
1875 messageRunIds: resultRunIds,
1876 turnItemRunIds: resultRunIds,
1877 turnItemTypes: ["assistant_message", "error", "system_notice"],
1878 })
1879 .pipe(Effect.mapError(threadManagementFailure));
1880 const childProjection = {
1881 ...childControls,
1882 messages: [...childControls.messages, ...resultRecords.messages],
1883 turnItems: resultRecords.turnItems,
1884 };
1885 const resultText = (run: OrchestrationV2Run) =>
1886 subagentResultForRun(
1887 { ...childProjection, runs: run.id === taskResultRun?.id ? reportRuns : [] },
1888 run,
1889 ).text;
1890 const workState =
1891 task.result !== null ? "result_available" : heldForRestart ? "working" : taskWorkState;
1892 const runStatus = taskStatusForRun(taskResultRun ?? childRun);
1893 const status =
1894 task.result !== null
1895 ? taskStatusForRun(
1896 task.status === "completed" ||
1897 task.status === "failed" ||
1898 task.status === "cancelled" ||
1899 task.status === "interrupted"
1900 ? { status: task.status }
1901 : childRun,
1902 )
1903 : workState === "result_available"
1904 ? // A cancelled task's finished turn settles it as interrupted.
1905 task.cancelledRunId !== undefined && runStatus === "completed"
1906 ? "interrupted"
1907 : runStatus
1908 : runStatus === "queued" || runStatus === "starting"
1909 ? runStatus
1910 : "running";
1911 const derivedResult =
1912 task.result !== null
1913 ? task.result
1914 : taskResultRun !== undefined && isTerminalTaskStatus(status)
1915 ? resultText(taskResultRun)
1916 : null;
1917 const resultTransfers = childControls.contextTransfers.filter(
1918 (transfer) =>
1919 transfer.type === "subagent_result" &&
1920 transfer.sourceThreadId === task.childThreadId &&
1921 transfer.targetThreadId === scope.thread.threadId,
1922 );
1923 const resultTransferForRun = (run: OrchestrationV2Run | undefined) =>
1924 !canExposeTaskRunResult(run)
1925 ? null
1926 : (resultTransfers.find((transfer) => transfer.sourcePoint.runId === run.id) ??
1927 (run.id === childRun?.id
1928 ? resultTransfers.find((transfer) => transfer.sourcePoint.runId === undefined)
1929 : undefined) ??
1930 null);
1931 const resultTransfer = taskResultTransfer(scope.thread.threadId, childProjection, task) ?? null;
1932 const terminalStatus = terminalRun === undefined ? null : taskStatusForRun(terminalRun);
1933 const latestTerminalSummary = canExposeTaskRunResult(terminalRun)
1934 ? terminalRun.id === childRun?.id
1935 ? derivedResult
1936 : resultText(terminalRun)
1937 : null;
1938 const resultContextTransferId = resultTransfer?.id ?? null;
1939 const latestTerminalResultContextTransferId = resultTransferForRun(terminalRun)?.id ?? null;
1940 const executionRun =
1941 task.result === null
1942 ? (taskResultRun ?? childRun)
1943 : (childControls.runs.find((run) => run.id === resultTransfer?.sourcePoint.runId) ??
1944 childRun);
1945 const modelSelection = executionRun?.modelSelection ??
1946 childControls.thread.modelSelection ?? {
1947 instanceId: task.providerInstanceId,
1948 model: task.model,
1949 };
1950 const result = {
1951 taskId: task.id,
1952 childThreadId: task.childThreadId,
1953 link: formatThreadLink(
1954 { environmentId: scope.environmentId, threadId: task.childThreadId },
1955 childControls.thread.title,
1956 ),
1957 childRunId: childRun?.id ?? null,
1958 childNodeId: task.id,
1959 status,
1960 workState,
1961 hasPendingChildRuns: hasPendingChildRuns(childProjection, childRun),
1962 providerInstanceId: modelSelection.instanceId,
1963 model: modelSelection.model,
1964 executedModel: runExecutedModel(childControls, executionRun),
1965 options: modelSelection.options ?? [],
1966 summary: derivedResult,
1967 resultContextTransferId,
1968 latestTerminalRunId: terminalRun?.id ?? null,
1969 latestTerminalStatus:
1970 terminalStatus !== null && isTerminalTaskStatus(terminalStatus) ? terminalStatus : null,
1971 latestTerminalSummary: latestTerminalSummary === derivedResult ? null : latestTerminalSummary,
1972 latestTerminalResultContextTransferId:
1973 latestTerminalResultContextTransferId === resultContextTransferId
1974 ? null
1975 : latestTerminalResultContextTransferId,
1976 hasPendingQuestion:
1977 !isTerminalTaskStatus(status) &&
1978 childControls.runtimeRequests.some(
1979 (request) =>
1980 request.kind === "user_input" &&
1981 request.status === "pending" &&
1982 request.responseCapability.type === "live",
1983 ),
1984 pendingApproval:
1985 isTerminalTaskStatus(status) || task.completionDelivery?.state === "disposed"
1986 ? null
1987 : pendingTaskApproval(childControls, task.id, childRun),
1988 waitTimedOut,
1989 } satisfies OrchestratorMcpDelegateTaskResult;
1990 const response: OrchestratorMcpDelegateTaskResult =
1991 endsTaskWait(result) || task.completionDelivery?.state === "disposed"
1992 ? result
1993 : { ...result, next: ORCHESTRATOR_MCP_RUNNING_TASK_NEXT };
1994 if (
1995 acknowledgeTerminal &&
1996 isTerminalTaskStatus(status) &&
1997 task.completionDelivery?.state !== "acknowledged" &&
1998 task.completionDelivery?.state !== "disposed"
1999 ) {
2000 const parentProjection = yield* loadCallerRecords(scope.thread.threadId, ["runs"]);
2001 const observingRun = ThreadManagementService.latestActiveRun({
2002 runs: parentProjection.runs.filter(
2003 (run) => run.providerInstanceId === scope.thread.providerInstanceId,
2004 ),
2005 });
2006 const acknowledgementRequestKey = yield* requestKey(undefined);
2007 yield* threadManagement
2008 .dispatch({
2009 type: "delegated_task.completion-delivery.acknowledge",
2010 commandId: stableCommandId({
2011 scope,
2012 requestKey: acknowledgementRequestKey,
2013 operation: acknowledgementOperation,
2014 }),
2015 parentThreadId: scope.thread.threadId,
2016 taskId,
2017 observedByRunId: observingRun?.id ?? null,
2018 })
2019 .pipe(
2020 Effect.mapError((error) =>
2021 failure(
2022 "orchestration_error",
2023 `Unable to acknowledge delegated task ${taskId}: ${errorMessage(error)}`,
2024 ),
2025 ),
2026 );
2027 }
2028 return response;
2029 });
2030
2031 /**
2032 * Blocks for `mode=wait`. A wait that ends without a terminal result, including an
2033 * interrupted tools/call, upgrades the wake so a later result still reaches the parent.
2034 */
2035 const awaitTask = Effect.fn("OrchestratorMcpService.awaitTask")(function* (
2036 scope: McpThreadInvocationScope,
2037 taskId: NodeId,
2038 wakePolicyRequestKey: string,
2039 requestedTimeoutMs: number | undefined,
2040 restore: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> = (effect) =>
2041 effect,
2042 ): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {
2043 const timeoutMs = Math.min(
2044 MAX_WAIT_TIMEOUT_MS,
2045 Math.max(1, requestedTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
2046 );
2047 const upgradeWake = threadManagement
2048 .dispatch({
2049 type: "delegated_task.wake-policy",
2050 commandId: stableCommandId({
2051 scope,
2052 requestKey: wakePolicyRequestKey,
2053 operation: "delegate-task-wake-policy",
2054 }),
2055 parentThreadId: scope.thread.threadId,
2056 taskId,
2057 completionWake: "always",
2058 })
2059 .pipe(
2060 Effect.catch((error) =>
2061 Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {
2062 taskId,
2063 outcome:
2064 error._tag === "OrchestratorCommandPreviouslyRejectedError"
2065 ? "previously_rejected"
2066 : "dispatch_failed",
2067 error,
2068 }),
2069 ),
2070 Effect.catchCause((cause) =>
2071 Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", {
2072 taskId,
2073 outcome: "defect",
2074 cause,
2075 }),
2076 ),
2077 );
2078 const delivered = (waited: Option.Option<OrchestratorMcpDelegateTaskResult>) =>
2079 Option.isSome(waited) && isTerminalTaskStatus(waited.value.status);
2080 // The finalizer runs uninterruptibly, and only the wait and the fallback read are
2081 // restored, so a cancel just before or after the wait still upgrades without the read
2082 // acknowledging a result the caller never receives.
2083 const waited = yield* restore(waitForTask(scope, taskId, timeoutMs)).pipe(
2084 Effect.onExit((exit) =>
2085 Exit.isSuccess(exit) && delivered(exit.value) ? Effect.void : upgradeWake,
2086 ),
2087 );
2088 if (Option.isSome(waited) && delivered(waited)) return waited.value;
2089 return yield* restore(readTask(scope, taskId, Option.isNone(waited), true));
2090 });
2091
2092 /**
2093 * A task that runs in a linked environment, answered from its row here:
2094 * the follower records its result once its thread there ends.
2095 */
2096 const readRemoteTask = Effect.fn("OrchestratorMcpService.readRemoteTask")(function* (
2097 scope: McpThreadInvocationScope,
2098 task: OrchestrationV2Subagent,
2099 waitTimedOut: boolean,
2100 acknowledgeTerminal: boolean,
2101 ): Effect.fn.Return<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> {
2102 const status: OrchestratorMcpDelegateTaskResult["status"] =
2103 task.result === null
2104 ? (yield* remoteDelegation.runStatus(scope, task)) === "starting"
2105 ? "starting"
2106 : "running"
2107 : task.status === "completed" ||
2108 task.status === "failed" ||
2109 task.status === "cancelled" ||
2110 task.status === "interrupted"
2111 ? task.status
2112 : "completed";
2113 const terminal = isTerminalTaskStatus(status);
2114 if (
2115 acknowledgeTerminal &&
2116 terminal &&
2117 task.completionDelivery?.state !== "acknowledged" &&
2118 task.completionDelivery?.state !== "disposed"
2119 ) {
2120 const parentProjection = yield* loadCallerRecords(scope.thread.threadId, ["runs"]);
2121 const observingRun = ThreadManagementService.latestActiveRun({
2122 runs: parentProjection.runs.filter(
2123 (run) => run.providerInstanceId === scope.thread.providerInstanceId,
2124 ),
2125 });
2126 yield* threadManagement
2127 .dispatch({
2128 type: "delegated_task.completion-delivery.acknowledge",
2129 commandId: stableCommandId({
2130 scope,
2131 requestKey: yield* requestKey(undefined),
2132 operation: "task-status-acknowledge",
2133 }),
2134 parentThreadId: scope.thread.threadId,
2135 taskId: task.id,
2136 observedByRunId: observingRun?.id ?? null,
2137 })
2138 .pipe(
2139 Effect.mapError((error) =>
2140 failure(
2141 "orchestration_error",
2142 `Unable to acknowledge delegated task ${task.id}: ${errorMessage(error)}`,
2143 ),
2144 ),
2145 );
2146 }
2147 return {
2148 taskId: task.id,
2149 childThreadId: null,
2150 ...(task.remoteChild === undefined
2151 ? {}
2152 : {
2153 remoteChild: task.remoteChild,
2154 link: formatThreadLink(task.remoteChild, task.remoteChild.title),
2155 }),
2156 childRunId: null,
2157 childNodeId: task.id,
2158 status,
2159 workState: terminal ? "result_available" : "working",
2160 hasPendingChildRuns: false,
2161 providerInstanceId: task.providerInstanceId,
2162 model: task.model,
2163 executedModel: task.executedModel ?? null,
2164 summary: task.result,
2165 resultContextTransferId: null,
2166 latestTerminalRunId: null,
2167 latestTerminalStatus: terminal
2168 ? (status as OrchestratorMcpDelegateTaskResult["latestTerminalStatus"])
2169 : null,
2170 latestTerminalSummary: terminal ? task.result : null,
2171 latestTerminalResultContextTransferId: null,
2172 // Its questions and approvals are answered in the environment it runs in.
2173 hasPendingQuestion: false,
2174 pendingApproval: null,
2175 waitTimedOut,
2176 } satisfies OrchestratorMcpDelegateTaskResult;
2177 });
2178
2179 const waitForTask = Effect.fn("OrchestratorMcpService.waitForTask")(
2180 function* (scope: McpThreadInvocationScope, taskId: NodeId, _timeoutMs: number) {
2181 const streamError = (error: unknown) =>
2182 failure(
2183 "orchestration_error",
2184 `Unable to watch delegated task ${taskId}: ${errorMessage(error)}`,
2185 );
2186 // One global cursor before both reads captures later events from either thread.
2187 const afterSequence = yield* threadManagement
2188 .getThreadEventSequence(scope.thread.threadId)
2189 .pipe(Effect.mapError(streamError));
2190 const initial = yield* readTask(scope, taskId, false, true);
2191 if (endsTaskWait(initial)) {
2192 return Option.some(initial);
2193 }
2194 // One stream per event type, so transcript events never fill a buffer.
2195 // A remote task has no child here; its completion lands on the parent.
2196 const childThreadId = initial.childThreadId;
2197 const wakeEvents =
2198 childThreadId === null
2199 ? TASK_WAKE_EVENTS.filter(({ thread }) => thread === "parent")
2200 : TASK_WAKE_EVENTS;
2201 return yield* Stream.mergeAll(
2202 wakeEvents.map(({ thread, eventType }) =>
2203 threadManagement
2204 .streamStoredEventsFrom({
2205 threadId:
2206 thread === "parent" || childThreadId === null
2207 ? scope.thread.threadId
2208 : childThreadId,
2209 afterSequence,
2210 eventType,
2211 })
2212 .pipe(
2213 Stream.filter(
2214 ({ event }) =>
2215 thread === "child" ||
2216 event.type !== "subagent.updated" ||
2217 event.payload.id === taskId,
2218 ),
2219 ),
2220 ),
2221 { concurrency: "unbounded" },
2222 ).pipe(
2223 Stream.mapError(streamError),
2224 Stream.mapEffect(() => readTask(scope, taskId, false, true)),
2225 Stream.filter(endsTaskWait),
2226 Stream.runHead,
2227 );
2228 },
2229 (effect, _scope, _taskId, timeoutMs) =>
2230 effect.pipe(Effect.timeoutOption(Duration.millis(timeoutMs)), Effect.map(Option.flatten)),
2231 );
2232
2233 const refExists = (cwd: string, revision: string) =>
2234 gitDriver.resolveCommit({ cwd, revision }).pipe(
2235 Effect.as(true),
2236 Effect.orElseSucceed(() => false),
2237 );
2238
2239 const resolveScheduledTaskBaseRef = Effect.fn(
2240 "OrchestratorMcpService.resolveScheduledTaskBaseRef",
2241 )(function* (cwd: string) {
2242 const remoteName = yield* gitDriver
2243 .resolvePrimaryRemoteName(cwd)
2244 .pipe(Effect.orElseSucceed(() => null));
2245 const conventional = ["main", "master"];
2246 if (remoteName !== null) {
2247 const remoteDefault = yield* gitDriver
2248 .resolveDefaultBranchName(cwd, remoteName)
2249 .pipe(Effect.orElseSucceed(() => null));
2250 // Fetch does not update a recorded HEAD, so it can outlive the branch it names.
2251 for (const branch of remoteDefault === null
2252 ? conventional
2253 : [remoteDefault, ...conventional]) {
2254 // Launch resolves a bare name through a local branch's upstream, or else assumes `origin`.
2255 if (yield* refExists(cwd, `refs/remotes/${remoteName}/${branch}`)) {
2256 return `${remoteName}/${branch}`;
2257 }
2258 }
2259 }
2260 // Local-only repositories, or a remote with neither a usable HEAD nor a conventional branch.
2261 for (const branch of conventional) {
2262 if (yield* refExists(cwd, `refs/heads/${branch}`)) return branch;
2263 }
2264 return "main";
2265 });
2266
2267 const scheduledTaskWorkspaceStrategy = Effect.fn(
2268 "OrchestratorMcpService.scheduledTaskWorkspaceStrategy",
2269 )(function* (boundToThread: boolean, projectId: ProjectId) {
2270 if (boundToThread) return { type: "root" as const };
2271 const { workspaceRoot } = yield* requireProject(projectId);
2272 return {
2273 type: "worktree" as const,
2274 baseRef: yield* resolveScheduledTaskBaseRef(workspaceRoot),
2275 startFromOrigin: true,
2276 };
2277 });
2278
2279 const scheduledTaskRunModes = Effect.fn("OrchestratorMcpService.scheduledTaskRunModes")(
2280 function* (task: ScheduledTask) {
2281 const modes = [{ runtimeMode: task.runtimeMode, interactionMode: task.interactionMode }];
2282 if (task.threadId === null) return modes;
2283 const bound = yield* threadManagement
2284 .getThreadShell(task.threadId)
2285 .pipe(Effect.mapError(threadManagementFailure));
2286 return bound === null || bound.deletedAt !== null ? modes : [...modes, bound];
2287 },
2288 );
2289
2290 const withinLimits = (
2291 limits: {
2292 readonly runtimeMode: RuntimeMode;
2293 readonly interactionMode: ProviderInteractionMode;
2294 },
2295 modes: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode },
2296 ) =>
2297 runtimeModeRank(modes.runtimeMode) <= runtimeModeRank(limits.runtimeMode) &&
2298 interactionModeRank(modes.interactionMode) <= interactionModeRank(limits.interactionMode);
2299
2300 /**
2301 * Creation returns a webhook URL only to callers allowed to start its runs: never a read-only
2302 * client, and a thread caller only with a live turn at modes covering every mode the task runs at.
2303 */
2304 const summarizeScheduledTask = Effect.fn("OrchestratorMcpService.summarizeScheduledTask")(
2305 function* (
2306 scope: McpInvocationScope,
2307 caller: {
2308 readonly parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs"> | undefined;
2309 readonly limits: {
2310 readonly runtimeMode: RuntimeMode;
2311 readonly interactionMode: ProviderInteractionMode;
2312 };
2313 },
2314 task: ScheduledTask,
2315 ) {
2316 const live =
2317 caller.parent === undefined
2318 ? scope.client?.access !== "read-only"
2319 : Exit.isSuccess(yield* Effect.exit(assertLiveCaller(scope, caller.parent)));
2320 const modes = yield* scheduledTaskRunModes(task).pipe(Effect.option);
2321 return scheduledTaskSummary(
2322 task,
2323 live &&
2324 Option.isSome(modes) &&
2325 modes.value.every((mode) => withinLimits(caller.limits, mode)),
2326 );
2327 },
2328 );
2329
2330 /**
2331 * A scheduled task the caller may change: one whose runs execute at modes no
2332 * broader than the caller's own, so editing its prompt cannot run work above
2333 * the caller's limits.
2334 */
2335 const loadScheduledTask = Effect.fn("OrchestratorMcpService.loadScheduledTask")(function* (
2336 scheduledTaskId: ScheduledTask["id"],
2337 limits: {
2338 readonly runtimeMode: RuntimeMode;
2339 readonly interactionMode: ProviderInteractionMode;
2340 },
2341 ): Effect.fn.Return<ScheduledTask, OrchestratorMcpFailure> {
2342 const { tasks } = yield* scheduledTasks
2343 .list()
2344 .pipe(
2345 Effect.mapError((error) =>
2346 failure("orchestration_error", `Could not load scheduled task: ${error.message}`),
2347 ),
2348 );
2349 const task = tasks.find((candidate) => candidate.id === scheduledTaskId);
2350 if (task === undefined) {
2351 return yield* failure("task_not_found", `Scheduled task ${scheduledTaskId} was not found.`);
2352 }
2353 for (const modes of yield* scheduledTaskRunModes(task)) {
2354 yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode);
2355 yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode);
2356 }
2357 return task;
2358 });
2359
2360 return OrchestratorMcpService.of({
2361 scheduleTask: Effect.fn("OrchestratorMcpService.scheduleTask")(function* (scope, input) {
2362 const { parent, limits } = yield* loadCaller(scope, ["runs"]);
2363 const projectId = yield* resolveProjectTarget(parent, input.projectId);
2364 yield* assertLiveCallerForOtherProject(scope, parent, projectId);
2365 const project = yield* requireProject(projectId);
2366 const bindToCurrentThread =
2367 input.bindToCurrentThread ??
2368 (parent !== undefined && parent.thread.projectId === projectId);
2369 if (bindToCurrentThread && (parent === undefined || parent.thread.projectId !== projectId)) {
2370 return yield* failure(
2371 "invalid_request",
2372 parent === undefined
2373 ? "bindToCurrentThread needs an agent running inside a T3 thread."
2374 : "bindToCurrentThread binds to this thread, which belongs to a different project.",
2375 );
2376 }
2377 const modelSelection =
2378 parent?.thread.modelSelection ?? (yield* projectDefaultModelSelection(project));
2379 // Never end on a lone high surrogate, which renders as a broken character.
2380 const derivedTitle = (input.prompt.split("\n")[0]?.trim() ?? "")
2381 .slice(0, 80)
2382 .replace(/[\uD800-\uDBFF]$/, "");
2383 const title = input.title ?? (derivedTitle.length > 0 ? derivedTitle : "Scheduled task");
2384 const upsertInput: ScheduledTaskUpsertInput = {
2385 title,
2386 prompt: input.prompt,
2387 enabled: input.enabled ?? true,
2388 schedule: input.schedule,
2389 projectId,
2390 threadId: bindToCurrentThread && parent !== undefined ? parent.thread.id : null,
2391 threadMode: input.freshSession
2392 ? "fresh_session"
2393 : bindToCurrentThread
2394 ? "continue"
2395 : "new_thread",
2396 workspaceStrategy: yield* scheduledTaskWorkspaceStrategy(bindToCurrentThread, projectId),
2397 modelSelection,
2398 runtimeMode: limits.runtimeMode,
2399 interactionMode: limits.interactionMode,
2400 createdBy: "agent",
2401 creationSource: "mcp",
2402 // Scope the idempotency key by provider session so two callers
2403 // reusing the same clientRequestId cannot collide on one task row.
2404 ...(input.clientRequestId === undefined
2405 ? {}
2406 : {
2407 commandId: stableCommandId({
2408 scope,
2409 requestKey: input.clientRequestId,
2410 operation: "schedule-task",
2411 }),
2412 }),
2413 };
2414 const { task } = yield* scheduledTasks
2415 .upsert(upsertInput)
2416 .pipe(
2417 Effect.mapError((error) =>
2418 failure("orchestration_error", `Could not schedule task: ${error.message}`),
2419 ),
2420 );
2421 return yield* summarizeScheduledTask(scope, { parent, limits }, task);
2422 }),
2423 listScheduledTasks: Effect.fn("OrchestratorMcpService.listScheduledTasks")(
2424 function* (scope, input) {
2425 const { parent } = yield* loadCaller(scope, []);
2426 const projectId = input.projectId ?? parent?.thread.projectId;
2427 const { tasks } = yield* scheduledTasks
2428 .list()
2429 .pipe(
2430 Effect.mapError((error) =>
2431 failure("orchestration_error", `Could not list scheduled tasks: ${error.message}`),
2432 ),
2433 );
2434 return {
2435 tasks: tasks
2436 .filter(
2437 (task) =>
2438 (projectId === undefined || task.projectId === projectId) &&
2439 (input.scheduledTaskId === undefined || task.id === input.scheduledTaskId),
2440 )
2441 .map((task) => scheduledTaskSummary(task, false)),
2442 };
2443 },
2444 ),
2445 updateScheduledTask: Effect.fn("OrchestratorMcpService.updateScheduledTask")(
2446 function* (scope, input) {
2447 const { parent, limits } = yield* loadCaller(scope, ["runs"]);
2448 const existing = yield* loadScheduledTask(input.scheduledTaskId, limits);
2449 yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId);
2450 if (
2451 input.bindToCurrentThread === true &&
2452 (parent === undefined || parent.thread.projectId !== existing.projectId)
2453 ) {
2454 return yield* failure(
2455 "invalid_request",
2456 parent === undefined
2457 ? "bindToCurrentThread needs an agent running inside a T3 thread."
2458 : "bindToCurrentThread binds to this thread, which belongs to a different project.",
2459 );
2460 }
2461 // A save keeps a bound thread unless the task goes back to new threads, so this pair
2462 // would leave runs in the old thread.
2463 if (
2464 input.bindToCurrentThread === false &&
2465 input.freshSession === true &&
2466 existing.threadId !== null
2467 ) {
2468 return yield* failure(
2469 "invalid_request",
2470 "To move this task to a new thread with fresh sessions, first unbind it with bindToCurrentThread: false, then set freshSession: true in a second call.",
2471 );
2472 }
2473 const threadId =
2474 input.bindToCurrentThread === undefined
2475 ? existing.threadId
2476 : input.bindToCurrentThread && parent !== undefined
2477 ? parent.thread.id
2478 : null;
2479 // Reset the workspace only when the binding flips, so unbinding cannot leave runs in the shared checkout.
2480 const workspaceStrategy =
2481 (threadId === null) === (existing.threadId === null)
2482 ? existing.workspaceStrategy
2483 : yield* scheduledTaskWorkspaceStrategy(threadId !== null, existing.projectId);
2484 const upsertInput: ScheduledTaskUpsertInput = {
2485 id: existing.id,
2486 title: input.title ?? existing.title,
2487 prompt: input.prompt ?? existing.prompt,
2488 enabled: input.enabled ?? existing.enabled,
2489 schedule: input.schedule ?? existing.schedule,
2490 projectId: existing.projectId,
2491 threadId,
2492 threadMode:
2493 input.freshSession === undefined && input.bindToCurrentThread === undefined
2494 ? scheduledTaskThreadMode(existing)
2495 : (input.freshSession ??
2496 (input.bindToCurrentThread !== false &&
2497 scheduledTaskThreadMode(existing) === "fresh_session"))
2498 ? "fresh_session"
2499 : threadId === null &&
2500 (input.bindToCurrentThread === false ||
2501 scheduledTaskThreadMode(existing) === "new_thread")
2502 ? "new_thread"
2503 : "continue",
2504 workspaceStrategy,
2505 modelSelection: existing.modelSelection,
2506 runtimeMode: existing.runtimeMode,
2507 interactionMode: existing.interactionMode,
2508 createdBy: existing.createdBy,
2509 creationSource: existing.creationSource,
2510 };
2511 const { task } = yield* scheduledTasks
2512 .upsert(upsertInput)
2513 .pipe(
2514 Effect.mapError((error) =>
2515 failure("orchestration_error", `Could not update scheduled task: ${error.message}`),
2516 ),
2517 );
2518 return scheduledTaskSummary(task, false);
2519 },
2520 ),
2521 deleteScheduledTask: Effect.fn("OrchestratorMcpService.deleteScheduledTask")(
2522 function* (scope, input) {
2523 const { parent, limits } = yield* loadCaller(scope, ["runs"]);
2524 const existing = yield* loadScheduledTask(input.scheduledTaskId, limits);
2525 yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId);
2526 yield* scheduledTasks
2527 .delete({ id: existing.id })
2528 .pipe(
2529 Effect.mapError((error) =>
2530 failure("orchestration_error", `Could not delete scheduled task: ${error.message}`),
2531 ),
2532 );
2533 return { scheduledTaskId: existing.id, deleted: true };
2534 },
2535 ),
2536 requestSecret: Effect.fn("OrchestratorMcpService.requestSecret")(function* (scope, input) {
2537 const { scope: threadScope, parent } = yield* loadThreadCaller(scope, "request_secret");
2538 const threadId = threadScope.thread.threadId;
2539 const run = ThreadManagementService.latestActiveRun(parent);
2540 if (
2541 run === undefined ||
2542 run.rootNodeId === null ||
2543 run.providerInstanceId !== threadScope.thread.providerInstanceId
2544 ) {
2545 return yield* failure(
2546 "parent_not_active",
2547 "Asking for a secret requires an active run owned by this MCP provider session.",
2548 );
2549 }
2550 if (
2551 input.fields !== undefined &&
2552 (input.value !== undefined || input.delivery === "secretRef")
2553 ) {
2554 return yield* failure(
2555 "invalid_request",
2556 '`fields` values are saved as files. Leave out `value` and `delivery: "secretRef"`.',
2557 );
2558 }
2559 const delivery = input.fields === undefined ? input.delivery : "file";
2560 // A secret the user already pasted needs no card: it goes straight to a file.
2561 if (input.value !== undefined) {
2562 if (input.delivery === "secretRef") {
2563 return yield* failure(
2564 "invalid_request",
2565 'A pasted `value` is saved as a file. Leave out `delivery: "secretRef"`.',
2566 );
2567 }
2568 const file = yield* secretRequests
2569 .savePasted({
2570 threadId,
2571 requestNamespace: scope.requestNamespace,
2572 requestKey: yield* requestKey(input.clientRequestId),
2573 value: input.value,
2574 })
2575 .pipe(Effect.mapError((error) => failure("orchestration_error", error.message)));
2576 yield* Effect.annotateCurrentSpan({ "secret_request.status": "saved_pasted" });
2577 yield* Metrics.increment(Metrics.secretRequestsTotal, { status: "saved_pasted" });
2578 return { status: "saved" as const, file };
2579 }
2580 const runId = run.id;
2581 const nodeId = run.rootNodeId;
2582 const key = `${runId}:${yield* requestKey(input.clientRequestId)}`;
2583 const turnItemId = TurnItemId.make(
2584 `turn-item:secret-request:${stablePart(threadId)}:${stablePart(key)}`,
2585 );
2586 const record = (secretStatus: "pending" | "cancelled") =>
2587 threadManagement
2588 .dispatch({
2589 type: "secret_request.record",
2590 commandId: stableCommandId({
2591 scope,
2592 requestKey: key,
2593 operation: `secret-${secretStatus}`,
2594 }),
2595 threadId: threadId,
2596 runId,
2597 nodeId,
2598 turnItemId,
2599 label: input.label,
2600 reason: input.reason,
2601 ...(input.url === undefined ? {} : { url: input.url }),
2602 ...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }),
2603 ...(delivery === "file" ? { delivery: "file" as const } : {}),
2604 ...(input.fields === undefined ? {} : { fields: input.fields }),
2605 secretStatus,
2606 })
2607 .pipe(
2608 Effect.mapError((error) =>
2609 failure(
2610 "orchestration_error",
2611 `Could not record the secret request: ${errorMessage(error)}`,
2612 ),
2613 ),
2614 );
2615 yield* record("pending");
2616 // Only this call can hand the agent its ref, so the card must not
2617 // outlive it: a timeout, a failed wait or an aborted call closes it as
2618 // cancelled.
2619 const closeCard = record("cancelled").pipe(
2620 Effect.catch((error) =>
2621 Effect.logWarning("Could not close a secret request card", { error: error.message }),
2622 ),
2623 );
2624
2625 const answered = yield* Effect.gen(function* () {
2626 while (true) {
2627 const projection = yield* threadManagement
2628 .getThreadRecords(threadId, ["runs", "turnItems"], {
2629 turnItemTypes: ["secret_request"],
2630 messageRoles: [],
2631 })
2632 .pipe(
2633 Effect.mapError((error) =>
2634 failure(
2635 "orchestration_error",
2636 `Unable to read the secret request: ${errorMessage(error)}`,
2637 ),
2638 ),
2639 );
2640 const item = projection.turnItems.find((candidate) => candidate.id === turnItemId);
2641 if (item?.type === "secret_request" && item.secretStatus !== "pending") {
2642 return item.secretStatus;
2643 }
2644 const current = projection.runs.find((candidate) => candidate.id === runId);
2645 if (
2646 current === undefined ||
2647 ThreadManagementService.isTerminalRunStatus(current.status)
2648 ) {
2649 yield* record("cancelled");
2650 return "cancelled" as const;
2651 }
2652 // A steering restart replaced the run's root, so this request belonged to
2653 // the superseded attempt: its card can never be answered into that attempt,
2654 // and the call must stop blocking the agent's turn.
2655 if (current.rootNodeId !== nodeId) {
2656 yield* record("cancelled");
2657 return "cancelled" as const;
2658 }
2659 yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS));
2660 }
2661 }).pipe(
2662 Effect.timeoutOption(
2663 Duration.millis(
2664 Math.min(
2665 input.timeoutMs ?? DEFAULT_SECRET_REQUEST_TIMEOUT_MS,
2666 MAX_SECRET_REQUEST_TIMEOUT_MS,
2667 ),
2668 ),
2669 ),
2670 Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : closeCard)),
2671 );
2672 if (Option.isNone(answered)) yield* closeCard;
2673 const status = Option.isSome(answered)
2674 ? answered.value
2675 : yield* threadManagement
2676 .getThreadRecords(threadId, ["turnItems"], {
2677 turnItemTypes: ["secret_request"],
2678 messageRoles: [],
2679 })
2680 .pipe(
2681 Effect.map((records) => {
2682 const item = records.turnItems.find((candidate) => candidate.id === turnItemId);
2683 return item?.type === "secret_request" &&
2684 (item.secretStatus === "saved" || item.secretStatus === "declined")
2685 ? item.secretStatus
2686 : ("timed_out" as const);
2687 }),
2688 Effect.orElseSucceed(() => "timed_out" as const),
2689 );
2690 yield* Effect.annotateCurrentSpan({ "secret_request.status": status });
2691 yield* Metrics.increment(Metrics.secretRequestsTotal, { status });
2692 if (status !== "saved") return { status, note: SECRET_REQUEST_UNSAVED_NOTE[status] };
2693 if (delivery === "file") {
2694 const saved = yield* secretRequests
2695 .saveToFile({ threadId, turnItemId })
2696 .pipe(Effect.mapError((error) => failure("orchestration_error", error.message)));
2697 return { status, ...saved };
2698 }
2699 const secretRef = yield* secretRequests.savedRef({ threadId: threadId, turnItemId });
2700 if (Option.isNone(secretRef)) {
2701 return yield* failure(
2702 "orchestration_error",
2703 "The user saved the secret, but it could not be read. Ask again with a new clientRequestId.",
2704 );
2705 }
2706 return { status, secretRef: secretRef.value };
2707 }),
2708
2709 capabilities: Effect.fn("OrchestratorMcpService.capabilities")(function* (scope, input = {}) {
2710 const { parent, limits } = yield* loadCaller(scope, []);
2711 const cwd = parent === undefined ? undefined : yield* parentWorkspaceCwd(parent);
2712 const machineProviders = yield* loadProviders;
2713 const unscanned =
2714 cwd === undefined
2715 ? []
2716 : machineProviders.filter(
2717 (provider) =>
2718 provider.enabled &&
2719 !provider.workspaceSnapshots?.some((snapshot) => snapshot.cwd === cwd),
2720 );
2721 if (cwd !== undefined && unscanned.length > 0) {
2722 yield* Effect.forEach(unscanned, (provider) => scanWorkspace(provider.instanceId, cwd), {
2723 concurrency: "unbounded",
2724 discard: true,
2725 });
2726 }
2727 const providers = withWorkspaceModels(
2728 unscanned.length > 0 ? yield* loadProviders : machineProviders,
2729 cwd,
2730 );
2731 const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds();
2732 const settings = yield* serverSettings.getSettings.pipe(
2733 Effect.mapError(() => failure("orchestration_error", "Unable to read server settings.")),
2734 );
2735 const inherited = parent?.thread.modelSelection;
2736 const searchTerms = input.search?.toLowerCase().split(/\s+/).filter(Boolean) ?? [];
2737 return {
2738 parentThreadId: parent?.thread.id ?? null,
2739 inheritedProviderInstanceId: inherited?.instanceId ?? null,
2740 inheritedModel: inherited?.model ?? null,
2741 inheritedOptions:
2742 knownOptions(
2743 inherited?.options,
2744 providers
2745 .find((provider) => provider.instanceId === inherited?.instanceId)
2746 ?.models.find((model) => model.slug === inherited?.model)?.capabilities
2747 ?.optionDescriptors,
2748 ) ?? [],
2749 runtimeMode: limits.runtimeMode,
2750 interactionMode: limits.interactionMode,
2751 providers: providers.map((provider) => {
2752 // Snapshots list instances any project enables; delegate_task checks the caller's project.
2753 const enabledForCaller =
2754 parent === undefined ||
2755 resolveProjectProviderInstanceEnabled(
2756 settings,
2757 parent.thread.projectId,
2758 provider.instanceId,
2759 );
2760 const constraints = providerConstraints(
2761 enabledForCaller ? provider : { ...provider, enabled: false },
2762 orchestrationCapableInstanceIds.has(provider.instanceId),
2763 );
2764 const { listed, omitted } = listCapabilityModels({
2765 provider,
2766 preferences: settings.providerModelPreferences?.[provider.instanceId],
2767 searchTerms,
2768 isPinned: (model) =>
2769 model.isCustom ||
2770 (inherited?.instanceId === provider.instanceId && inherited.model === model.slug) ||
2771 (settings.favorites ?? []).some(
2772 (favorite) =>
2773 favorite.provider === provider.instanceId && favorite.model === model.slug,
2774 ),
2775 });
2776 return {
2777 providerInstanceId: provider.instanceId,
2778 driverKind: provider.driver,
2779 displayName: provider.displayName ?? null,
2780 models: listed.map((model) => {
2781 const options = model.capabilities?.optionDescriptors ?? [];
2782 return {
2783 id: model.slug,
2784 ...(model.name.toLowerCase() === model.slug.toLowerCase()
2785 ? {}
2786 : { label: model.name }),
2787 ...(options.length === 0 ? {} : { options: options.map(capabilityModelOption) }),
2788 };
2789 }),
2790 ...(omitted === 0 ? {} : { omittedModels: omitted }),
2791 ...(provider.supportedRuntimeModes === undefined ||
2792 provider.supportedRuntimeModes.length === 0
2793 ? {}
2794 : { runtimeModes: [...provider.supportedRuntimeModes] }),
2795 canRunChildTask: constraints.length === 0,
2796 canRunCrossProviderChildTask: constraints.length === 0,
2797 constraints: [...constraints],
2798 };
2799 }),
2800 features: {
2801 appOwnedSubagents: true,
2802 asyncPolling: true,
2803 cancellation: true,
2804 batchThreadCreation: true,
2805 threadManagement: true,
2806 incrementalThreadRead: true,
2807 scheduledTasks: true,
2808 maxBatchThreads: 20,
2809 },
2810 };
2811 }),
2812 delegateTask: Effect.fn("OrchestratorMcpService.delegateTask")(function* (callerScope, input) {
2813 const environmentId =
2814 input.target === undefined
2815 ? undefined
2816 : PeerForwarding.remoteTarget(callerScope, input.target.environmentId);
2817 if (input.target !== undefined && environmentId !== undefined) {
2818 yield* requireCapability(callerScope);
2819 const scope = yield* requireThreadScope(callerScope, "delegate_task");
2820 // The task's child runs as an ordinary thread there; this thread keeps the task.
2821 const { taskId } = yield* remoteDelegation.delegate(scope, {
2822 ...input,
2823 target: { ...input.target, environmentId },
2824 });
2825 return yield* input.mode === "wait"
2826 ? awaitTask(scope, taskId, taskId, input.timeoutMs)
2827 : readTask(scope, taskId, false, true);
2828 }
2829 const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task");
2830 if (
2831 input.target?.projectId !== undefined &&
2832 input.target.projectId !== parent.thread.projectId
2833 ) {
2834 return yield* failure(
2835 "invalid_request",
2836 "A local task runs in this thread's project. Omit target.projectId, or pass target.environmentId to run it in that environment's project.",
2837 );
2838 }
2839 const parentRun =
2840 ThreadManagementService.latestActiveRun(parent) ??
2841 (yield* backgroundSubagentRun(scope, parent.thread.id));
2842 if (
2843 parentRun === undefined ||
2844 parentRun.rootNodeId === null ||
2845 parentRun.providerInstanceId !== scope.thread.providerInstanceId
2846 ) {
2847 return yield* failure(
2848 "parent_not_active",
2849 "Delegated tasks require an active run owned by this MCP provider session.",
2850 );
2851 }
2852 const providers = yield* loadProviders;
2853 const key = yield* requestKey(input.clientRequestId);
2854 const commandId = stableCommandId({
2855 scope,
2856 requestKey: key,
2857 operation: "delegate-task",
2858 });
2859 const isRetryOfAcceptedDelegation = yield* threadManagement.hasReceipt(commandId);
2860 const target = yield* resolveTargetRechecking({
2861 parent,
2862 target: input.target,
2863 providers,
2864 cwd: yield* parentWorkspaceCwd(parent),
2865 skipProjectEnablementFilter: isRetryOfAcceptedDelegation,
2866 });
2867 const runtimeMode = yield* resolveRuntimeMode(
2868 parent.thread.runtimeMode,
2869 input.runtimeMode,
2870 target,
2871 );
2872 const interactionMode = yield* resolveInteractionMode(
2873 parent.thread.interactionMode,
2874 input.interactionMode,
2875 );
2876 let workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined;
2877 if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) {
2878 const project = yield* requireProject(parent.thread.projectId);
2879 const base = yield* gitDriver
2880 .resolveCommit({
2881 cwd: parent.thread.worktreePath ?? project.workspaceRoot,
2882 revision: "HEAD",
2883 })
2884 .pipe(
2885 Effect.mapError(() =>
2886 failure("invalid_request", "Unable to resolve the parent checkout commit."),
2887 ),
2888 );
2889 // Launch preparation creates the worktree from the project root, so a
2890 // parent checkout in another repository (such as a Git folder inside
2891 // Scratch) would hand it a commit it cannot find.
2892 if (parent.thread.worktreePath !== null) {
2893 yield* gitDriver
2894 .resolveCommit({ cwd: project.workspaceRoot, revision: base.commitSha })
2895 .pipe(
2896 Effect.mapError(() =>
2897 failure(
2898 "invalid_request",
2899 `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.`,
2900 ),
2901 ),
2902 );
2903 }
2904 workspaceStrategy = { type: "worktree", baseRef: base.commitSha, startFromOrigin: false };
2905 }
2906 const parentNodeId = parentRun.rootNodeId;
2907 // The command commits the child's preparing run, which only this call
2908 // prepares, so a caller that goes away must not stop it in between.
2909 return yield* Effect.uninterruptibleMask((restore) =>
2910 Effect.gen(function* () {
2911 // ThreadManagementService.dispatch is the chokepoint for this command
2912 // type's own enablement check, using the same command id and its
2913 // receipt-replay exemption, so no separate assert runs here.
2914 const result = yield* threadManagement
2915 .dispatch({
2916 type: "delegated_task.request",
2917 createdBy: "agent",
2918 creationSource: "mcp",
2919 commandId,
2920 parentThreadId: scope.thread.threadId,
2921 parentRunId: parentRun.id,
2922 parentNodeId,
2923 task: taskPrompt(input),
2924 ...(input.title === undefined ? {} : { title: input.title }),
2925 modelSelection: target.modelSelection,
2926 runtimeMode,
2927 interactionMode,
2928 ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
2929 // Async delegations wake the parent on every child terminal; wait
2930 // delegations deliver through the blocking tool call until `awaitTask`
2931 // gives up the wait (timeout, cancelled call) and upgrades the wake.
2932 completionWake: input.mode === "wait" ? "settled_only" : "always",
2933 })
2934 .pipe(
2935 Effect.mapError((error) =>
2936 error._tag === "ThreadManagementProviderInstanceDisabledError"
2937 ? threadManagementFailure(error)
2938 : failure(
2939 "orchestration_error",
2940 `Unable to create delegated task: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,
2941 ),
2942 ),
2943 );
2944 const taskEvent = result.storedEvents.find(
2945 (stored) =>
2946 stored.event.type === "subagent.updated" &&
2947 stored.event.payload.origin === "app_owned",
2948 );
2949 if (taskEvent?.event.type !== "subagent.updated") {
2950 return yield* failure(
2951 "orchestration_error",
2952 "Delegated task command did not produce a task projection.",
2953 );
2954 }
2955 const taskId = taskEvent.event.payload.id;
2956 const childThreadId = taskEvent.event.payload.childThreadId;
2957 const childRunEvent = result.storedEvents.find(
2958 (stored) =>
2959 stored.event.type === "run.created" && stored.event.threadId === childThreadId,
2960 );
2961 if (
2962 childThreadId !== null &&
2963 childRunEvent?.event.type === "run.created" &&
2964 childRunEvent.event.payload.workspacePreparation !== undefined
2965 ) {
2966 yield* threadLaunch.prepareRun({
2967 commandId,
2968 threadId: childThreadId,
2969 runId: childRunEvent.event.payload.id,
2970 });
2971 }
2972 return yield* input.mode === "wait"
2973 ? awaitTask(scope, taskId, key, input.timeoutMs, restore)
2974 : restore(readTask(scope, taskId, false, true));
2975 }),
2976 );
2977 }),
2978 taskStatus: Effect.fn("OrchestratorMcpService.taskStatus")(function* (callerScope, taskId) {
2979 const scope = yield* requireThreadScope(callerScope, "task_status");
2980 return yield* readTask(scope, taskId, false, true);
2981 }),
2982 cancelTask: Effect.fn("OrchestratorMcpService.cancelTask")(function* (callerScope, input) {
2983 const scope = yield* requireThreadScope(callerScope, "task_cancel");
2984 const current = yield* readTask(scope, input.taskId);
2985 const childThreadId = current.childThreadId;
2986 if (childThreadId === null) {
2987 // The task runs in a linked environment: its thread there is stopped through the link.
2988 const subagents = yield* loadTasks(scope.thread.threadId, [input.taskId]);
2989 const remoteTask = subagents.find(
2990 (task) =>
2991 task.id === input.taskId &&
2992 task.origin === "app_owned" &&
2993 task.remoteChild !== undefined,
2994 );
2995 if (remoteTask === undefined) {
2996 return yield* failure(
2997 "task_not_found",
2998 `Delegated task ${input.taskId} does not belong to thread ${scope.thread.threadId}.`,
2999 );
3000 }
3001 return yield* remoteDelegation.cancel(scope, remoteTask, input);
3002 }
3003 const key = yield* requestKey(input.clientRequestId);
3004 const parentProjection = yield* loadThreadRecords(scope.thread.threadId, []);
3005 // Cancelling stops the child and every task under it, each a write to a
3006 // thread its user may have raised above the parent's modes since it was
3007 // delegated. All of them are checked before anything is stopped.
3008 const assertStoppable = Effect.fn("OrchestratorMcpService.assertStoppable")(function* (
3009 threadId: ThreadId,
3010 ): Effect.fn.Return<void, OrchestratorMcpFailure> {
3011 const shell = yield* threadManagement
3012 .getThreadShell(threadId)
3013 .pipe(Effect.mapError(threadManagementFailure));
3014 if (shell !== null && shell.deletedAt === null) {
3015 yield* resolveRuntimeMode(parentProjection.thread.runtimeMode, shell.runtimeMode);
3016 yield* resolveInteractionMode(
3017 parentProjection.thread.interactionMode,
3018 shell.interactionMode,
3019 );
3020 }
3021 const childThreadIds = yield* threadManagement
3022 .listAppOwnedChildThreadIds(threadId)
3023 .pipe(Effect.mapError(threadManagementFailure));
3024 for (const childThreadId of childThreadIds) {
3025 yield* assertStoppable(childThreadId);
3026 }
3027 });
3028 yield* assertStoppable(childThreadId);
3029 const parentTask = (yield* loadTasks(scope.thread.threadId, [input.taskId])).find(
3030 (task) => task.id === input.taskId && task.origin === "app_owned",
3031 );
3032 const disposeCompletionDelivery =
3033 parentTask?.completionDelivery?.state === "disposed"
3034 ? Effect.void
3035 : threadManagement
3036 .dispatch({
3037 type: "delegated_task.completion-delivery.dispose",
3038 commandId: stableCommandId({
3039 scope,
3040 requestKey: key,
3041 operation: "cancel-task-completion-delivery",
3042 }),
3043 parentThreadId: scope.thread.threadId,
3044 taskId: input.taskId,
3045 })
3046 .pipe(
3047 Effect.asVoid,
3048 Effect.mapError((error) =>
3049 failure(
3050 "orchestration_error",
3051 `Unable to dispose delegated task ${input.taskId} completion delivery: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,
3052 ),
3053 ),
3054 );
3055 const stopChild = Effect.gen(function* () {
3056 const commandId = stableCommandId({ scope, requestKey: key, operation: "cancel-task" });
3057 const reason = agentStopReason(input.reason);
3058 const command = {
3059 type: "thread.stop" as const,
3060 commandId,
3061 threadId: childThreadId,
3062 stopDelegatedTasks: false,
3063 reason,
3064 };
3065 yield* threadManagement
3066 .cancelDelegatedTask({
3067 parentThreadId: scope.thread.threadId,
3068 taskId: input.taskId,
3069 command,
3070 stopDescendants: (remoteDispatch) =>
3071 threadManagement.stopDelegatedTasks({
3072 threadId: childThreadId,
3073 commandId,
3074 reason,
3075 remoteDispatch,
3076 }),
3077 })
3078 .pipe(
3079 Effect.mapError((error) =>
3080 failure(
3081 "task_not_cancellable",
3082 `Unable to stop delegated task ${input.taskId}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,
3083 ),
3084 ),
3085 );
3086 const stopped = yield* threadManagement
3087 .getThreadRecords(childThreadId, ["runs"])
3088 .pipe(Effect.mapError(threadManagementFailure));
3089 for (const run of stopped.runs) {
3090 if (
3091 run.status !== "queued" ||
3092 (run.delegatedTaskId !== input.taskId && run.id !== current.childRunId)
3093 )
3094 continue;
3095 // Stop preserves the queue for Resume. Cancelling a task must also
3096 // remove that task's queued turn, including a previously held one.
3097 yield* threadManagement
3098 .dispatch({
3099 type: "queued-run.cancel",
3100 commandId: stableCommandId({
3101 scope,
3102 requestKey: key,
3103 operation: `cancel-task-queued-run:${run.id}`,
3104 }),
3105 threadId: childThreadId,
3106 runId: run.id,
3107 })
3108 .pipe(Effect.mapError(threadManagementFailure));
3109 }
3110 });
3111 // Checked above; a user raising one of these threads meanwhile is
3112 // caught again under that thread's lock, which leaves it running.
3113 const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);
3114 const stopWithinLimit = stopChild.pipe(
3115 Effect.provideService(DispatchModeLimit, {
3116 runtimeMode: parentProjection.thread.runtimeMode,
3117 interactionMode: parentProjection.thread.interactionMode,
3118 refused,
3119 }),
3120 Effect.catch((error) =>
3121 Effect.flatMap(Ref.get(refused), (refusal) =>
3122 Effect.fail(
3123 refusal === undefined
3124 ? error
3125 : failure(
3126 refusal.mode === "runtime"
3127 ? "runtime_mode_escalation_denied"
3128 : "interaction_mode_escalation_denied",
3129 `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.`,
3130 ),
3131 ),
3132 ),
3133 ),
3134 );
3135 // A follow-up that lost its child run stays running on the parent, while its
3136 // status here comes from the child's last run. Stop on the parent cancels that task.
3137 const cancelOrphan = Effect.gen(function* () {
3138 if (parentTask?.runId == null || !isOrchestrationV2WorkActive(parentTask.status))
3139 return false;
3140 yield* threadManagement.dispatch({
3141 type: "subagent.stop",
3142 commandId: stableCommandId({
3143 scope,
3144 requestKey: key,
3145 operation: "cancel-task-orphan",
3146 }),
3147 threadId: scope.thread.threadId,
3148 runId: parentTask.runId,
3149 subagentId: parentTask.id,
3150 });
3151 const { subagents } = yield* threadManagement.getThreadRecords(
3152 scope.thread.threadId,
3153 ["subagents"],
3154 { subagentIds: [input.taskId] },
3155 );
3156 return subagents.some((task) => task.id === input.taskId && task.status === "cancelled");
3157 }).pipe(Effect.mapError(threadManagementFailure));
3158 if (isTerminalTaskStatus(current.status)) {
3159 // The child can still run work for another turn, so it is stopped either way.
3160 yield* stopWithinLimit;
3161 const cancelled = yield* cancelOrphan;
3162 yield* disposeCompletionDelivery;
3163 return {
3164 taskId: input.taskId,
3165 status: cancelled ? "cancelled" : current.status,
3166 } satisfies OrchestratorMcpTaskCancelResult;
3167 }
3168 const child = yield* loadThreadRecords(childThreadId, ["runs"]);
3169 if (
3170 current.workState !== "waiting_for_children" &&
3171 ThreadManagementService.latestActiveRun(child) === undefined &&
3172 !child.runs.some(
3173 (run) =>
3174 run.status === "queued" &&
3175 (run.delegatedTaskId === input.taskId || run.id === current.childRunId),
3176 )
3177 ) {
3178 if (yield* cancelOrphan) return { taskId: input.taskId, status: "cancelled" };
3179 return yield* failure(
3180 "task_not_cancellable",
3181 `Delegated task ${input.taskId} has no interruptible child run.`,
3182 );
3183 }
3184 yield* stopWithinLimit;
3185 yield* disposeCompletionDelivery.pipe(
3186 Effect.catchCause((cause) =>
3187 Effect.logWarning("orchestrator-mcp.cancel-task.delivery-dispose-failed", {
3188 taskId: input.taskId,
3189 cause,
3190 }),
3191 ),
3192 );
3193 return {
3194 taskId: input.taskId,
3195 status: "cancel_requested",
3196 };
3197 }),
3198 createThreads: Effect.fn("OrchestratorMcpService.createThreads")(
3199 function* (callerScope, input) {
3200 const { scope, parent } = yield* loadThreadCaller(callerScope, "create_threads");
3201 const parentRun = ThreadManagementService.latestActiveRun(parent);
3202 if (
3203 parentRun === undefined ||
3204 parentRun.rootNodeId === null ||
3205 parentRun.providerInstanceId !== scope.thread.providerInstanceId
3206 ) {
3207 return yield* failure(
3208 "parent_not_active",
3209 "Thread creation requires an active run owned by this MCP provider session.",
3210 );
3211 }
3212 const parentNodeId = parentRun.rootNodeId;
3213 const providers = yield* loadProviders;
3214 const cwd = yield* parentWorkspaceCwd(parent);
3215 const key = yield* requestKey(input.clientRequestId);
3216 const created = yield* Effect.forEach(
3217 input.threads,
3218 (request, index) =>
3219 Effect.gen(function* () {
3220 const commandId = stableCommandId({
3221 scope,
3222 requestKey: key,
3223 operation: "create-thread",
3224 index,
3225 });
3226 const threadId = stableThreadId({
3227 scope,
3228 requestKey: key,
3229 index,
3230 });
3231 const isRetryOfAcceptedCreation = yield* threadManagement.hasReceipt(commandId);
3232 const committedThread = isRetryOfAcceptedCreation
3233 ? yield* threadManagement
3234 .getThreadShell(threadId)
3235 .pipe(Effect.mapError(threadManagementFailure))
3236 : null;
3237 const target = yield* resolveTargetRechecking({
3238 parent,
3239 target:
3240 committedThread === null
3241 ? request.target
3242 : {
3243 ...request.target,
3244 providerInstanceId: committedThread.modelSelection.instanceId,
3245 },
3246 providers,
3247 cwd,
3248 skipProjectEnablementFilter: isRetryOfAcceptedCreation,
3249 });
3250 const runtimeMode = yield* resolveRuntimeMode(
3251 parent.thread.runtimeMode,
3252 request.runtimeMode,
3253 target,
3254 );
3255 const interactionMode = yield* resolveInteractionMode(
3256 parent.thread.interactionMode,
3257 request.interactionMode,
3258 );
3259 yield* assertTargetEnabledForProject(parent, commandId, target);
3260 const title = threadTitle({
3261 parentTitle: parent.thread.title,
3262 prompt: request.prompt,
3263 title: request.title,
3264 index,
3265 });
3266 const initialMessage =
3267 request.prompt === undefined
3268 ? undefined
3269 : {
3270 senderThreadId: scope.thread.threadId,
3271 messageId: stableMessageId({
3272 scope,
3273 requestKey: key,
3274 index,
3275 }),
3276 text: request.prompt,
3277 attachments: [],
3278 };
3279 const created = yield* threadManagement
3280 .dispatch({
3281 type: "thread.create",
3282 createdBy: "agent",
3283 creationSource: "mcp",
3284 commandId,
3285 threadId,
3286 projectId: parent.thread.projectId,
3287 title,
3288 modelSelection: target.modelSelection,
3289 runtimeMode,
3290 interactionMode,
3291 branch: parent.thread.branch,
3292 worktreePath: parent.thread.worktreePath,
3293 ...(parent.thread.linkOrigin === undefined
3294 ? {}
3295 : { linkOrigin: parent.thread.linkOrigin }),
3296 ...(initialMessage === undefined ? {} : { initialMessage }),
3297 })
3298 .pipe(
3299 Effect.mapError((error) =>
3300 failure(
3301 "orchestration_error",
3302 `Unable to create thread ${index + 1}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,
3303 ),
3304 ),
3305 );
3306 // A receipt can appear after target resolution; use the committed thread's selection.
3307 const resolvedModelSelection = (yield* threadManagement
3308 .getThreadRecords(threadId, [])
3309 .pipe(Effect.mapError(threadManagementFailure))).thread.modelSelection;
3310 // A replayed creation that carried no prompt has no run yet.
3311 if (
3312 initialMessage !== undefined &&
3313 !created.storedEvents.some(({ event }) => event.type === "run.created")
3314 ) {
3315 const currentParent = (yield* loadThreadRecords(scope.thread.threadId, [])).thread;
3316 const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);
3317 yield* threadManagement
3318 .dispatch({
3319 ...initialMessage,
3320 type: "message.dispatch",
3321 createdBy: "agent",
3322 creationSource: "mcp",
3323 commandId: stableCommandId({
3324 scope,
3325 requestKey: key,
3326 operation: "dispatch-thread",
3327 index,
3328 }),
3329 threadId,
3330 modelSelection: resolvedModelSelection,
3331 dispatchMode: { type: "start_immediately" },
3332 })
3333 .pipe(
3334 Effect.provideService(DispatchModeLimit, {
3335 runtimeMode: currentParent.runtimeMode,
3336 interactionMode: currentParent.interactionMode,
3337 refused,
3338 }),
3339 Effect.mapError((error) =>
3340 error._tag === "ThreadManagementProviderInstanceDisabledError"
3341 ? threadManagementFailure(error)
3342 : failure(
3343 "orchestration_error",
3344 `Unable to start thread ${index + 1}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,
3345 ),
3346 ),
3347 Effect.catch((error) =>
3348 Effect.flatMap(Ref.get(refused), (refusal) =>
3349 Effect.fail(
3350 refusal === undefined
3351 ? error
3352 : failure(
3353 refusal.mode === "runtime"
3354 ? "runtime_mode_escalation_denied"
3355 : "interaction_mode_escalation_denied",
3356 `Thread ${refusal.threadId} now runs in ${refusal.runtimeMode}/${refusal.interactionMode} mode, above this thread's.`,
3357 ),
3358 ),
3359 ),
3360 ),
3361 );
3362 }
3363 const projection = yield* loadThreadRecords(threadId, ["runs"]);
3364 const run = projection.runs.at(-1);
3365 yield* threadManagement
3366 .dispatch({
3367 type: "thread.created.record",
3368 commandId: stableCommandId({
3369 scope,
3370 requestKey: key,
3371 operation: "record-created-thread",
3372 index,
3373 }),
3374 parentThreadId: scope.thread.threadId,
3375 parentRunId: parentRun.id,
3376 parentNodeId,
3377 targetThreadId: threadId,
3378 targetRunId: run?.id ?? null,
3379 })
3380 .pipe(
3381 Effect.mapError((error) =>
3382 failure(
3383 "orchestration_error",
3384 `Unable to record thread ${index + 1} in the parent timeline: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,
3385 ),
3386 ),
3387 );
3388 return {
3389 threadId,
3390 link: formatThreadLink(
3391 { environmentId: scope.environmentId, threadId },
3392 projection.thread.title,
3393 ),
3394 runId: run?.id ?? null,
3395 status: run?.status ?? "idle",
3396 title: projection.thread.title,
3397 createdBy: projection.thread.createdBy,
3398 creationSource: projection.thread.creationSource,
3399 providerInstanceId: resolvedModelSelection.instanceId,
3400 model: resolvedModelSelection.model,
3401 } satisfies OrchestratorMcpCreatedThread;
3402 }),
3403 { concurrency: 1 },
3404 );
3405 return { threads: created };
3406 },
3407 ),
3408 listThreads: Effect.fn("OrchestratorMcpService.listThreads")(function* (scope, input) {
3409 const { parent } = yield* loadCaller(scope, []);
3410 const projectId = input.allProjects
3411 ? null
3412 : yield* resolveProjectTarget(
3413 parent,
3414 input.projectId,
3415 "Pass projectId, or allProjects: true for every project. This MCP client is not running inside a T3 thread.",
3416 );
3417 if (!input.allProjects && input.projectId !== undefined) {
3418 yield* requireProject(input.projectId);
3419 }
3420 const listFailure = (error: unknown) =>
3421 failure("orchestration_error", `Unable to list threads: ${errorMessage(error)}`);
3422 const projectThreads = yield* threadManagement
3423 .listProjectThreads({
3424 projectId: projectId ?? undefined,
3425 includeSubagents: input.includeSubagents !== false,
3426 })
3427 .pipe(Effect.mapError(listFailure));
3428 const nowMs = yield* Clock.currentTimeMillis;
3429 // An empty list is no filter: clients that fill every optional field send `[]`.
3430 const statuses =
3431 input.statuses === undefined || input.statuses.length === 0
3432 ? null
3433 : new Set(input.statuses);
3434 const titleContains = input.titleContains?.toLocaleLowerCase();
3435 // A live status needs a source the index's mayBeLive covers, so a live-only filter
3436 // skips building shells for every thread that cannot match.
3437 const mayBeLiveIds =
3438 statuses !== null &&
3439 [...statuses].every((status) => LIVE_LISTED_THREAD_STATUSES.has(status))
3440 ? new Set(
3441 (yield* threadManagement
3442 .listActiveShellIndex()
3443 .pipe(Effect.mapError(listFailure))).flatMap((entry) =>
3444 entry.mayBeLive ? [entry.id] : [],
3445 ),
3446 )
3447 : null;
3448 const candidates = projectThreads
3449 .filter((thread) => mayBeLiveIds === null || mayBeLiveIds.has(thread.id))
3450 .filter(
3451 (thread) =>
3452 input.settled === undefined || threadSettlement(thread).settled === input.settled,
3453 )
3454 .filter(
3455 (thread) =>
3456 titleContains === undefined || thread.title.toLocaleLowerCase().includes(titleContains),
3457 )
3458 // Only a snooze that ends later can hold, so the rest skip building a shell.
3459 .filter(
3460 (thread) =>
3461 input.snoozed !== true ||
3462 (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs),
3463 );
3464 // Shells are the costly part, so build them only for the threads the page needs.
3465 const shellsOf = (threads: ReadonlyArray<{ readonly id: ThreadId }>) =>
3466 threads.length === 0
3467 ? Effect.succeed([])
3468 : threadManagement
3469 .getShellSnapshot({ location: "active", threadIds: threads.map(({ id }) => id) })
3470 .pipe(
3471 Effect.map((snapshot) => {
3472 const shellsById = new Map(snapshot.threads.map((shell) => [shell.id, shell]));
3473 return threads.flatMap(({ id }) => shellsById.get(id) ?? []);
3474 }),
3475 Effect.mapError(listFailure),
3476 );
3477 const cursor = input.cursor ?? 0;
3478 const limit = input.limit ?? DEFAULT_THREAD_LIST_LIMIT;
3479 let page: ReadonlyArray<OrchestrationV2ThreadShell>;
3480 let total: number;
3481 if (statuses === null && input.snoozed === undefined) {
3482 total = candidates.length;
3483 page = yield* shellsOf(candidates.slice(cursor, cursor + limit));
3484 } else {
3485 // Status and snooze state are derived from the shell.
3486 const filtered = (yield* shellsOf(candidates))
3487 .filter((thread) => statuses === null || statuses.has(listedThreadStatus(thread)))
3488 .filter(
3489 (thread) => input.snoozed === undefined || isSnoozed(thread, nowMs) === input.snoozed,
3490 );
3491 total = filtered.length;
3492 page = filtered.slice(cursor, cursor + limit);
3493 }
3494 const nextCursor = cursor + limit < total ? cursor + limit : null;
3495 return {
3496 projectId,
3497 currentThreadId: parent?.thread.id ?? null,
3498 threads: page.map((shell) => listItemFromShell(scope, shell, nowMs)),
3499 nextCursor,
3500 total,
3501 } satisfies OrchestratorMcpThreadListResult;
3502 }),
3503 readThread: Effect.fn("OrchestratorMcpService.readThread")(function* (scope, input) {
3504 const runLimit = input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT;
3505 const { parent, target, shell, runCount } = yield* loadReadableThread(
3506 scope,
3507 input.threadId,
3508 runLimit,
3509 );
3510 const view = input.view ?? "messages";
3511 const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT;
3512 const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS;
3513 // Client callers (the CLI, older linked environments) page forward from a cursorless read.
3514 const newestFirst =
3515 input.beforePosition !== undefined ||
3516 (input.afterPosition === undefined && scope.thread !== undefined);
3517 const timeline = yield* threadManagement
3518 .getTimelinePage(input.threadId, {
3519 ...(input.afterPosition === undefined ? {} : { afterPosition: input.afterPosition }),
3520 ...(newestFirst
3521 ? { beforePosition: input.beforePosition ?? Number.POSITIVE_INFINITY }
3522 : {}),
3523 limit,
3524 view,
3525 ...(input.itemId === undefined ? {} : { itemId: input.itemId }),
3526 })
3527 .pipe(Effect.mapError(threadManagementFailure));
3528 const messageIdsByThread = new Map<ThreadId, Array<MessageId>>();
3529 for (const row of timeline.items) {
3530 if (row.item.type !== "user_message" && row.item.type !== "assistant_message") continue;
3531 const ids = messageIdsByThread.get(row.sourceThreadId) ?? [];
3532 ids.push(row.item.messageId);
3533 messageIdsByThread.set(row.sourceThreadId, ids);
3534 }
3535 const sourceMessages = yield* Effect.forEach(
3536 [...messageIdsByThread],
3537 ([threadId, messageIds]) =>
3538 threadManagement.getThreadRecords(threadId, ["messages"], { messageIds }).pipe(
3539 Effect.map((records) => [threadId, records.messages] as const),
3540 Effect.mapError(threadManagementFailure),
3541 ),
3542 { concurrency: 1 },
3543 );
3544 const messagesByThreadId = new Map(sourceMessages);
3545 const thread = threadDetail(
3546 scope,
3547 target,
3548 runCount,
3549 timeline.totalItems,
3550 shell,
3551 yield* Clock.currentTimeMillis,
3552 input.afterPosition === undefined &&
3553 input.beforePosition === undefined &&
3554 input.itemId === undefined,
3555 );
3556 const recentRuns = target.runs
3557 .toSorted((left, right) => right.ordinal - left.ordinal)
3558 .slice(0, runLimit)
3559 .map((run) => threadRun(target, run));
3560 const { items, start } = timelineItemsWithinBudget(
3561 { thread, recentRuns, nextPosition: null, hasMore: false, earlierPosition: null },
3562 timeline.items.map((row) => ({
3563 row,
3564 maxChars,
3565 messagesByThreadId,
3566 ...(input.itemId === undefined ? {} : { textOffset: input.textOffset ?? 0 }),
3567 })),
3568 newestFirst,
3569 );
3570 const page = timeline.items.slice(start, start + items.length);
3571 const returnedRunIds = new Set(
3572 page.filter((row) => row.sourceThreadId === target.thread.id).map((row) => row.item.runId),
3573 );
3574 const tasks =
3575 parent === undefined
3576 ? []
3577 : directAppOwnedChildTasks(
3578 {
3579 thread: parent.thread,
3580 subagents: yield* loadTasks(
3581 parent.thread.id,
3582 directChildTaskIds(target, returnedRunIds),
3583 ),
3584 },
3585 target,
3586 returnedRunIds,
3587 );
3588 // A read past the end of an item's text shows the agent nothing to acknowledge.
3589 const readPastEnd = (input.textOffset ?? 0) > 0 && items.every((item) => !item.text);
3590 if (parent !== undefined && scope.thread !== undefined && tasks.length > 0 && !readPastEnd) {
3591 for (const task of tasks) {
3592 const transfer = taskResultTransfer(parent.thread.id, target, task);
3593 const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id;
3594 const resultRunIds = resultRunId === undefined ? [] : [resultRunId];
3595 const resultRecords = yield* threadManagement
3596 .getThreadRecords(target.thread.id, ["messages", "turnItems"], {
3597 messageRoles: ["assistant"],
3598 messageRunIds: resultRunIds,
3599 turnItemRunIds: resultRunIds,
3600 turnItemTypes: ["assistant_message", "error"],
3601 })
3602 .pipe(Effect.mapError(threadManagementFailure));
3603 if (
3604 pageIncludesTerminalTaskResult({
3605 parentThreadId: parent.thread.id,
3606 items,
3607 task,
3608 target: { ...target, ...resultRecords },
3609 })
3610 ) {
3611 yield* readTask(
3612 scope as McpThreadInvocationScope,
3613 task.id,
3614 false,
3615 true,
3616 "thread-read-acknowledge",
3617 );
3618 }
3619 }
3620 }
3621 return {
3622 thread,
3623 recentRuns,
3624 items,
3625 nextPosition: items.at(-1)?.position ?? null,
3626 hasMore: timeline.hasMore || (!newestFirst && items.length < timeline.items.length),
3627 earlierPosition: timeline.hasEarlier || start > 0 ? (items[0]?.position ?? null) : null,
3628 } satisfies OrchestratorMcpThreadReadResult;
3629 }),
3630 sendToThread: Effect.fn("OrchestratorMcpService.sendToThread")(function* (scope, input) {
3631 const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId, ["runs"]);
3632 yield* assertLiveCallerForOtherThread(scope, parent, target);
3633 yield* assertTargetWithinLimits(limits, target.thread);
3634
3635 const mode = input.mode ?? "auto";
3636 const key = yield* requestKey(input.clientRequestId);
3637 const messageId = stableOperationMessageId({
3638 scope,
3639 requestKey: key,
3640 operation: "thread-send",
3641 });
3642 const result = yield* threadManagement
3643 .sendToThread({
3644 projectId: target.thread.projectId,
3645 commandId: stableCommandId({
3646 scope,
3647 requestKey: key,
3648 operation: "thread-send",
3649 }),
3650 threadId: input.threadId,
3651 ...(parent === undefined ? {} : { senderThreadId: parent.thread.id }),
3652 // A linked environment's agent has no thread here; the link names it.
3653 ...(parent === undefined && scope.client?.senderThread !== undefined
3654 ? { linkedSender: scope.client.senderThread }
3655 : {}),
3656 messageId,
3657 text: input.message,
3658 attachments: [],
3659 mode,
3660 ...(input.freshContext ? { freshContext: true } : {}),
3661 ...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }),
3662 createdBy: "agent",
3663 creationSource: "mcp",
3664 })
3665 .pipe(
3666 Effect.mapError((error) =>
3667 isThreadManagementError(error)
3668 ? threadManagementFailure(error)
3669 : failure(
3670 "orchestration_error",
3671 `Unable to send to thread ${input.threadId}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,
3672 ),
3673 ),
3674 );
3675 return {
3676 threadId: input.threadId,
3677 link: threadLinkFor(scope, input.threadId, target.thread.title),
3678 messageId,
3679 runId: result.run.id,
3680 ...(result.run.delegatedTaskId === undefined ? {} : { taskId: result.run.delegatedTaskId }),
3681 status: result.run.status,
3682 delivery: result.delivery,
3683 } satisfies OrchestratorMcpThreadSendResult;
3684 }),
3685 waitForThread: Effect.fn("OrchestratorMcpService.waitForThread")(function* (scope, input) {
3686 const { parent, target } = yield* loadScopedThread(scope, input.threadId, []);
3687 const result = yield* threadManagement
3688 .waitForThread({
3689 projectId: target.thread.projectId,
3690 threadId: input.threadId,
3691 ...(input.runId === undefined ? {} : { runId: input.runId }),
3692 timeoutMs: Math.min(
3693 MAX_WAIT_TIMEOUT_MS,
3694 Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
3695 ),
3696 ...(input.untilDelegatedWorkSettled === true ? { untilDelegatedWorkSettled: true } : {}),
3697 ...(input.untilOutput === true ? { untilOutput: true } : {}),
3698 })
3699 .pipe(Effect.mapError(threadManagementFailure));
3700 const status = result.run === null ? "idle" : runOutcome(result.run);
3701 const taskId = result.run?.delegatedTaskId;
3702 const ownedTask =
3703 result.timedOut &&
3704 status !== "waiting" &&
3705 parent !== undefined &&
3706 taskId !== undefined &&
3707 (yield* loadTasks(parent.thread.id, [taskId])).some(
3708 (task) =>
3709 task.id === taskId &&
3710 task.origin === "app_owned" &&
3711 task.threadId === parent.thread.id &&
3712 task.childThreadId === input.threadId &&
3713 task.completionDelivery?.state !== "disposed",
3714 );
3715 // A child waiting on a question or approval needs an answer, not a wake.
3716 const childRequests = ownedTask
3717 ? (yield* threadManagement
3718 .getThreadRecords(input.threadId, ["runtimeRequests"])
3719 .pipe(Effect.mapError(threadManagementFailure))).runtimeRequests
3720 : [];
3721 const wakesCaller =
3722 ownedTask && !childRequests.some((request) => request.status === "pending");
3723 return {
3724 threadId: input.threadId,
3725 runId: result.run?.id ?? null,
3726 status,
3727 timedOut: result.timedOut,
3728 ...(wakesCaller ? { next: ORCHESTRATOR_MCP_RUNNING_TASK_NEXT } : {}),
3729 ...(result.resultRun === undefined
3730 ? {}
3731 : {
3732 resultRun: { runId: result.resultRun.id, status: runOutcome(result.resultRun) },
3733 }),
3734 ...(result.run?.output === undefined ? {} : { output: result.run.output.value }),
3735 } satisfies OrchestratorMcpThreadWaitResult;
3736 }),
3737 interruptThread: Effect.fn("OrchestratorMcpService.interruptThread")(function* (scope, input) {
3738 const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId, ["runs"]);
3739 yield* assertLiveCallerForOtherThread(scope, parent, target);
3740 yield* assertTargetWithinLimits(limits, target.thread);
3741 const key = yield* requestKey(input.clientRequestId);
3742 // A peer from before `stop` drops it when decoding, so it interrupts
3743 // the run instead, as this call did then.
3744 if (input.stop === true) {
3745 const commandId = stableCommandId({ scope, requestKey: key, operation: "thread-stop" });
3746 const reason = agentStopReason(input.reason);
3747 // The cause goes to the log; the caller learns only that the stop failed.
3748 const stopFailed = (error: unknown) =>
3749 Effect.logWarning("orchestrator-mcp.thread-stop-failed", {
3750 threadId: input.threadId,
3751 error,
3752 }).pipe(
3753 Effect.andThen(
3754 Effect.fail(
3755 failure("orchestration_error", `Unable to stop thread ${input.threadId}.`),
3756 ),
3757 ),
3758 );
3759 const stopped = yield* threadManagement
3760 .dispatch({
3761 type: "thread.stop",
3762 commandId,
3763 threadId: input.threadId,
3764 reason,
3765 })
3766 .pipe(Effect.catch(stopFailed));
3767 // A retry with the same clientRequestId repeats only the stops that failed.
3768 yield* threadManagement
3769 .stopDelegatedTasks({ threadId: input.threadId, commandId, reason })
3770 .pipe(Effect.catch(stopFailed));
3771 // The run this stop interrupted, from its own events, so a retry
3772 // reports the same run even if another has started since. Stop also
3773 // holds queued runs and marks runs it could not interrupt, with no
3774 // provider turn; neither is the run it interrupted.
3775 const interrupted = stopped.storedEvents.find(
3776 ({ event }) =>
3777 (event.type === "run.updated" && event.payload.status === "interrupted") ||
3778 (event.type === "turn-item.updated" &&
3779 event.payload.type === "run_interrupt_request" &&
3780 event.payload.providerTurnId !== null),
3781 )?.event.runId;
3782 return {
3783 threadId: input.threadId,
3784 runId: interrupted ?? null,
3785 status: interrupted === undefined ? "no_active_run" : "interrupt_requested",
3786 } satisfies OrchestratorMcpThreadInterruptResult;
3787 }
3788 const result = yield* threadManagement
3789 .interruptThread({
3790 projectId: target.thread.projectId,
3791 commandId: stableCommandId({
3792 scope,
3793 requestKey: key,
3794 operation: "thread-interrupt",
3795 }),
3796 threadId: input.threadId,
3797 ...(input.runId === undefined ? {} : { runId: input.runId }),
3798 reason: agentStopReason(input.reason),
3799 })
3800 .pipe(
3801 Effect.mapError((error) =>
3802 isThreadManagementError(error)
3803 ? threadManagementFailure(error)
3804 : failure(
3805 "orchestration_error",
3806 `Unable to interrupt thread ${input.threadId}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`,
3807 ),
3808 ),
3809 );
3810 if (result.type === "no_active_run") {
3811 return {
3812 threadId: input.threadId,
3813 runId: null,
3814 status: "no_active_run",
3815 } satisfies OrchestratorMcpThreadInterruptResult;
3816 }
3817 return {
3818 threadId: input.threadId,
3819 runId: result.run.id,
3820 status: result.type === "already_terminal" ? result.run.status : "interrupt_requested",
3821 } satisfies OrchestratorMcpThreadInterruptResult;
3822 }),
3823 });
3824 });
3825
3826 export const layer: Layer.Layer<
3827 OrchestratorMcpService,
3828 never,
3829 | SecureRandom.SecureRandom
3830 | ThreadManagementService.ThreadManagementService
3831 | ThreadLaunchService.ThreadLaunchService
3832 | GitVcsDriver.GitVcsDriver
3833 | ProviderRegistry.ProviderRegistry
3834 | ProviderAdapterRegistry.ProviderAdapterRegistryV2
3835 | ScheduledTaskService.ScheduledTaskService
3836 | ProjectService.ProjectService
3837 | SecretRequests.SecretRequests
3838 | ServerSettings.ServerSettingsService
3839 | RemoteDelegation.RemoteDelegation
3840 > = Layer.effect(OrchestratorMcpService, make);