@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, 04:45 UTC

main
ts 2,511 lines 101 KB
Raw
1 import { MspError, type ProcessExit, type SendUserTurnOptions } from "@muse-code/sdk";
2 import {
3 MUSE_DEFAULT_MODEL,
4 ProviderDriverKind,
5 type ModelSelection,
6 type OrchestrationV2AppThread,
7 type OrchestrationV2ConversationMessage,
8 type OrchestrationV2ExecutionNode,
9 type OrchestrationV2ProviderCapabilities,
10 type OrchestrationV2ProviderRetry,
11 type OrchestrationV2ProviderSession,
12 type OrchestrationV2ProviderThread,
13 type OrchestrationV2ProviderTurn,
14 type OrchestrationV2RuntimeRequest,
15 type OrchestrationV2Subagent,
16 type OrchestrationV2TurnItemStatus,
17 type NodeId,
18 type OrchestrationV2TurnItem,
19 type ProviderInstanceId,
20 type PlanId,
21 type OrchestrationV2PlanStep,
22 type ProviderApprovalDecision,
23 type RuntimeRequestId,
24 type ServerProviderModel,
25 type ThreadId,
26 } from "@t3tools/contracts";
27 import type { MuseSettings } from "../settings.ts";
28 import { AgentScope } from "@t3tools/shared/AgentScope";
29 import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
30 import { formatDuration } from "@t3tools/shared/orchestrationTiming";
31 import * as Cause from "effect/Cause";
32 import * as DateTime from "effect/DateTime";
33 import * as Deferred from "effect/Deferred";
34 import * as Effect from "effect/Effect";
35 import * as FileSystem from "effect/FileSystem";
36 import * as Queue from "effect/Queue";
37 import * as Schema from "effect/Schema";
38 import * as Semaphore from "effect/Semaphore";
39 import * as Scope from "effect/Scope";
40 import * as Stream from "effect/Stream";
41
42 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
43 import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
44 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
45 import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
46 import { museModelCapabilities, resolveMuseReasoningEffort } from "./modelCatalog.ts";
47 import {
48 MuseApproval,
49 MuseCompactResult,
50 MuseContextUsage,
51 MuseDelta,
52 MuseItemEvent,
53 MuseSessionResult,
54 MuseSubscriptionUsage,
55 MuseTokenUsageEvent,
56 MuseTodoList,
57 MuseRetryScheduled,
58 MuseTurnCompleted,
59 MuseTurnStartResult,
60 MuseUserInput,
61 museApprovalChoices,
62 museApprovalDecision,
63 museApprovalOptions,
64 type MuseItem,
65 } from "./protocol.ts";
66 import {
67 isMuseUsageLimitFailure,
68 museUsageLimitResetAt,
69 museUsageToLimits,
70 } from "./usageLimits.ts";
71 import {
72 createMuseSdkHostEffect,
73 MuseSdkError,
74 museApprovalMode,
75 museCanonicalPath,
76 musePermissionProfile,
77 museWorkspaceRoot,
78 type createMuseSdkHost,
79 type MuseSdkHost,
80 } from "./sdk.ts";
81 import type * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
82 import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot";
83 import {
84 providerMessageTextWithAttachmentPaths,
85 isProviderNativeImageAttachment,
86 } from "@t3tools/provider-core/server/attachmentPrompt";
87 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
88 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
89 import {
90 backgroundWorkNotification,
91 type BackgroundWorkReport,
92 } from "@t3tools/provider-core/server/notification";
93 import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
94 import {
95 makeProviderFailure,
96 makeProviderRetryTurnItem,
97 } from "@t3tools/provider-core/server/failure";
98 import {
99 makeSubagentChildThread,
100 makeSubagentConversationArtifacts,
101 subagentThreadTitle,
102 } from "@t3tools/provider-core/server/subagentProjection";
103 import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
104 import { museItemStatus, museToolPresentation } from "./itemPresentation.ts";
105
106 const MUSE_PROVIDER = ProviderDriverKind.make("muse");
107 const isOpenSessionError = Schema.is(ProviderAdapter.ProviderAdapterOpenSessionError);
108 const isProtocolError = Schema.is(ProviderAdapter.ProviderAdapterProtocolError);
109
110 const MuseProviderCapabilitiesV2 = {
111 runtimePolicy: { enforcement: "native" },
112 sessions: {
113 supportsMultipleProviderThreadsPerSession: false,
114 supportsModelSwitchInSession: true,
115 supportsProviderSwitchingViaHandoff: true,
116 supportsRuntimeModeSwitchInSession: false,
117 pendingRequestsSurviveRestart: false,
118 },
119 threads: {
120 canCreateEmptyThread: true,
121 canReadThreadSnapshot: true,
122 canRollbackThread: false,
123 canForkThread: false,
124 canForkFromTurn: false,
125 canForkFromSubagentThread: false,
126 exposesNativeThreadId: true,
127 },
128 turns: {
129 exposesNativeTurnId: true,
130 emitsTurnStarted: true,
131 emitsTurnCompleted: true,
132 supportsInterrupt: true,
133 supportsNativeResume: false,
134 supportsActiveSteering: true,
135 supportsSteeringByInterruptRestart: false,
136 supportsQueuedMessages: true,
137 terminalStatusQuality: "strong",
138 },
139 streaming: {
140 streamsAssistantText: true,
141 streamsReasoning: true,
142 streamsToolOutput: true,
143 streamsPlanText: false,
144 emitsMessageCompleted: true,
145 },
146 tools: {
147 exposesToolItemIds: true,
148 emitsToolStarted: true,
149 emitsToolCompleted: true,
150 emitsToolOutput: true,
151 supportsMcpTools: true,
152 supportsDynamicToolCallbacks: false,
153 },
154 approvals: {
155 supportsCommandApproval: true,
156 supportsFileReadApproval: true,
157 supportsFileChangeApproval: true,
158 supportsApplyPatchApproval: false,
159 approvalsHaveNativeRequestIds: true,
160 approvalCallbacksAreLiveOnly: true,
161 approvalsCanOriginateFromSubagents: true,
162 },
163 planning: {
164 emitsPlanUpdated: true,
165 emitsTodoList: true,
166 emitsProposedPlan: false,
167 supportsStructuredQuestions: true,
168 planDeltasHaveItemIds: false,
169 },
170 subagents: {
171 supportsSubagents: true,
172 exposesSubagentThreadIds: false,
173 emitsSubagentLifecycle: true,
174 canWaitForSubagents: false,
175 canCloseSubagents: false,
176 canForkSubagentThread: false,
177 },
178 context: {
179 acceptsSystemContext: false,
180 acceptsDeveloperContext: false,
181 acceptsSyntheticUserContext: true,
182 canGenerateSummaries: false,
183 canConsumeHandoffSummaries: true,
184 supportsDeltaHandoff: true,
185 supportsFullThreadHandoff: true,
186 maxRecommendedHandoffChars: null,
187 },
188 checkpointing: {
189 appCanCheckpointFilesystem: true,
190 supportsNestedCheckpointScopes: false,
191 providerCanRollbackConversation: false,
192 providerRollbackReturnsSnapshot: false,
193 providerCanReadConversationSnapshot: true,
194 },
195 identity: {
196 nativeThreadIds: "strong",
197 nativeTurnIds: "strong",
198 nativeItemIds: "strong",
199 nativeRequestIds: "strong",
200 },
201 } satisfies OrchestrationV2ProviderCapabilities;
202
203 export interface MuseAdapterV2Options {
204 readonly instanceId: ProviderInstanceId;
205 readonly settings: MuseSettings;
206 readonly environment: NodeJS.ProcessEnv;
207 readonly modelCatalog?: Effect.Effect<ReadonlyArray<ServerProviderModel>>;
208 readonly createHost?: typeof createMuseSdkHost;
209 readonly requestTimeoutMs?: number;
210 readonly nativeEventLogger?: ProviderEventLoggers.EventNdjsonLogger;
211 /** Receives every account-wide usage report, whichever session's host sent it. */
212 readonly onUsageLimits?: ManagedServerProvider["applyUsageLimits"];
213 readonly continuationRequests?: {
214 readonly offer: (
215 request: ProviderContinuationRequests.ProviderContinuationRequest,
216 ) => Effect.Effect<void>;
217 };
218 }
219
220 interface ActiveTurn {
221 readonly input: ProviderAdapter.ProviderAdapterV2TurnInput;
222 providerTurn: OrchestrationV2ProviderTurn;
223 readonly nativeId: string;
224 readonly joined: Set<string>;
225 readonly items: Map<string, MuseItem>;
226 readonly ordinals: Map<string, number>;
227 readonly started: Map<string, DateTime.Utc>;
228 readonly dirty: Set<string>;
229 readonly settledRequests: Set<string>;
230 readonly retries: Array<MuseRetryRow>;
231 readonly done: Deferred.Deferred<void>;
232 todoPlanId?: PlanId;
233 nextOrdinal: number;
234 flushScheduled: boolean;
235 interruptRequested: boolean;
236 compact: boolean;
237 }
238
239 interface MuseRetryRow {
240 readonly method: string;
241 readonly nativeId: string;
242 readonly retry: OrchestrationV2ProviderRetry;
243 readonly cause: string;
244 readonly code: string | undefined;
245 running: boolean;
246 }
247
248 interface PendingRequest {
249 readonly native:
250 | { type: "approval"; value: MuseApproval }
251 | { type: "question"; value: MuseUserInput };
252 request: OrchestrationV2RuntimeRequest;
253 node: OrchestrationV2ExecutionNode;
254 item: OrchestrationV2TurnItem;
255 response?: Pick<OrchestrationV2RuntimeRequest, "decision" | "answers">;
256 shown: boolean;
257 }
258
259 // Muse 1.4.4 cannot read/subscribe to inline child sessions; retain prompt, root status, and result here.
260 interface ChildContext {
261 readonly childSessionId: string;
262 readonly childThreadId: ThreadId;
263 readonly appThread: OrchestrationV2AppThread;
264 readonly rootNodeId: NodeId;
265 readonly parentThreadId: ThreadId;
266 status: OrchestrationV2TurnItemStatus;
267 result?: string;
268 }
269
270 const nativeRef = (nativeId: string) => ({
271 driver: MUSE_PROVIDER,
272 nativeId,
273 strength: "strong" as const,
274 });
275 /** The roster lists a child under its turn item's native id, so readers can pair the two. */
276 const backgroundTaskId = (item: MuseItem) =>
277 item.kind === "subagent" ? item.childSessionId || item.subagentId || item.itemId : item.itemId;
278 const recordSchema = Schema.Record(Schema.String, Schema.Unknown);
279 const INFORMATIONAL_NOTIFICATIONS = new Set([
280 "session/contextUsage",
281 "session/tokenUsage",
282 "session/todoListChanged",
283 "turn/retryScheduled",
284 "turn/modelRetryScheduled",
285 "usage/changed",
286 ]);
287 const TOOLS_WITH_NATIVE_ROWS = new Set(["write_todos", "request_user_input", "workflow"]);
288 // Reminder children and other runtime items can start while the model is still retrying.
289 const MODEL_OUTPUT_KINDS = new Set(["agentMessage", "reasoning", "toolCall"]);
290 const responseAnswerSchema = Schema.Union([Schema.String, Schema.Array(Schema.String)]);
291
292 export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
293 options: MuseAdapterV2Options,
294 ) {
295 const idAllocator = yield* IdAllocator.IdAllocatorV2;
296 const providerHost = yield* ProviderHost.ProviderHost;
297 const fileSystem = yield* FileSystem.FileSystem;
298 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
299 const agentScope = yield* AgentScope;
300
301 const protocolError = (detail: string, payload?: unknown) =>
302 new ProviderAdapter.ProviderAdapterProtocolError({
303 driver: MUSE_PROVIDER,
304 detail,
305 ...(payload === undefined ? {} : { payload }),
306 });
307 return ProviderAdapter.ProviderAdapterV2.of({
308 instanceId: options.instanceId,
309 driver: MUSE_PROVIDER,
310 getCapabilities: Effect.fn("MuseAdapter.getCapabilities")(function () {
311 return Effect.succeed(MuseProviderCapabilitiesV2);
312 }),
313 planSelectionTransition: Effect.fn("MuseAdapter.planSelectionTransition")(function () {
314 return Effect.succeed(turnScopedSelectionTransition());
315 }),
316 openSession: Effect.fn("MuseAdapterV2.openSession")(function* (
317 input: ProviderAdapter.ProviderAdapterV2OpenSessionInput,
318 ) {
319 if (!options.settings.enabled) return yield* protocolError("Muse Code is disabled");
320 if (input.runtimePolicy.interactionMode === "plan")
321 return yield* protocolError("Muse Code does not support dedicated Plan mode");
322 const scope = yield* Effect.scope;
323 // Native realpath also corrects filesystem case, which Muse validates.
324 const requestedCwd = input.runtimePolicy.cwd ?? providerHost.paths.cwd;
325 const cwd = yield* museCanonicalPath(requestedCwd);
326 const workspaceRoot = yield* museWorkspaceRoot(cwd);
327 const now = yield* DateTime.now;
328 let session: OrchestrationV2ProviderSession = {
329 id: input.providerSessionId,
330 driver: MUSE_PROVIDER,
331 providerInstanceId: options.instanceId,
332 status: "ready",
333 cwd,
334 model: input.modelSelection.model,
335 capabilities: MuseProviderCapabilitiesV2,
336 createdAt: now,
337 updatedAt: now,
338 lastError: null,
339 };
340 const events = yield* Queue.unbounded<
341 ProviderAdapter.ProviderAdapterV2Event,
342 ProviderAdapter.ProviderAdapterV2Error | Cause.Done
343 >();
344 type Inbox =
345 | { type: "notification"; method: string; params: unknown; epoch: number }
346 | { type: "failure"; cause: unknown; epoch: number }
347 | { type: "flush"; turn: ActiveTurn };
348 const inbox = yield* Queue.unbounded<Inbox>();
349 const commands = yield* Semaphore.make(1);
350 const eventPermit = yield* Semaphore.make(1);
351 let host: MuseSdkHost;
352 let hostEpoch = 0;
353 let closed = false;
354 let broken = false;
355 // Only idle host failures can be retried on this runtime.
356 let relaunchable = false;
357 let nativeSessionId: string | undefined;
358 let thread: OrchestrationV2ProviderThread | undefined;
359 let active: ActiveTurn | undefined;
360 let lastProviderTurn: OrchestrationV2ProviderTurn | undefined;
361 let latestSubscriptionUsage: MuseSubscriptionUsage | undefined;
362 const agentEndedAt = new Map<string, DateTime.Utc>();
363 const resolveModel = Effect.fnUntraced(function* (selection: ModelSelection) {
364 if (selection.model !== MUSE_DEFAULT_MODEL) return selection.model;
365 const catalog = options.modelCatalog ? yield* options.modelCatalog : [];
366 return catalog.find((model) => model.isDefault && !model.isCustom)?.slug;
367 });
368 const pending = new Map<RuntimeRequestId, PendingRequest>();
369 const seenTerminals = new Set<string>();
370 const observedChildren = new Map<string, ActiveTurn>();
371 const childrenByItemId = new Map<string, ChildContext>();
372 const agentTitles = new Map<string, string>();
373 const finishedBackground: Array<BackgroundWorkReport> = [];
374 let wake:
375 | { readonly nativeId: string; readonly events: Array<[string, unknown]> }
376 | undefined;
377 const emit = (event: ProviderAdapter.ProviderAdapterV2Event) =>
378 Queue.offer(events, event).pipe(Effect.asVoid);
379 const decode = <A, I>(schema: Schema.Codec<A, I>, data: unknown) =>
380 Schema.decodeUnknownEffect(schema)(data).pipe(
381 Effect.mapError((cause) => protocolError("Invalid Muse protocol response", cause)),
382 );
383 const request = (
384 method: string,
385 params: Record<string, unknown>,
386 command = true,
387 commandId?: string,
388 ) =>
389 Effect.tryPromise({
390 try: () =>
391 command
392 ? host.connection.command(
393 method,
394 { ...(nativeSessionId ? { sessionId: nativeSessionId } : {}), ...params },
395 {
396 ...(method === "turn/start" ? {} : { maxAttempts: 1 }),
397 ...(commandId ? { commandId } : {}),
398 },
399 )
400 : host.connection.request(method, {
401 ...(nativeSessionId ? { sessionId: nativeSessionId } : {}),
402 ...params,
403 }),
404 catch: (cause) =>
405 protocolError(
406 cause instanceof Error && cause.message
407 ? `Muse ${method} failed: ${cause.message}`
408 : `Muse ${method} failed`,
409 cause,
410 ),
411 }).pipe(
412 Effect.timeout(options.requestTimeoutMs ?? 30_000),
413 Effect.catchTags({
414 // The enclosing operation owns the span for this inline handler.
415 TimeoutError: Effect.fnUntraced(function* (cause) {
416 yield* eventPermit.withPermits(1)(failHost(cause));
417 return yield* protocolError(`Muse ${method} timed out; its host was closed`, cause);
418 }),
419 }),
420 );
421 const updateSession = Effect.fnUntraced(function* (
422 status: OrchestrationV2ProviderSession["status"],
423 lastError: string | null = null,
424 ) {
425 session = {
426 ...session,
427 status,
428 // lastError is the thread banner, so it gets the failure item's bounded, redacted text.
429 lastError:
430 lastError === null ? null : makeProviderFailure({ message: lastError }).message,
431 updatedAt: yield* DateTime.now,
432 };
433 yield* emit({
434 type: "provider_session.updated",
435 driver: MUSE_PROVIDER,
436 providerSession: session,
437 });
438 });
439 const updateThread = Effect.fnUntraced(function* (
440 patch: Partial<OrchestrationV2ProviderThread>,
441 ) {
442 if (!thread) return;
443 thread = { ...thread, ...patch, updatedAt: yield* DateTime.now };
444 yield* emit({
445 type: "provider_thread.updated",
446 driver: MUSE_PROVIDER,
447 providerThread: thread,
448 });
449 });
450 const itemIdentity = (turn: ActiveTurn, nativeId: string) =>
451 `${options.instanceId}:${turn.input.providerThread.id}:${turn.nativeId}:${nativeId}`;
452 const baseItem = (turn: ActiveTurn, nativeId: string, time: DateTime.Utc) => {
453 if (!turn.ordinals.has(nativeId)) turn.ordinals.set(nativeId, turn.nextOrdinal++);
454 if (!turn.started.has(nativeId)) turn.started.set(nativeId, time);
455 const identity = itemIdentity(turn, nativeId);
456 return {
457 id: idAllocator.derive.turnItemFromProviderItem({
458 driver: MUSE_PROVIDER,
459 nativeItemId: identity,
460 }),
461 nodeId: idAllocator.derive.nodeFromProviderItem({
462 driver: MUSE_PROVIDER,
463 nativeItemId: identity,
464 }),
465 threadId: turn.input.threadId,
466 runId: turn.input.runId,
467 providerThreadId: turn.input.providerThread.id,
468 providerTurnId: turn.providerTurn.id,
469 nativeItemRef: nativeRef(nativeId),
470 parentItemId: null,
471 ordinal: turn.ordinals.get(nativeId)!,
472 startedAt: turn.started.get(nativeId)!,
473 updatedAt: time,
474 };
475 };
476 const emitRetry = Effect.fnUntraced(function* (
477 turn: ActiveTurn,
478 row: MuseRetryRow,
479 status: "running" | "completed" | "interrupted",
480 ) {
481 const time = yield* DateTime.now;
482 const base = baseItem(turn, row.nativeId, time);
483 yield* emit({
484 type: "turn_item.updated",
485 driver: MUSE_PROVIDER,
486 turnItem: {
487 ...makeProviderRetryTurnItem({
488 ...base,
489 driver: MUSE_PROVIDER,
490 nodeId: turn.input.rootNodeId,
491 itemOrdinal: base.ordinal,
492 failure: makeProviderFailure({
493 // Clients show only the failure message, so a waiting row carries its delay.
494 message:
495 status === "running"
496 ? `${row.cause}. Retrying in ${formatDuration(row.retry.retryDelayMs ?? 0)}.`
497 : row.cause,
498 code: row.code,
499 class: "provider_error",
500 retryable: true,
501 }),
502 retry: row.retry,
503 status,
504 updatedAt: time,
505 }),
506 // The shared helper keys one row per turn; a long Muse turn can retry several times.
507 id: base.id,
508 },
509 });
510 });
511 // Muse sends no recovered event, so model output or the turn's end closes open retry rows.
512 const settleRetries = Effect.fnUntraced(function* (
513 turn: ActiveTurn,
514 status: "completed" | "interrupted",
515 ) {
516 for (const row of turn.retries) {
517 if (!row.running) continue;
518 row.running = false;
519 yield* emitRetry(turn, row, status);
520 }
521 });
522 const childItemIdentity = (context: ChildContext, nativeId: string) =>
523 `${options.instanceId}:child:${context.childSessionId}:${nativeId}`;
524 const itemStatus = (item: MuseItem): OrchestrationV2TurnItemStatus => {
525 const status = museItemStatus(item);
526 return status === "running" &&
527 item.kind === "subagent" &&
528 item.controlStatus === "resultReady"
529 ? "completed"
530 : status;
531 };
532 const publishChildRoot = Effect.fnUntraced(function* (
533 context: ChildContext,
534 status: OrchestrationV2TurnItemStatus,
535 time: DateTime.Utc,
536 ) {
537 context.status = status;
538 yield* emit({
539 type: "node.updated",
540 driver: MUSE_PROVIDER,
541 node: {
542 id: context.rootNodeId,
543 threadId: context.childThreadId,
544 runId: null,
545 parentNodeId: null,
546 rootNodeId: context.rootNodeId,
547 kind: "root_turn",
548 status,
549 countsForRun: false,
550 providerThreadId: null,
551 providerTurnId: null,
552 nativeItemRef: nativeRef(context.childSessionId),
553 runtimeRequestId: null,
554 checkpointScopeId: null,
555 startedAt: context.appThread.createdAt,
556 completedAt: status === "running" || status === "pending" ? null : time,
557 },
558 });
559 });
560 const publishChildMessage = Effect.fnUntraced(function* (
561 context: ChildContext,
562 role: "user" | "assistant",
563 text: string,
564 suffix: "prompt" | "result",
565 time: DateTime.Utc,
566 ) {
567 const identity = childItemIdentity(context, suffix);
568 const artifacts = makeSubagentConversationArtifacts({
569 messageId: idAllocator.derive.messageFromProviderItem({
570 driver: MUSE_PROVIDER,
571 nativeItemId: identity,
572 }),
573 ...(role === "user" ? { senderThreadId: context.parentThreadId } : {}),
574 turnItemId: idAllocator.derive.turnItemFromProviderItem({
575 driver: MUSE_PROVIDER,
576 nativeItemId: identity,
577 }),
578 threadId: context.childThreadId,
579 rootNodeId: context.rootNodeId,
580 providerThreadId: null,
581 providerTurnId: null,
582 nativeItemRef: nativeRef(context.childSessionId),
583 role,
584 text,
585 ordinal: suffix === "prompt" ? 1 : 2,
586 now: time,
587 });
588 yield* emit({ type: "message.updated", driver: MUSE_PROVIDER, message: artifacts.message });
589 yield* emit({
590 type: "turn_item.updated",
591 driver: MUSE_PROVIDER,
592 turnItem: artifacts.turnItem,
593 });
594 });
595 const ensureChildContext = Effect.fnUntraced(function* (
596 turn: ActiveTurn,
597 item: MuseItem,
598 parentNodeId: NodeId,
599 title: string,
600 prompt: string,
601 status: OrchestrationV2TurnItemStatus,
602 time: DateTime.Utc,
603 ) {
604 const existing = childrenByItemId.get(item.itemId);
605 const childSessionId = item.childSessionId;
606 if (existing || !childSessionId) return existing;
607 const childThreadId = idAllocator.derive.subagentThread({
608 driver: MUSE_PROVIDER,
609 providerInstanceId: options.instanceId,
610 nativeThreadId: childSessionId,
611 });
612 const appThread = makeSubagentChildThread({
613 parentThread: turn.input.appThread,
614 childThreadId,
615 parentNodeId,
616 activeProviderThreadId: null,
617 providerInstanceId: options.instanceId,
618 modelSelection: turn.input.modelSelection,
619 title,
620 now: time,
621 createdBy: "agent",
622 creationSource: "provider",
623 });
624 const context: ChildContext = {
625 childSessionId,
626 childThreadId,
627 appThread,
628 rootNodeId: idAllocator.derive.nodeFromProviderItem({
629 driver: MUSE_PROVIDER,
630 nativeItemId: `${options.instanceId}:child:${childSessionId}:thread-root`,
631 }),
632 parentThreadId: turn.input.threadId,
633 status,
634 };
635 childrenByItemId.set(item.itemId, context);
636 yield* emit({ type: "app_thread.created", driver: MUSE_PROVIDER, appThread });
637 yield* publishChildRoot(context, status, time);
638 if (prompt) yield* publishChildMessage(context, "user", prompt, "prompt", time);
639 return context;
640 });
641 const publishNativeSubagent = Effect.fnUntraced(function* (
642 turn: ActiveTurn,
643 item: MuseItem,
644 base: ReturnType<typeof baseItem> & {
645 readonly status: OrchestrationV2TurnItemStatus;
646 readonly completedAt: DateTime.Utc | null;
647 readonly title: string | null;
648 },
649 status: OrchestrationV2TurnItemStatus,
650 time: DateTime.Utc,
651 ) {
652 const prompt = item.objective ?? item.fallbackText ?? "";
653 const settled = status !== "running" && status !== "pending";
654 const endKey = `subagent:${item.itemId}`;
655 if (settled && !agentEndedAt.has(endKey)) agentEndedAt.set(endKey, time);
656 if (!settled) agentEndedAt.delete(endKey);
657 const completedAt = settled ? (agentEndedAt.get(endKey) ?? time) : null;
658 if (!agentTitles.has(endKey))
659 agentTitles.set(
660 endKey,
661 subagentThreadTitle({
662 parentTitle: turn.input.appThread.title,
663 prompt,
664 title: item.role ?? null,
665 ordinal: childrenByItemId.size + 1,
666 }),
667 );
668 const title = agentTitles.get(endKey)!;
669 const context = yield* ensureChildContext(
670 turn,
671 item,
672 base.nodeId,
673 title,
674 prompt,
675 status,
676 time,
677 );
678 const resultText =
679 item.result?.text ??
680 item.result?.summary ??
681 (status === "failed" ? item.failureReason : undefined);
682 const result = resultText ?? null;
683 const nativeTaskRef = nativeRef(backgroundTaskId(item));
684 const subagent: OrchestrationV2Subagent = {
685 id: base.nodeId,
686 threadId: base.threadId,
687 runId: base.runId,
688 parentNodeId: turn.input.rootNodeId,
689 origin: "provider_native",
690 createdBy: "agent",
691 driver: MUSE_PROVIDER,
692 providerInstanceId: options.instanceId,
693 providerThreadId: base.providerThreadId,
694 childThreadId: context?.childThreadId ?? null,
695 nativeTaskRef,
696 prompt,
697 title,
698 model: null,
699 status,
700 result,
701 startedAt: base.startedAt,
702 completedAt,
703 updatedAt: time,
704 };
705 yield* emit({ type: "subagent.updated", driver: MUSE_PROVIDER, subagent });
706 yield* emit({
707 type: "node.updated",
708 driver: MUSE_PROVIDER,
709 node: {
710 id: base.nodeId,
711 threadId: base.threadId,
712 runId: base.runId,
713 parentNodeId: turn.input.rootNodeId,
714 rootNodeId: turn.input.rootNodeId,
715 kind: "subagent",
716 status,
717 countsForRun: false,
718 providerThreadId: base.providerThreadId,
719 providerTurnId: base.providerTurnId,
720 nativeItemRef: nativeTaskRef,
721 runtimeRequestId: null,
722 checkpointScopeId: null,
723 startedAt: base.startedAt,
724 completedAt,
725 },
726 });
727 yield* emit({
728 type: "turn_item.updated",
729 driver: MUSE_PROVIDER,
730 turnItem: {
731 ...base,
732 nativeItemRef: nativeTaskRef,
733 type: "subagent",
734 status,
735 title,
736 completedAt,
737 subagentId: subagent.id,
738 origin: "provider_native",
739 driver: MUSE_PROVIDER,
740 providerInstanceId: options.instanceId,
741 childThreadId: subagent.childThreadId,
742 prompt,
743 result,
744 },
745 });
746 if (context) {
747 if (context.status !== status) yield* publishChildRoot(context, status, time);
748 if (settled && result?.trim() && context.result !== result) {
749 context.result = result;
750 yield* publishChildMessage(context, "assistant", result, "result", time);
751 }
752 }
753 });
754 const syncBackground = Effect.fnUntraced(function* () {
755 yield* updateThread({
756 pendingBackgroundTasks: [...observedChildren].flatMap(([itemId, owner]) => {
757 const item = owner.items.get(itemId);
758 const description = item?.objective ?? item?.entryId ?? item?.fallbackText;
759 return [
760 {
761 taskId: item ? backgroundTaskId(item) : itemId,
762 kind:
763 item?.kind === "subagent" ? ("subagent" as const) : ("background_task" as const),
764 ...(description ? { description } : {}),
765 },
766 ];
767 }),
768 });
769 });
770 const publishItem = Effect.fnUntraced(function* (
771 turn: ActiveTurn,
772 item: MuseItem,
773 terminal?: OrchestrationV2TurnItem["status"],
774 ) {
775 // Muse's skill-reminder child runs on every model step; it is housekeeping, not work.
776 if (item.kind === "userMessage" || item.kind === "reminderChild") return;
777 if (
778 item.kind === "toolCall" &&
779 item.tool &&
780 TOOLS_WITH_NATIVE_ROWS.has(item.tool) &&
781 item.status !== "failed"
782 )
783 return;
784 const time = yield* DateTime.now;
785 const status = terminal ?? itemStatus(item);
786 if (item.kind === "subagent" || item.kind === "workflow") {
787 const wasRunning = observedChildren.has(item.itemId);
788 if (status === "running") observedChildren.set(item.itemId, turn);
789 else if (observedChildren.delete(item.itemId) && active !== turn)
790 finishedBackground.push({
791 kind: item.kind === "subagent" ? "subagent" : "background_task",
792 label: item.objective ?? item.entryId ?? item.fallbackText,
793 outcome:
794 status === "completed"
795 ? "completed"
796 : status === "cancelled"
797 ? "cancelled"
798 : "failed",
799 });
800 const running = observedChildren.has(item.itemId);
801 // Muse reveals a subagent's ids over several revisions, so a running child is
802 // relisted whenever the id its turn item carries moves.
803 const listed = thread?.pendingBackgroundTasks?.some(
804 (task) => task.taskId === backgroundTaskId(item),
805 );
806 if (wasRunning !== running || (running && !listed)) yield* syncBackground();
807 }
808 const streaming = status === "running";
809 const base = {
810 ...baseItem(turn, item.itemId, time),
811 status,
812 completedAt: streaming ? null : time,
813 title: item.tool ?? null,
814 };
815 if (item.kind === "subagent") {
816 yield* publishNativeSubagent(turn, item, base, status, time);
817 return;
818 }
819 const text = item.text ?? item.summary?.join("\n") ?? item.fallbackText ?? "";
820 let turnItem: OrchestrationV2TurnItem;
821 if (item.kind === "agentMessage") {
822 const messageId = idAllocator.derive.messageFromProviderItem({
823 driver: MUSE_PROVIDER,
824 nativeItemId: itemIdentity(turn, item.itemId),
825 });
826 const message: OrchestrationV2ConversationMessage = {
827 id: messageId,
828 threadId: turn.input.threadId,
829 runId: turn.input.runId,
830 nodeId: base.nodeId,
831 role: "assistant",
832 text,
833 attachments: [],
834 streaming,
835 createdBy: "agent",
836 creationSource: "provider",
837 createdAt: base.startedAt,
838 updatedAt: time,
839 };
840 yield* emit({ type: "message.updated", driver: MUSE_PROVIDER, message });
841 turnItem = { ...base, type: "assistant_message", messageId, text, streaming };
842 } else if (item.kind === "reasoning") {
843 turnItem = { ...base, type: "reasoning", text, streaming };
844 } else if (item.kind === "compaction") {
845 turnItem = {
846 ...base,
847 type: "compaction",
848 driver: MUSE_PROVIDER,
849 summary: text || item.reason,
850 };
851 } else {
852 turnItem = { ...base, ...museToolPresentation(item, status) };
853 }
854 yield* emit({
855 type: "node.updated",
856 driver: MUSE_PROVIDER,
857 node: {
858 id: base.nodeId,
859 threadId: base.threadId,
860 runId: base.runId,
861 parentNodeId: turn.input.rootNodeId,
862 rootNodeId: turn.input.rootNodeId,
863 kind:
864 item.kind === "agentMessage"
865 ? "assistant_message"
866 : item.kind === "reasoning"
867 ? "reasoning"
868 : "tool_call",
869 status,
870 countsForRun: false,
871 providerThreadId: base.providerThreadId,
872 providerTurnId: base.providerTurnId,
873 nativeItemRef: base.nativeItemRef,
874 runtimeRequestId: null,
875 checkpointScopeId: null,
876 startedAt: base.startedAt,
877 completedAt: base.completedAt,
878 },
879 });
880 yield* emit({ type: "turn_item.updated", driver: MUSE_PROVIDER, turnItem });
881 if (item.kind === "workflow") yield* publishWorkflowAgents(turn, item, base, status);
882 });
883 const publishWorkflowAgents = Effect.fnUntraced(function* (
884 turn: ActiveTurn,
885 item: MuseItem,
886 workflow: { readonly id: OrchestrationV2TurnItem["id"]; readonly nodeId: NodeId },
887 workflowStatus: OrchestrationV2TurnItemStatus,
888 ) {
889 const latest = new Map((item.children ?? []).map((child) => [child.childId, child]));
890 for (const [index, child] of [...latest.values()].entries()) {
891 const time = yield* DateTime.now;
892 const base = baseItem(turn, `${item.itemId}:agent:${child.childId}`, time);
893 // Muse marks a failed attempt with `failureKind`, even when its terminal is `completed`.
894 const status: OrchestrationV2TurnItemStatus =
895 child.terminal === "completed" && child.failureKind === undefined
896 ? "completed"
897 : child.terminal === "cancelled"
898 ? "cancelled"
899 : child.terminal !== undefined
900 ? "failed"
901 : workflowStatus !== "running"
902 ? workflowStatus
903 : child.status === "scheduled"
904 ? "pending"
905 : "running";
906 const settled = status !== "running" && status !== "pending";
907 // Children are re-sent on every workflow change; keep each one's first end time.
908 const endKey = `${item.itemId}:${child.childId}:${child.attempt}`;
909 if (settled && !agentEndedAt.has(endKey)) agentEndedAt.set(endKey, time);
910 // Later revisions drop the label; keep the last one seen.
911 if (child.label?.trim()) agentTitles.set(endKey, child.label.trim());
912 const title = agentTitles.get(endKey) || `Agent ${index + 1}`;
913 const result = child.failureReason ?? child.failureKind ?? null;
914 const subagent: OrchestrationV2Subagent = {
915 id: base.nodeId,
916 threadId: base.threadId,
917 runId: base.runId,
918 parentNodeId: workflow.nodeId,
919 origin: "provider_native",
920 createdBy: "agent",
921 driver: MUSE_PROVIDER,
922 providerInstanceId: options.instanceId,
923 providerThreadId: base.providerThreadId,
924 childThreadId: null,
925 nativeTaskRef: nativeRef(child.childId),
926 prompt: title,
927 title,
928 model: null,
929 status,
930 result,
931 startedAt: base.startedAt,
932 completedAt: settled ? (agentEndedAt.get(endKey) ?? time) : null,
933 updatedAt: time,
934 };
935 yield* emit({ type: "subagent.updated", driver: MUSE_PROVIDER, subagent });
936 yield* emit({
937 type: "node.updated",
938 driver: MUSE_PROVIDER,
939 node: {
940 id: base.nodeId,
941 threadId: base.threadId,
942 runId: base.runId,
943 parentNodeId: workflow.nodeId,
944 rootNodeId: turn.input.rootNodeId,
945 kind: "subagent",
946 status,
947 countsForRun: false,
948 providerThreadId: base.providerThreadId,
949 providerTurnId: base.providerTurnId,
950 nativeItemRef: subagent.nativeTaskRef,
951 runtimeRequestId: null,
952 checkpointScopeId: null,
953 startedAt: base.startedAt,
954 completedAt: subagent.completedAt,
955 },
956 });
957 yield* emit({
958 type: "turn_item.updated",
959 driver: MUSE_PROVIDER,
960 turnItem: {
961 ...base,
962 nativeItemRef: subagent.nativeTaskRef,
963 parentItemId: workflow.id,
964 type: "subagent",
965 status,
966 title,
967 completedAt: subagent.completedAt,
968 subagentId: subagent.id,
969 origin: "provider_native",
970 driver: MUSE_PROVIDER,
971 providerInstanceId: options.instanceId,
972 childThreadId: null,
973 prompt: title,
974 result,
975 },
976 });
977 }
978 });
979 const settleObservedChildren = Effect.fnUntraced(function* (
980 status: "failed" | "cancelled" | "interrupted",
981 ) {
982 for (const [itemId, owner] of observedChildren) {
983 const item = owner.items.get(itemId);
984 if (item) yield* publishItem(owner, item, status);
985 }
986 observedChildren.clear();
987 if (thread?.pendingBackgroundTasks?.length) yield* syncBackground();
988 for (const entry of pending.values()) yield* resolvePending(entry, "cancelled");
989 });
990 const resolvePending = Effect.fnUntraced(function* (
991 entry: PendingRequest,
992 status: "resolved" | "cancelled",
993 ) {
994 const time = yield* DateTime.now;
995 entry.request = {
996 ...entry.request,
997 ...(status === "resolved" ? entry.response : undefined),
998 status,
999 resolvedAt: time,
1000 responseCapability: { type: "not_resumable", reason: "This Muse request has ended." },
1001 };
1002 entry.node = {
1003 ...entry.node,
1004 status: status === "resolved" ? "completed" : "cancelled",
1005 completedAt: time,
1006 };
1007 entry.item = {
1008 ...entry.item,
1009 status: status === "resolved" ? "completed" : "cancelled",
1010 completedAt: time,
1011 updatedAt: time,
1012 };
1013 pending.delete(entry.request.id);
1014 yield* emit({
1015 type: "runtime_request.updated",
1016 driver: MUSE_PROVIDER,
1017 threadId: input.threadId,
1018 runtimeRequest: entry.request,
1019 });
1020 yield* emit({ type: "node.updated", driver: MUSE_PROVIDER, node: entry.node });
1021 yield* emit({ type: "turn_item.updated", driver: MUSE_PROVIDER, turnItem: entry.item });
1022 });
1023 const finish = Effect.fnUntraced(function* (
1024 turn: ActiveTurn,
1025 status: "completed" | "cancelled" | "interrupted" | "failed",
1026 detail?: string,
1027 disposition: "reusable" | "broken" = "reusable",
1028 quota?: { readonly resetsAtMs: number },
1029 ) {
1030 if (active !== turn || seenTerminals.has(turn.nativeId)) return;
1031 seenTerminals.add(turn.nativeId);
1032 const completedAt = yield* DateTime.now;
1033 for (const item of turn.items.values()) {
1034 if (
1035 (item.kind === "subagent" || item.kind === "workflow") &&
1036 item.status === "inProgress" &&
1037 status === "completed" &&
1038 disposition === "reusable"
1039 )
1040 continue;
1041 if (turn.dirty.has(item.itemId) || item.status === "inProgress")
1042 yield* publishItem(turn, item, item.status === "inProgress" ? status : undefined);
1043 }
1044 turn.dirty.clear();
1045 // A failed turn has its own failure row; its retry rows only record that retrying stopped.
1046 yield* settleRetries(turn, status === "completed" ? "completed" : "interrupted");
1047 for (const entry of pending.values())
1048 if (entry.request.providerTurnId !== null) yield* resolvePending(entry, "cancelled");
1049 turn.providerTurn = { ...turn.providerTurn, status, completedAt };
1050 lastProviderTurn = turn.providerTurn;
1051 yield* emit({
1052 type: "provider_turn.updated",
1053 driver: MUSE_PROVIDER,
1054 threadId: turn.input.threadId,
1055 providerTurn: turn.providerTurn,
1056 });
1057 yield* updateThread({
1058 status: disposition === "broken" ? "error" : "idle",
1059 ...(!turn.compact && status === "completed"
1060 ? { nativeConversationHeadRef: nativeRef(turn.nativeId) }
1061 : {}),
1062 });
1063 yield* updateSession(disposition === "broken" ? "error" : "ready", detail ?? null);
1064 active = undefined;
1065 if (status === "failed") {
1066 const usageLimited =
1067 disposition === "reusable" && (quota !== undefined || isMuseUsageLimitFailure(detail));
1068 const failure = makeProviderFailure({
1069 class:
1070 disposition === "broken"
1071 ? "transport_error"
1072 : usageLimited
1073 ? "usage_limit"
1074 : "provider_error",
1075 message: detail ?? "Muse turn failed.",
1076 ...(usageLimited
1077 ? {
1078 resetAt: museUsageLimitResetAt(
1079 latestSubscriptionUsage,
1080 DateTime.toEpochMillis(completedAt),
1081 { quota, message: detail },
1082 ),
1083 }
1084 : {}),
1085 });
1086 const base = baseItem(turn, `failure:${turn.nativeId}`, completedAt);
1087 yield* emit({
1088 type: "turn_item.updated",
1089 driver: MUSE_PROVIDER,
1090 turnItem: {
1091 ...base,
1092 type: "error",
1093 status: "failed",
1094 title: usageLimited ? "Usage limit reached" : null,
1095 completedAt,
1096 failure,
1097 },
1098 });
1099 yield* emit({
1100 type: "turn.terminal",
1101 driver: MUSE_PROVIDER,
1102 providerThreadId: turn.providerTurn.providerThreadId,
1103 providerTurnId: turn.providerTurn.id,
1104 runOrdinal: turn.input.runOrdinal,
1105 status,
1106 failure,
1107 failureItemOrdinal: base.ordinal,
1108 threadDisposition: disposition,
1109 });
1110 } else {
1111 yield* emit({
1112 type: "turn.terminal",
1113 driver: MUSE_PROVIDER,
1114 providerThreadId: turn.providerTurn.providerThreadId,
1115 providerTurnId: turn.providerTurn.id,
1116 runOrdinal: turn.input.runOrdinal,
1117 status,
1118 failure: null,
1119 threadDisposition: disposition,
1120 });
1121 }
1122 yield* Deferred.succeed(turn.done, undefined);
1123 });
1124 const failHost = Effect.fnUntraced(function* (cause: unknown) {
1125 if (closed || broken) return;
1126 hostEpoch++;
1127 // Registration can replace the host while failure events are consumed.
1128 const failed = host;
1129 const turn = active;
1130 broken = true;
1131 relaunchable = !turn;
1132 wake = undefined;
1133 const rootCause = Cause.isCause(cause) ? Cause.squash(cause) : cause;
1134 const failure = isOpenSessionError(rootCause) ? rootCause.cause : rootCause;
1135 const detail = isProtocolError(failure)
1136 ? failure.detail
1137 : failure instanceof Error
1138 ? failure.message
1139 : "Muse transport failed.";
1140 if (turn) yield* finish(turn, "failed", detail, "broken");
1141 else {
1142 yield* updateThread({ status: "error" });
1143 yield* updateSession("error", detail);
1144 }
1145 yield* settleObservedChildren("failed");
1146 if (turn) yield* Queue.fail(events, protocolError(detail, cause));
1147 yield* Effect.tryPromise({
1148 try: () => failed.close(),
1149 catch: (cause) => new MuseSdkError({ operation: "close", cause }),
1150 }).pipe(Effect.ignore, Effect.forkIn(scope));
1151 });
1152 const owns = (turn: ActiveTurn, turnId: string) =>
1153 turnId === turn.nativeId || turn.joined.has(turnId);
1154 const decideApproval = Effect.fnUntraced(function* (
1155 entry: PendingRequest,
1156 decision: ProviderApprovalDecision | undefined,
1157 ) {
1158 if (entry.native.type !== "approval") return;
1159 const approval = entry.native.value;
1160 const choice = decision && museApprovalChoices(approval).get(decision);
1161 if (!choice) return yield* protocolError("Muse did not offer this approval decision");
1162 // Recorded first: Muse can settle the approval before it acknowledges the command.
1163 entry.response = { decision };
1164 yield* request("approval/decide", {
1165 approvalId: approval.approvalId,
1166 requirementId: approval.currentRequirementId,
1167 choiceId: choice.choiceId,
1168 }).pipe(Effect.tapError(() => Effect.sync(() => delete entry.response)));
1169 });
1170 const showRequest = Effect.fnUntraced(function* (entry: PendingRequest) {
1171 entry.shown = true;
1172 yield* emit({
1173 type: "runtime_request.updated",
1174 driver: MUSE_PROVIDER,
1175 threadId: entry.node.threadId,
1176 runtimeRequest: entry.request,
1177 });
1178 yield* emit({ type: "node.updated", driver: MUSE_PROVIDER, node: entry.node });
1179 yield* emit({ type: "turn_item.updated", driver: MUSE_PROVIDER, turnItem: entry.item });
1180 yield* updateSession("waiting");
1181 });
1182 /**
1183 * A workflow child's approval is runless: the turn that started the workflow
1184 * may end long before the child asks, and T3 keeps a runless request on the
1185 * thread until Muse settles it.
1186 */
1187 const publishRequest = Effect.fnUntraced(function* (native: PendingRequest["native"]) {
1188 const child = native.type === "approval" && native.value.subagentOrigin !== undefined;
1189 const turn = child ? undefined : active;
1190 if (
1191 !thread ||
1192 (!child && !turn) ||
1193 native.value.sessionId !== nativeSessionId ||
1194 (turn && native.value.turnId && !owns(turn, native.value.turnId))
1195 )
1196 return;
1197 const nativeId =
1198 native.type === "approval" ? native.value.approvalId : native.value.userInputId;
1199 if (turn?.settledRequests.has(`${native.type}:${nativeId}`)) return;
1200 const previous = [...pending.values()].find(
1201 (entry) =>
1202 entry.native.type === native.type &&
1203 entry.request.nativeRequestRef?.nativeId === nativeId,
1204 );
1205 const providerTurnId = turn?.providerTurn.id ?? null;
1206 const threadId = turn?.input.threadId ?? thread.appThreadId ?? input.threadId;
1207 const requestId =
1208 previous?.request.id ??
1209 (yield* idAllocator.allocate
1210 .runtimeRequest({
1211 driver: MUSE_PROVIDER,
1212 ...(providerTurnId ? { providerTurnId } : {}),
1213 nativeRequestId: nativeId,
1214 })
1215 .pipe(
1216 Effect.mapError((cause) => protocolError("Cannot allocate Muse request", cause)),
1217 ));
1218 const time = yield* DateTime.now;
1219 const nodeId = idAllocator.derive.approvalNode({ requestId });
1220 const subject = native.type === "approval" ? native.value.subject : undefined;
1221 const kind = !subject
1222 ? "user_input"
1223 : subject.kind === "shell"
1224 ? "command"
1225 : subject.kind !== "fileAccess"
1226 ? "permission"
1227 : subject.access === "read"
1228 ? "file-read"
1229 : "file-change";
1230 const runtimeRequest: OrchestrationV2RuntimeRequest = {
1231 id: requestId,
1232 nodeId,
1233 providerTurnId,
1234 nativeRequestRef: nativeRef(nativeId),
1235 kind,
1236 status: "pending",
1237 responseCapability: { type: "live", providerSessionId: input.providerSessionId },
1238 createdAt: previous?.request.createdAt ?? time,
1239 resolvedAt: null,
1240 };
1241 const node: OrchestrationV2ExecutionNode = {
1242 id: nodeId,
1243 threadId,
1244 runId: turn?.input.runId ?? null,
1245 parentNodeId: turn?.input.rootNodeId ?? null,
1246 rootNodeId: turn?.input.rootNodeId ?? nodeId,
1247 kind: native.type === "approval" ? "approval_request" : "user_input_request",
1248 status: "waiting",
1249 countsForRun: false,
1250 providerThreadId: thread.id,
1251 providerTurnId,
1252 nativeItemRef: nativeRef(nativeId),
1253 runtimeRequestId: requestId,
1254 checkpointScopeId: null,
1255 startedAt: runtimeRequest.createdAt,
1256 completedAt: null,
1257 };
1258 const latestTurn = active?.providerTurn ?? lastProviderTurn;
1259 const base = {
1260 ...(turn
1261 ? baseItem(turn, `request:${nativeId}`, time)
1262 : {
1263 threadId,
1264 runId: null,
1265 providerThreadId: thread.id,
1266 providerTurnId: null,
1267 nativeItemRef: nativeRef(nativeId),
1268 parentItemId: null,
1269 ordinal: previous?.item.ordinal ?? ((latestTurn?.ordinal ?? 0) + 1) * 100,
1270 startedAt: runtimeRequest.createdAt,
1271 updatedAt: time,
1272 }),
1273 id: idAllocator.derive.approvalTurnItem({ requestId }),
1274 nodeId,
1275 status: "waiting" as const,
1276 title: null,
1277 completedAt: null,
1278 };
1279 const item: OrchestrationV2TurnItem =
1280 native.type === "approval"
1281 ? {
1282 ...base,
1283 type: "approval_request",
1284 requestId,
1285 requestKind: kind === "user_input" ? "command" : kind,
1286 prompt:
1287 native.value.subject.command ??
1288 native.value.subject.path ??
1289 native.value.subject.host ??
1290 native.value.subject.target ??
1291 native.value.toolName ??
1292 "Muse requests permission",
1293 options: museApprovalOptions(native.value),
1294 }
1295 : {
1296 ...base,
1297 type: "user_input_request",
1298 requestId,
1299 questions: native.value.questions.map((question) => ({
1300 id: question.id,
1301 header: question.header || "Question",
1302 question: question.question,
1303 options: question.options.map((option) => ({
1304 label: option.label,
1305 description: option.description || option.label,
1306 })),
1307 multiSelect: question.selection.mode === "multiple",
1308 allowCustomAnswer: true,
1309 required: true,
1310 })),
1311 };
1312 // Muse does not propagate allowAll to workflow children; T3 answers for them.
1313 const autoApprove = child && input.runtimePolicy.runtimeMode === "full-access";
1314 const entry: PendingRequest = {
1315 native,
1316 request: runtimeRequest,
1317 node,
1318 item,
1319 shown: !autoApprove || previous?.shown === true,
1320 };
1321 pending.set(requestId, entry);
1322 if (entry.shown) yield* showRequest(entry);
1323 if (autoApprove)
1324 yield* decideApproval(entry, "accept").pipe(
1325 Effect.catch(() =>
1326 Effect.gen(function* () {
1327 // Native updates may settle or replace this entry while the RPC is in flight.
1328 if (!closed && !broken && pending.get(requestId) === entry)
1329 yield* showRequest(entry);
1330 }).pipe(eventPermit.withPermits(1)),
1331 ),
1332 Effect.forkIn(scope),
1333 );
1334 });
1335 const handleRequestEvent = Effect.fnUntraced(function* (
1336 method: string,
1337 params: Record<string, unknown>,
1338 turn: ActiveTurn | undefined,
1339 ) {
1340 switch (method) {
1341 case "approval/requested":
1342 case "approval/updated":
1343 if (
1344 method === "approval/updated" &&
1345 ![...pending.values()].some(
1346 (entry) =>
1347 entry.native.type === "approval" &&
1348 entry.native.value.approvalId === params.approvalId,
1349 )
1350 )
1351 return;
1352 return yield* publishRequest({
1353 type: "approval",
1354 value: yield* decode(MuseApproval, params),
1355 });
1356 case "userInput/requested":
1357 return yield* publishRequest({
1358 type: "question",
1359 value: yield* decode(MuseUserInput, params),
1360 });
1361 case "approval/resolved":
1362 case "userInput/settled": {
1363 const id = method === "approval/resolved" ? params.approvalId : params.userInputId;
1364 if (typeof id === "string")
1365 turn?.settledRequests.add(
1366 `${method === "approval/resolved" ? "approval" : "question"}:${id}`,
1367 );
1368 const entry = [...pending.values()].find(
1369 (candidate) => candidate.request.nativeRequestRef?.nativeId === id,
1370 );
1371 if (entry) {
1372 const native =
1373 method === "approval/resolved" && typeof params.decision === "string"
1374 ? museApprovalDecision({ decision: params.decision, scope: "once" })
1375 : undefined;
1376 if (!entry.response && native) entry.response = { decision: native };
1377 yield* resolvePending(entry, "resolved");
1378 }
1379 if (![...pending.values()].some((candidate) => candidate.shown))
1380 yield* updateSession(active ? "running" : "ready");
1381 }
1382 }
1383 });
1384 const handleNotification = Effect.fnUntraced(function* (method: string, data: unknown) {
1385 const params = yield* decode(recordSchema, data);
1386 // usage/changed is account-wide and carries no session ID.
1387 if (method === "usage/changed") {
1388 latestSubscriptionUsage = yield* decode(MuseSubscriptionUsage, params);
1389 if (options.onUsageLimits) {
1390 yield* options.onUsageLimits(museUsageToLimits(latestSubscriptionUsage));
1391 }
1392 return;
1393 }
1394 if (params.sessionId !== nativeSessionId) return;
1395 if (method === "view/gap")
1396 return yield* protocolError("Muse delivery gap requires session recovery");
1397 if (method === "session/contextUsage") {
1398 const usage = yield* decode(MuseContextUsage, params);
1399 const currentTurn = active?.providerTurn ?? lastProviderTurn;
1400 const updatedAt = DateTime.formatIso(yield* DateTime.now);
1401 const tokenUsage = {
1402 ...currentTurn?.tokenUsage,
1403 usedTokens: usage.usedTokens,
1404 maxTokens: usage.windowTokens ?? currentTurn?.tokenUsage?.maxTokens ?? undefined,
1405 updatedAt,
1406 };
1407 yield* updateThread({ contextUsage: tokenUsage });
1408 if (currentTurn) {
1409 const updated = { ...currentTurn, tokenUsage };
1410 if (active) active.providerTurn = updated;
1411 else lastProviderTurn = updated;
1412 yield* emit({
1413 type: "provider_turn.updated",
1414 driver: MUSE_PROVIDER,
1415 providerTurn: updated,
1416 });
1417 }
1418 return;
1419 }
1420 const itemEvent = ["item/started", "item/updated", "item/completed"].includes(method)
1421 ? (yield* decode(MuseItemEvent, params)).item
1422 : undefined;
1423 if (itemEvent) {
1424 const owner = observedChildren.get(itemEvent.itemId);
1425 if (owner && owner !== active && itemEvent.turnId === owner.nativeId) {
1426 const previous = owner.items.get(itemEvent.itemId);
1427 if (!previous || itemEvent.revision > previous.revision) {
1428 owner.items.set(itemEvent.itemId, itemEvent);
1429 yield* publishItem(owner, itemEvent);
1430 }
1431 return;
1432 }
1433 }
1434 // Child approvals use their own run IDs and can outlive turns; bypass turn routing.
1435 if (params.subagentOrigin !== undefined && method.startsWith("approval/"))
1436 return yield* handleRequestEvent(method, params, undefined);
1437 if (
1438 method === "turn/started" &&
1439 typeof params.turnId === "string" &&
1440 params.turnId !== active?.nativeId &&
1441 params.turnId !== wake?.nativeId
1442 ) {
1443 if (active && !active.compact) active.joined.add(params.turnId);
1444 else if (!active && !wake) {
1445 const held = { nativeId: params.turnId, events: [] };
1446 wake = held;
1447 const notification = backgroundWorkNotification(finishedBackground.splice(0));
1448 if (thread?.appThreadId && options.continuationRequests)
1449 yield* options.continuationRequests.offer({
1450 threadId: thread.appThreadId,
1451 providerThreadId: thread.id,
1452 driver: MUSE_PROVIDER,
1453 detail: null,
1454 ...(notification ? { notification } : {}),
1455 dispatchIfCurrent: (dispatch) =>
1456 wake === held ? Effect.asSome(dispatch) : Effect.succeedNone,
1457 clearIfCurrent: () =>
1458 Effect.sync(() => {
1459 if (wake === held) wake = undefined;
1460 }),
1461 });
1462 }
1463 }
1464 // Muse compacts the latest run, which can be the held wake; its compaction item ends this turn.
1465 if (
1466 wake &&
1467 active?.nativeId !== wake.nativeId &&
1468 !(active?.compact && itemEvent?.kind === "compaction")
1469 ) {
1470 const turnId = typeof params.turnId === "string" ? params.turnId : itemEvent?.turnId;
1471 if (turnId === wake.nativeId) {
1472 wake.events.push([method, data]);
1473 return;
1474 }
1475 }
1476 const turn = active;
1477 if (!turn) return;
1478 if (typeof params.turnId === "string" && !owns(turn, params.turnId) && !turn.compact)
1479 return;
1480 switch (method) {
1481 case "item/started":
1482 case "item/updated":
1483 case "item/completed": {
1484 const item = itemEvent!;
1485 if (
1486 item.turnId &&
1487 !owns(turn, item.turnId) &&
1488 !(turn.compact && item.kind === "compaction")
1489 )
1490 return;
1491 const previous = turn.items.get(item.itemId);
1492 if (previous && previous.revision >= item.revision) return;
1493 if (method === "item/started" && MODEL_OUTPUT_KINDS.has(item.kind))
1494 yield* settleRetries(turn, "completed");
1495 turn.items.set(item.itemId, item);
1496 turn.dirty.delete(item.itemId);
1497 yield* publishItem(turn, item);
1498 if (turn.compact && item.kind === "compaction" && item.status !== "inProgress") {
1499 yield* finish(
1500 turn,
1501 item.status === "completed" && (!item.outcome || item.outcome === "compacted")
1502 ? "completed"
1503 : item.status === "cancelled"
1504 ? "cancelled"
1505 : "failed",
1506 item.failureReason ?? item.reason,
1507 );
1508 }
1509 break;
1510 }
1511 case "item/delta": {
1512 const delta = yield* decode(MuseDelta, params);
1513 const previous = turn.items.get(delta.itemId);
1514 if (!previous || previous.status !== "inProgress") return;
1515 const field = delta.field ?? "text";
1516 let item = previous;
1517 if (field === "text") item = { ...previous, text: (previous.text ?? "") + delta.delta };
1518 else if (field === "output" || field === "visibleOutput")
1519 item = { ...previous, visibleOutput: (previous.visibleOutput ?? "") + delta.delta };
1520 else if (field.startsWith("summary.")) {
1521 const index = Number(field.slice(8));
1522 if (Number.isSafeInteger(index) && index >= 0 && index < 100) {
1523 const summary = [...(previous.summary ?? [])];
1524 summary[index] = (summary[index] ?? "") + delta.delta;
1525 item = { ...previous, summary };
1526 }
1527 }
1528 if (item === previous) return;
1529 turn.items.set(item.itemId, item);
1530 turn.dirty.add(item.itemId);
1531 if (!turn.flushScheduled) {
1532 turn.flushScheduled = true;
1533 yield* Effect.sleep(50).pipe(
1534 Effect.andThen(Queue.offer(inbox, { type: "flush", turn })),
1535 Effect.forkIn(scope),
1536 );
1537 }
1538 break;
1539 }
1540 case "turn/completed": {
1541 if (turn.compact) return;
1542 const result = yield* decode(MuseTurnCompleted, params);
1543 // A joined Muse turn ending does not end this run; its own turn does.
1544 if (result.turnId !== turn.nativeId) break;
1545 if (result.usage) {
1546 const usage = result.usage;
1547 turn.providerTurn = {
1548 ...turn.providerTurn,
1549 turnTokenUsage: {
1550 usageScope: "main_agent",
1551 usageStatus: "complete",
1552 hasSubagents: [...turn.items.values()].some((item) => item.kind === "subagent"),
1553 inputTokens: turn.providerTurn.turnTokenUsage?.inputTokens ?? usage.inputTokens,
1554 outputTokens: usage.outputTokens,
1555 cachedInputTokens: usage.cacheReadTokens ?? usage.cachedTokens,
1556 reasoningTokens: usage.reasoningTokens,
1557 ...(usage.cacheWriteTokens === undefined
1558 ? {}
1559 : { cacheCreationTokens: usage.cacheWriteTokens }),
1560 },
1561 };
1562 }
1563 const status =
1564 result.terminal === "completed"
1565 ? "completed"
1566 : result.terminal === "cancelled"
1567 ? turn.interruptRequested
1568 ? "interrupted"
1569 : "cancelled"
1570 : "failed";
1571 yield* finish(
1572 turn,
1573 status,
1574 result.error?.message ?? result.reason,
1575 "reusable",
1576 result.error?.quota,
1577 );
1578 break;
1579 }
1580 case "approval/requested":
1581 case "approval/updated":
1582 case "approval/resolved":
1583 case "userInput/requested":
1584 case "userInput/settled":
1585 yield* handleRequestEvent(method, params, turn);
1586 break;
1587 case "session/tokenUsage": {
1588 const usage = yield* decode(MuseTokenUsageEvent, params);
1589 yield* settleRetries(turn, "completed");
1590 const previous = turn.providerTurn.turnTokenUsage;
1591 const contextUsage = thread?.contextUsage;
1592 turn.providerTurn = {
1593 ...turn.providerTurn,
1594 ...(contextUsage
1595 ? {
1596 tokenUsage: {
1597 ...turn.providerTurn.tokenUsage,
1598 usedTokens: contextUsage.usedTokens,
1599 inputTokens: usage.usage.inputTokens,
1600 outputTokens: usage.usage.outputTokens,
1601 cachedInputTokens: usage.usage.cacheReadTokens ?? usage.usage.cachedTokens,
1602 reasoningOutputTokens: usage.usage.reasoningTokens,
1603 updatedAt: DateTime.formatIso(yield* DateTime.now),
1604 },
1605 }
1606 : {}),
1607 turnTokenUsage: {
1608 usageScope: "main_agent",
1609 usageStatus: "partial",
1610 hasSubagents: [...turn.items.values()].some((item) => item.kind === "subagent"),
1611 inputTokens: (previous?.inputTokens ?? 0) + usage.promptTokens,
1612 outputTokens: (previous?.outputTokens ?? 0) + usage.usage.outputTokens,
1613 cachedInputTokens:
1614 (previous?.cachedInputTokens ?? 0) +
1615 (usage.usage.cacheReadTokens ?? usage.usage.cachedTokens),
1616 ...(usage.usage.cacheWriteTokens === undefined &&
1617 previous?.cacheCreationTokens === undefined
1618 ? {}
1619 : {
1620 cacheCreationTokens:
1621 (previous?.cacheCreationTokens ?? 0) + (usage.usage.cacheWriteTokens ?? 0),
1622 }),
1623 reasoningTokens: (previous?.reasoningTokens ?? 0) + usage.usage.reasoningTokens,
1624 },
1625 };
1626 yield* emit({
1627 type: "provider_turn.updated",
1628 driver: MUSE_PROVIDER,
1629 providerTurn: turn.providerTurn,
1630 });
1631 break;
1632 }
1633 case "session/todoListChanged": {
1634 const todo = yield* decode(MuseTodoList, params);
1635 const steps: ReadonlyArray<OrchestrationV2PlanStep> = todo.items
1636 .filter((item) => item.text.trim() && item.status !== "cancelled")
1637 .map((item, index) => ({
1638 id: `${turn.nativeId}:todo:${index}`,
1639 text: item.text.trim(),
1640 status:
1641 item.status === "completed"
1642 ? "completed"
1643 : item.status === "inProgress"
1644 ? "running"
1645 : "pending",
1646 }));
1647 const time = yield* DateTime.now;
1648 const base = baseItem(turn, "todo", time);
1649 const planId =
1650 turn.todoPlanId ??
1651 (yield* idAllocator.allocate
1652 .plan({
1653 threadId: turn.input.threadId,
1654 runId: turn.input.runId,
1655 driver: MUSE_PROVIDER,
1656 })
1657 .pipe(
1658 Effect.mapError((cause) =>
1659 protocolError("Cannot allocate Muse todo list", cause),
1660 ),
1661 ));
1662 turn.todoPlanId = planId;
1663 yield* emit({
1664 type: "plan.updated",
1665 driver: MUSE_PROVIDER,
1666 plan: {
1667 id: planId,
1668 threadId: turn.input.threadId,
1669 runId: turn.input.runId,
1670 nodeId: base.nodeId,
1671 kind: "todo_list",
1672 status: steps.every((step) => step.status === "completed") ? "completed" : "active",
1673 steps,
1674 },
1675 });
1676 yield* emit({
1677 type: "node.updated",
1678 driver: MUSE_PROVIDER,
1679 node: {
1680 id: base.nodeId,
1681 threadId: base.threadId,
1682 runId: base.runId,
1683 parentNodeId: turn.input.rootNodeId,
1684 rootNodeId: turn.input.rootNodeId,
1685 kind: "todo_list",
1686 status: "completed",
1687 countsForRun: false,
1688 providerThreadId: base.providerThreadId,
1689 providerTurnId: base.providerTurnId,
1690 nativeItemRef: null,
1691 runtimeRequestId: null,
1692 checkpointScopeId: null,
1693 startedAt: base.startedAt,
1694 completedAt: time,
1695 },
1696 });
1697 yield* emit({
1698 type: "turn_item.updated",
1699 driver: MUSE_PROVIDER,
1700 turnItem: {
1701 ...base,
1702 nativeItemRef: null,
1703 type: "todo_list",
1704 status: "completed",
1705 title: null,
1706 completedAt: time,
1707 planId,
1708 steps,
1709 },
1710 });
1711 break;
1712 }
1713 case "turn/retryScheduled":
1714 case "turn/modelRetryScheduled": {
1715 const retry = yield* decode(MuseRetryScheduled, params);
1716 const cause =
1717 retry.httpStatus === undefined ? retry.errorKind : `HTTP ${retry.httpStatus}`;
1718 // A chain's first retry opens a row; its later attempts update that row.
1719 const index =
1720 retry.attempt > 1 ? turn.retries.findLastIndex((row) => row.method === method) : -1;
1721 const row: MuseRetryRow = {
1722 method,
1723 nativeId: turn.retries[index]?.nativeId ?? `retry:${retry.sourceRange.first.id}`,
1724 // Muse counts the first request as attempt 1; T3 counts retries.
1725 retry: {
1726 attempt: retry.attempt,
1727 maxAttempts: Math.max(1, retry.maxAttempts - 1),
1728 retryDelayMs: Math.trunc(retry.retryDelayMs),
1729 },
1730 cause:
1731 retry.reason ??
1732 (cause ? `Model request failed (${cause})` : "Model request failed"),
1733 code: retry.errorKind,
1734 running: true,
1735 };
1736 if (index === -1) turn.retries.push(row);
1737 else turn.retries[index] = row;
1738 yield* emitRetry(turn, row, "running");
1739 break;
1740 }
1741 }
1742 });
1743 yield* Stream.fromQueue(inbox).pipe(
1744 Stream.runForEach((entry) =>
1745 Effect.gen(function* () {
1746 if (entry.type === "flush") {
1747 const turn = entry.turn;
1748 turn.flushScheduled = false;
1749 if (active !== turn) return;
1750 for (const id of turn.dirty) {
1751 const item = turn.items.get(id);
1752 if (item) yield* publishItem(turn, item);
1753 }
1754 turn.dirty.clear();
1755 } else if (entry.epoch === hostEpoch) {
1756 if (entry.type === "failure") yield* failHost(entry.cause);
1757 else {
1758 if (options.nativeEventLogger && entry.method !== "item/delta")
1759 yield* options.nativeEventLogger.write(
1760 { provider: "muse", method: entry.method, params: entry.params },
1761 input.threadId,
1762 );
1763 yield* handleNotification(entry.method, entry.params).pipe(
1764 Effect.catch((cause) =>
1765 INFORMATIONAL_NOTIFICATIONS.has(entry.method)
1766 ? Effect.logWarning(`Skipped an unreadable Muse ${entry.method}`, cause)
1767 : failHost(cause),
1768 ),
1769 );
1770 }
1771 }
1772 }).pipe(eventPermit.withPermits(1)),
1773 ),
1774 Effect.forkIn(scope),
1775 );
1776 const launchHost = Effect.fnUntraced(function* () {
1777 const epoch = ++hostEpoch;
1778 const mcpSession = yield* mcpSessions.read(input.threadId);
1779 const environment = McpProviderSession.withAgentDeviceEnvironment(
1780 options.environment,
1781 mcpSession,
1782 );
1783 const launch = yield* agentScope.wrap({
1784 command: options.settings.binaryPath || "muse",
1785 args: [],
1786 name: "muse",
1787 threadId: input.threadId,
1788 env: environment,
1789 });
1790 // Finalizers run in reverse order: reap detached work after closing the host.
1791 const scopeUnit = launch.unit;
1792 const stopScope =
1793 scopeUnit === undefined ? Effect.void : yield* Effect.cached(agentScope.stop(scopeUnit));
1794 yield* Scope.addFinalizer(scope, stopScope);
1795 const processExited = yield* Deferred.make<ProcessExit>();
1796 // Observe raw exit before acquisition: inherited stdout can also block startup cleanup.
1797 yield* Deferred.await(processExited).pipe(Effect.andThen(stopScope), Effect.forkIn(scope));
1798 const created = yield* Effect.acquireRelease(
1799 createMuseSdkHostEffect(
1800 {
1801 binaryPath: launch.command,
1802 launchArgs: launch.args,
1803 cwd,
1804 environment,
1805 runtimeMode: input.runtimePolicy.runtimeMode,
1806 onProcessExit: (exit) => {
1807 Deferred.doneUnsafe(processExited, Effect.succeed(exit));
1808 },
1809 },
1810 options.createHost,
1811 ).pipe(
1812 Effect.mapError(
1813 (error) =>
1814 new ProviderAdapter.ProviderAdapterOpenSessionError({
1815 driver: MUSE_PROVIDER,
1816 providerSessionId: input.providerSessionId,
1817 cause: error.cause,
1818 }),
1819 ),
1820 ),
1821 (created) =>
1822 Effect.gen(function* () {
1823 if (host === created) {
1824 closed = true;
1825 hostEpoch++;
1826 }
1827 const close = Effect.tryPromise({
1828 try: () => created.close(),
1829 catch: (cause) => new MuseSdkError({ operation: "close", cause }),
1830 });
1831 // SDK shutdown sends SIGKILL after 10s + 2s, but inherited pipes can
1832 // keep its close promise pending. Let the scope reap those holders.
1833 yield* (
1834 scopeUnit === undefined
1835 ? close
1836 : close.pipe(Effect.interruptible, Effect.timeoutOption("13 seconds"))
1837 ).pipe(Effect.ignore);
1838 }),
1839 { interruptible: true },
1840 ).pipe(Effect.provideService(Scope.Scope, scope));
1841 host = created;
1842 created.connection.onNotification((notification) => {
1843 Queue.offerUnsafe(inbox, {
1844 type: "notification",
1845 method: notification.method,
1846 params: notification.params,
1847 epoch,
1848 });
1849 });
1850 created.connection.onProtocolError((cause) => {
1851 Queue.offerUnsafe(inbox, { type: "failure", cause, epoch });
1852 });
1853 created.connection.onServerRequest(async (request) => {
1854 if (request.method === "approval/request" || request.method === "userInput/request")
1855 return {};
1856 throw new Error(`Unsupported Muse server request: ${request.method}`);
1857 });
1858 void created.connection.closed.then(() => {
1859 if (!closed && epoch === hostEpoch)
1860 Queue.offerUnsafe(inbox, {
1861 type: "failure",
1862 cause: new Error("Muse connection closed unexpectedly"),
1863 epoch,
1864 });
1865 });
1866 const reportExit = (exit: ProcessExit) => {
1867 if (!closed && epoch === hostEpoch) {
1868 const reason = created
1869 .stderrTail?.()
1870 .findLast((line) => line.trim())
1871 ?.trim();
1872 Queue.offerUnsafe(inbox, {
1873 type: "failure",
1874 cause: new Error(
1875 `Muse exited unexpectedly (${exit.code ?? exit.signal})${reason ? `: ${reason}` : ""}`,
1876 ),
1877 epoch,
1878 });
1879 }
1880 };
1881 void created.exited.then(reportExit);
1882 yield* Deferred.await(processExited).pipe(
1883 Effect.tap((exit) => Effect.sync(() => reportExit(exit))),
1884 Effect.forkIn(scope),
1885 );
1886 });
1887 yield* Effect.addFinalizer(() =>
1888 Effect.gen(function* () {
1889 closed = true;
1890 hostEpoch++;
1891 if (active) yield* finish(active, "cancelled", "Muse session closed", "broken");
1892 yield* settleObservedChildren("cancelled");
1893 yield* Queue.shutdown(inbox);
1894 yield* Queue.shutdown(events);
1895 }).pipe(eventPermit.withPermits(1)),
1896 );
1897 yield* launchHost();
1898
1899 const register = Effect.fnUntraced(function* (
1900 args: ProviderAdapter.ProviderAdapterV2EnsureThreadInput,
1901 ) {
1902 if (closed || (broken && !relaunchable))
1903 return yield* protocolError("Muse host is unavailable; reopen the session");
1904 if (broken) {
1905 yield* Effect.logWarning("Relaunching the Muse host after a failure");
1906 yield* launchHost();
1907 broken = false;
1908 relaunchable = false;
1909 thread = undefined;
1910 nativeSessionId = undefined;
1911 yield* updateSession("ready", null);
1912 }
1913 if (active)
1914 return yield* protocolError("Cannot change Muse sessions during an active turn");
1915 const existing = args.existingProviderThread;
1916 if (
1917 existing &&
1918 (existing.driver !== MUSE_PROVIDER || existing.providerInstanceId !== options.instanceId)
1919 )
1920 return yield* protocolError("Muse thread belongs to another provider instance");
1921 const requestedId = existing
1922 ? (existing.nativeThreadRef?.nativeId ?? undefined)
1923 : input.initialNativeThreadId;
1924 if (
1925 thread &&
1926 (!requestedId || requestedId === nativeSessionId) &&
1927 thread.appThreadId === args.threadId
1928 )
1929 return thread;
1930 if (thread) return yield* protocolError("Open a new host to attach another Muse session");
1931 let missingNativeSession = false;
1932 return yield* Effect.gen(function* () {
1933 nativeSessionId = requestedId ?? host.connection.mintCommandId();
1934 const mcpSession = yield* mcpSessions.read(args.threadId);
1935 if (mcpSession && !host.initializeResult.grantedCapabilities.includes("sessionMcp"))
1936 return yield* protocolError(
1937 "Update Muse Code to a version that supports session MCP servers",
1938 );
1939 const config = mcpSession
1940 ? {
1941 mcpServers: {
1942 // Muse's required default fails runs if T3 tools are unreachable; make them optional.
1943 "t3-code": {
1944 transport: "streamableHttp",
1945 mode: "optional",
1946 url: mcpSession.endpoint,
1947 headers: { Authorization: mcpSession.authorizationHeader },
1948 },
1949 },
1950 }
1951 : undefined;
1952 const startModel = yield* resolveModel(args.modelSelection);
1953 const permissionProfile = musePermissionProfile(args.runtimePolicy.runtimeMode);
1954 const result = yield* request(
1955 requestedId ? "session/resume" : "session/start",
1956 requestedId
1957 ? { excludeItems: true, ...(config ? { config } : {}), permissionProfile }
1958 : {
1959 workspaceRoot: cwd,
1960 ...(config ? { config } : {}),
1961 ...(startModel ? { modelId: startModel } : {}),
1962 providerId: "meta",
1963 approvalMode: museApprovalMode(args.runtimePolicy.runtimeMode),
1964 permissionProfile,
1965 },
1966 ).pipe(
1967 Effect.catch((error) => {
1968 missingNativeSession =
1969 requestedId !== undefined &&
1970 error.payload instanceof MspError &&
1971 (error.payload.kind === "sessionNotFound" || error.payload.kind === "notFound");
1972 return Effect.fail(error);
1973 }),
1974 Effect.flatMap((value) => decode(MuseSessionResult, value)),
1975 );
1976 if (result.session.sessionId !== nativeSessionId)
1977 return yield* protocolError("Muse returned a different session identity");
1978 if (result.history?.noneReason === "projectionUnavailable")
1979 return yield* protocolError(
1980 "Muse cannot stream this session because its live view is unavailable",
1981 );
1982 if (requestedId)
1983 yield* request("session/setApprovalMode", {
1984 mode: museApprovalMode(args.runtimePolicy.runtimeMode),
1985 });
1986 const createdAt = yield* DateTime.now;
1987 thread = existing
1988 ? {
1989 ...existing,
1990 providerSessionId: input.providerSessionId,
1991 nativeThreadRef: nativeRef(result.session.sessionId),
1992 status: "idle",
1993 updatedAt: createdAt,
1994 }
1995 : {
1996 id: idAllocator.derive.providerThread({
1997 driver: MUSE_PROVIDER,
1998 providerInstanceId: options.instanceId,
1999 nativeThreadId: nativeSessionId,
2000 }),
2001 driver: MUSE_PROVIDER,
2002 providerInstanceId: options.instanceId,
2003 providerSessionId: input.providerSessionId,
2004 appThreadId: args.threadId,
2005 ownerNodeId: null,
2006 nativeThreadRef: nativeRef(nativeSessionId),
2007 nativeConversationHeadRef: null,
2008 status: "idle",
2009 firstRunOrdinal: null,
2010 lastRunOrdinal: null,
2011 handoffIds: [],
2012 forkedFrom: null,
2013 createdAt,
2014 updatedAt: createdAt,
2015 };
2016 session = {
2017 ...session,
2018 model: result.session.modelId ?? args.modelSelection.model,
2019 };
2020 yield* emit({
2021 type: "provider_thread.updated",
2022 driver: MUSE_PROVIDER,
2023 providerThread: thread,
2024 });
2025 return thread;
2026 }).pipe(
2027 Effect.onError((cause) =>
2028 missingNativeSession ? Effect.void : eventPermit.withPermits(1)(failHost(cause)),
2029 ),
2030 );
2031 });
2032 const prompt = Effect.fnUntraced(function* (
2033 message: ProviderAdapter.ProviderAdapterV2TurnMessage,
2034 ) {
2035 const parts: SendUserTurnOptions<unknown>["input"] = [];
2036 const text = yield* providerMessageTextWithAttachmentPaths({
2037 text: message.text,
2038 attachments: message.attachments,
2039 resolveAttachmentPath: providerHost.resolveAttachmentPath,
2040 resolveExtractedTextPath: providerHost.resolveExtractedTextPath,
2041 });
2042 if (text) parts.push({ type: "text", text });
2043 for (const attachment of message.attachments)
2044 if (isProviderNativeImageAttachment(attachment)) {
2045 const path = providerHost.resolveAttachmentPath(attachment);
2046 if (!path) return yield* protocolError("Muse image attachment is missing");
2047 const bytes = yield* fileSystem
2048 .readFile(path)
2049 .pipe(Effect.mapError((cause) => protocolError("Cannot read Muse image", cause)));
2050 parts.push({
2051 type: "image",
2052 base64Data: Buffer.from(bytes).toString("base64"),
2053 mediaType: attachment.mimeType,
2054 });
2055 }
2056 if (!parts.length) return yield* protocolError("Muse needs text or an image");
2057 return parts;
2058 });
2059 const validateThread = (candidate: OrchestrationV2ProviderThread) =>
2060 thread !== undefined &&
2061 candidate.driver === MUSE_PROVIDER &&
2062 candidate.providerInstanceId === options.instanceId &&
2063 candidate.appThreadId === thread.appThreadId &&
2064 candidate.nativeThreadRef?.nativeId === nativeSessionId;
2065 const selectionEffort = Effect.fnUntraced(function* (selection: ModelSelection) {
2066 if (selection.instanceId !== options.instanceId)
2067 return yield* protocolError("Model selection belongs to another Muse instance");
2068 const catalog = options.modelCatalog ? yield* options.modelCatalog : [];
2069 const model = yield* resolveModel(selection);
2070 const selected = getModelSelectionStringOptionValue(selection, "reasoningEffort");
2071 return resolveMuseReasoningEffort(
2072 catalog.find((entry) => entry.slug === model)?.capabilities ?? museModelCapabilities(),
2073 selected,
2074 );
2075 });
2076 const start = Effect.fnUntraced(function* (
2077 turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
2078 compact = false,
2079 ) {
2080 if (!validateThread(turnInput.providerThread) || broken || closed)
2081 return yield* protocolError("Muse thread is not attached to this host");
2082 if (active)
2083 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
2084 driver: MUSE_PROVIDER,
2085 detail: "Muse already has an active turn; queue through the orchestrator",
2086 reason: "previous_turn_active",
2087 });
2088 if (turnInput.runtimePolicy.interactionMode === "plan")
2089 return yield* protocolError("Muse does not support dedicated Plan mode");
2090 if (turnInput.runtimePolicy.runtimeMode !== input.runtimePolicy.runtimeMode)
2091 return yield* protocolError("Runtime policy changes require a fresh Muse host");
2092 const continuation =
2093 turnInput.message.createdBy === "agent" &&
2094 turnInput.message.creationSource === "provider";
2095 const adopted = continuation ? wake : undefined;
2096 const effort = continuation ? undefined : yield* selectionEffort(turnInput.modelSelection);
2097 const parts = compact || continuation ? [] : yield* prompt(turnInput.message);
2098 const targetModel = continuation
2099 ? undefined
2100 : yield* resolveModel(turnInput.modelSelection);
2101 if (targetModel && session.model !== targetModel) {
2102 yield* request("session/setModel", {
2103 model: { modelId: targetModel, providerId: "meta" },
2104 });
2105 session = { ...session, model: targetModel };
2106 }
2107 const nativeId = adopted?.nativeId ?? host.connection.mintCommandId();
2108 const startedAt = yield* DateTime.now;
2109 const providerTurn: OrchestrationV2ProviderTurn = {
2110 id: idAllocator.derive.providerTurn({
2111 driver: MUSE_PROVIDER,
2112 nativeTurnId: `${options.instanceId}:${nativeSessionId}:${nativeId}`,
2113 }),
2114 providerThreadId: turnInput.providerThread.id,
2115 nodeId: turnInput.rootNodeId,
2116 runAttemptId: turnInput.attemptId,
2117 nativeTurnRef: compact
2118 ? { ...nativeRef(nativeId), strength: "weak" }
2119 : nativeRef(nativeId),
2120 ordinal: turnInput.providerTurnOrdinal,
2121 status: "running",
2122 startedAt,
2123 completedAt: null,
2124 };
2125 const turn: ActiveTurn = {
2126 input: turnInput,
2127 providerTurn,
2128 nativeId,
2129 joined: new Set(),
2130 items: new Map(),
2131 ordinals: new Map(),
2132 started: new Map(),
2133 dirty: new Set(),
2134 settledRequests: new Set(),
2135 retries: [],
2136 done: yield* Deferred.make<void>(),
2137 nextOrdinal: turnInput.providerTurnOrdinal * 100 + 1,
2138 flushScheduled: false,
2139 interruptRequested: false,
2140 compact,
2141 };
2142 yield* Effect.gen(function* () {
2143 thread = turnInput.providerThread;
2144 active = turn;
2145 yield* emit({
2146 type: "provider_turn.updated",
2147 driver: MUSE_PROVIDER,
2148 threadId: turnInput.threadId,
2149 providerTurn,
2150 });
2151 yield* updateThread({
2152 status: "active",
2153 firstRunOrdinal: thread.firstRunOrdinal ?? turnInput.runOrdinal,
2154 lastRunOrdinal: turnInput.runOrdinal,
2155 });
2156 yield* updateSession("running");
2157 // Compaction cannot join a running wake, so the wake stays held for its continuation.
2158 const held = compact ? undefined : wake;
2159 if (held) wake = undefined;
2160 if (continuation && !held) return yield* finish(turn, "completed");
2161 if (held && !continuation) turn.joined.add(held.nativeId);
2162 for (const [method, data] of held?.events ?? [])
2163 yield* handleNotification(method, data).pipe(Effect.catch(failHost));
2164 }).pipe(eventPermit.withPermits(1));
2165 if (continuation) return;
2166 yield* Effect.gen(function* () {
2167 if (compact) {
2168 // The turn's terminal reports a declined compaction; only a broken host fails the command.
2169 const declined = yield* request("session/compact", {}, true, nativeId).pipe(
2170 Effect.flatMap((value) => decode(MuseCompactResult, value)),
2171 Effect.map((result) =>
2172 result.status === "accepted"
2173 ? undefined
2174 : result.status === "noop"
2175 ? (result.reason ?? "Muse has no context to compact.")
2176 : `Muse returned an unsupported compaction status: ${result.status}`,
2177 ),
2178 Effect.catch((error) => (broken ? Effect.fail(error) : Effect.succeed(error.detail))),
2179 );
2180 if (declined !== undefined)
2181 yield* eventPermit.withPermits(1)(finish(turn, "failed", declined));
2182 } else {
2183 const result = yield* request(
2184 "turn/start",
2185 {
2186 input: [
2187 {
2188 type: "text",
2189 text: buildRuntimeInstructions({
2190 harness: "Muse Code",
2191 model: session.model ?? undefined,
2192 reasoningEffort: effort,
2193 }),
2194 },
2195 ...parts,
2196 ],
2197 displayText: turnInput.message.text || "Image attachment",
2198 // Resumed sessions retain old roots; pin edits to the current checkout.
2199 workspaceRoots: [workspaceRoot],
2200 ifBusy: "queue",
2201 ...(effort ? { reasoningEffort: effort } : {}),
2202 },
2203 true,
2204 nativeId,
2205 ).pipe(Effect.flatMap((value) => decode(MuseTurnStartResult, value)));
2206 if (result.turnId !== nativeId) {
2207 yield* eventPermit.withPermits(1)(
2208 failHost(new Error("Muse admitted an unowned turn")),
2209 );
2210 return yield* protocolError("Muse admitted the turn under an unexpected identity");
2211 }
2212 }
2213 }).pipe(
2214 Effect.onError((cause) => {
2215 const error = Cause.squash(cause);
2216 const detail = isProtocolError(error)
2217 ? error.detail
2218 : error instanceof Error
2219 ? error.message
2220 : "Muse could not start the turn.";
2221 return eventPermit.withPermits(1)(finish(turn, "failed", detail));
2222 }),
2223 );
2224 });
2225 const snapshot = Effect.fnUntraced(function* (
2226 current: OrchestrationV2ProviderThread,
2227 ): Effect.fn.Return<
2228 ProviderAdapter.ProviderAdapterV2ThreadSnapshot,
2229 ProviderAdapter.ProviderAdapterV2Error
2230 > {
2231 const result = yield* request("session/read", { excludeItems: false }, false).pipe(
2232 Effect.flatMap((value) => decode(MuseSessionResult, value)),
2233 );
2234 if (result.session.sessionId !== nativeSessionId)
2235 return yield* protocolError("Muse snapshot belongs to a different session");
2236 const items = result.history?.items ?? result.history?.snapshot?.state.items ?? [];
2237 const now = yield* DateTime.now;
2238 return {
2239 providerThread: current,
2240 providerTurns: [],
2241 messages: items.flatMap((item): OrchestrationV2ConversationMessage[] =>
2242 item.kind === "agentMessage" || item.kind === "userMessage"
2243 ? [
2244 {
2245 id: idAllocator.derive.messageFromProviderItem({
2246 driver: MUSE_PROVIDER,
2247 nativeItemId: `${options.instanceId}:${current.id}:${item.turnId ?? "history"}:${item.itemId}`,
2248 }),
2249 threadId: current.appThreadId ?? input.threadId,
2250 runId: null,
2251 nodeId: null,
2252 role: item.kind === "agentMessage" ? "assistant" : "user",
2253 text: item.text ?? "",
2254 attachments: [],
2255 streaming: item.status === "inProgress",
2256 createdBy: item.kind === "agentMessage" ? "agent" : "user",
2257 creationSource: "provider",
2258 createdAt: now,
2259 updatedAt: now,
2260 },
2261 ]
2262 : [],
2263 ),
2264 runtimeRequests: [...pending.values()]
2265 .filter((entry) => entry.shown)
2266 .map((entry) => entry.request),
2267 providerPayload: items,
2268 };
2269 });
2270 const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = {
2271 instanceId: options.instanceId,
2272 driver: MUSE_PROVIDER,
2273 providerSessionId: input.providerSessionId,
2274 providerSession: session,
2275 events: Stream.fromQueue(events),
2276 backgroundTasksEndWithProcess: true,
2277 // A running workflow or a held Muse turn keeps the host: idle release must wait.
2278 hasPendingBackgroundWork: Effect.sync(
2279 () => observedChildren.size > 0 || wake !== undefined,
2280 ),
2281 ensureThread: (args) =>
2282 register(args).pipe(
2283 commands.withPermits(1),
2284 Effect.mapError(
2285 (cause) =>
2286 new ProviderAdapter.ProviderAdapterEnsureThreadError({
2287 driver: MUSE_PROVIDER,
2288 threadId: args.threadId,
2289 cause,
2290 }),
2291 ),
2292 ),
2293 resumeThread: (args) =>
2294 register({
2295 threadId: args.threadId ?? args.providerThread.appThreadId ?? input.threadId,
2296 modelSelection: args.modelSelection ?? input.modelSelection,
2297 runtimePolicy: args.runtimePolicy ?? input.runtimePolicy,
2298 existingProviderThread: args.providerThread,
2299 }).pipe(
2300 commands.withPermits(1),
2301 Effect.mapError(
2302 (cause) =>
2303 new ProviderAdapter.ProviderAdapterResumeThreadError({
2304 driver: MUSE_PROVIDER,
2305 providerSessionId: input.providerSessionId,
2306 providerThreadId: args.providerThread.id,
2307 cause,
2308 }),
2309 ),
2310 ),
2311 startTurn: (args) =>
2312 start(args).pipe(
2313 commands.withPermits(1),
2314 Effect.mapError(
2315 (cause) =>
2316 new ProviderAdapter.ProviderAdapterTurnStartError({
2317 driver: MUSE_PROVIDER,
2318 threadId: args.threadId,
2319 providerThreadId: args.providerThread.id,
2320 runId: args.runId,
2321 cause,
2322 }),
2323 ),
2324 ),
2325 compactThread: (args) => start(args, true).pipe(commands.withPermits(1)),
2326 steerTurn: Effect.fn("MuseAdapter.steerTurn")(
2327 function* (args) {
2328 const turn = active;
2329 if (
2330 !turn ||
2331 turn.providerTurn.id !== args.providerTurnId ||
2332 !validateThread(args.providerThread) ||
2333 turn.compact
2334 )
2335 return yield* protocolError("This Muse turn cannot be steered");
2336 const parts = yield* prompt(args.message);
2337 const result = yield* request("turn/steer", {
2338 expectedTurnId: turn.nativeId,
2339 input: parts,
2340 }).pipe(Effect.flatMap((value) => decode(MuseTurnStartResult, value)));
2341 if (result.turnId !== turn.nativeId)
2342 return yield* protocolError("Muse steering targeted a different turn");
2343 },
2344 (effect, args) =>
2345 effect.pipe(
2346 commands.withPermits(1),
2347 Effect.mapError(
2348 (cause) =>
2349 new ProviderAdapter.ProviderAdapterSteerRunError({
2350 driver: MUSE_PROVIDER,
2351 providerThreadId: args.providerThread.id,
2352 providerTurnId: args.providerTurnId,
2353 cause,
2354 }),
2355 ),
2356 ),
2357 ),
2358 interruptTurn: Effect.fn("MuseAdapter.interruptTurn")(
2359 function* (args) {
2360 const turn = active;
2361 // Recovering an ended turn is done unless Muse still runs work Stop cannot end.
2362 if (
2363 !turn &&
2364 args.requestRuntimeRestart === true &&
2365 observedChildren.size === 0 &&
2366 wake === undefined
2367 )
2368 return;
2369 if (
2370 !turn ||
2371 turn.providerTurn.id !== args.providerTurnId ||
2372 !validateThread(args.providerThread)
2373 )
2374 return yield* protocolError("This Muse turn is no longer active");
2375 turn.interruptRequested = true;
2376 if (turn.compact) {
2377 yield* eventPermit.withPermits(1)(
2378 Effect.gen(function* () {
2379 if (active !== turn) return;
2380 hostEpoch++;
2381 yield* Effect.tryPromise({
2382 try: () => host.close(),
2383 catch: (cause) => protocolError("Cannot stop Muse compaction", cause),
2384 }).pipe(Effect.onError(failHost));
2385 broken = true;
2386 wake = undefined;
2387 yield* finish(turn, "interrupted", undefined, "broken");
2388 yield* settleObservedChildren("interrupted");
2389 yield* updateSession("stopped");
2390 yield* Queue.end(events);
2391 }),
2392 );
2393 return;
2394 }
2395 // Muse runs a joined turn first, so Stop must end it too.
2396 for (const joined of turn.joined)
2397 yield* request("turn/interrupt", { turnId: joined }).pipe(Effect.ignore);
2398 yield* request("turn/interrupt", { turnId: turn.nativeId });
2399 yield* Deferred.await(turn.done).pipe(
2400 Effect.timeout(options.requestTimeoutMs ?? 30_000),
2401 Effect.mapError((cause) => protocolError("Muse did not confirm interruption", cause)),
2402 Effect.onError((cause) => eventPermit.withPermits(1)(failHost(cause))),
2403 );
2404 },
2405 (effect, args) =>
2406 effect.pipe(
2407 commands.withPermits(1),
2408 Effect.mapError(
2409 (cause) =>
2410 new ProviderAdapter.ProviderAdapterInterruptError({
2411 driver: MUSE_PROVIDER,
2412 providerThreadId: args.providerThread.id,
2413 providerTurnId: args.providerTurnId,
2414 cause,
2415 }),
2416 ),
2417 ),
2418 ),
2419 respondToRuntimeRequest: Effect.fn("MuseAdapter.respondToRuntimeRequest")(
2420 function* (args) {
2421 const entry = pending.get(args.requestId);
2422 if (!entry) return yield* protocolError("This Muse request is no longer pending");
2423 if (entry.native.type === "approval") yield* decideApproval(entry, args.decision);
2424 else {
2425 const questionRequest = entry.native.value;
2426 const answers = [];
2427 for (const question of questionRequest.questions) {
2428 const raw = yield* decode(responseAnswerSchema, args.answers?.[question.id]);
2429 const values = typeof raw === "string" ? [raw] : [...new Set(raw)];
2430 const selected = values.filter((value) =>
2431 question.options.some((option) => option.label === value),
2432 );
2433 const freeText = values.filter((value) => !selected.includes(value)).join("\n");
2434 if (freeText.length > 500 || (!freeText && !selected.length))
2435 return yield* protocolError(
2436 "Muse needs a nonempty answer with at most 500 custom characters",
2437 );
2438 if (
2439 (question.selection.mode === "single" && selected.length > 1) ||
2440 (selected.length > 0 &&
2441 (selected.length < (question.selection.minSelections ?? 0) ||
2442 selected.length > (question.selection.maxSelections ?? Infinity)))
2443 )
2444 return yield* protocolError("Muse question selection count is invalid");
2445 answers.push({
2446 questionId: question.id,
2447 ...(selected.length
2448 ? question.selection.mode === "single"
2449 ? { selectedLabel: selected[0]! }
2450 : { selectedLabels: selected }
2451 : {}),
2452 ...(freeText ? (selected.length ? { note: freeText } : { freeText }) : {}),
2453 });
2454 }
2455 if (args.answers) entry.response = { answers: args.answers };
2456 yield* request("userInput/answer", {
2457 userInputId: questionRequest.userInputId,
2458 answers,
2459 }).pipe(Effect.tapError(() => Effect.sync(() => delete entry.response)));
2460 }
2461 },
2462 (effect, args) =>
2463 effect.pipe(
2464 Effect.mapError(
2465 (cause) =>
2466 new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
2467 driver: MUSE_PROVIDER,
2468 requestId: args.requestId,
2469 cause,
2470 }),
2471 ),
2472 ),
2473 ),
2474 readThreadSnapshot: (args) =>
2475 (!validateThread(args.providerThread)
2476 ? protocolError("Snapshot requested for a different Muse thread")
2477 : snapshot(args.providerThread)
2478 ).pipe(
2479 commands.withPermits(1),
2480 Effect.mapError(
2481 (cause) =>
2482 new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
2483 driver: MUSE_PROVIDER,
2484 providerThreadId: args.providerThread.id,
2485 cause,
2486 }),
2487 ),
2488 ),
2489 // Muse rejects completed-turn forks with InvalidCut; use portable handoff without rewinding.
2490 rollbackThread: (args) =>
2491 Effect.fail(
2492 new ProviderAdapter.ProviderAdapterRollbackThreadError({
2493 driver: MUSE_PROVIDER,
2494 providerThreadId: args.providerThread.id,
2495 checkpointId: args.target.checkpointId,
2496 cause: "Muse Code does not support conversation rollback in T3 Code.",
2497 }),
2498 ),
2499 forkThread: (args) =>
2500 Effect.fail(
2501 new ProviderAdapter.ProviderAdapterForkThreadError({
2502 driver: MUSE_PROVIDER,
2503 providerThreadId: args.sourceProviderThread.id,
2504 cause: "Muse Code does not support native forks in T3 Code.",
2505 }),
2506 ),
2507 };
2508 return runtime;
2509 }),
2510 });
2511 });