diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index f23f7ca84d7ea..2d34aabe03ef5 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -1727,6 +1727,286 @@ describe("MuseAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(testLayer)), ); + it.effect("lists a running monitor as pending background work and stops it with the thread", () => + Effect.gen(function* () { + const fake = yield* makeFakeMuse(); + const harness = yield* makeHarness(fake); + const turn = yield* startConversation(harness, fake); + const monitor = { + itemId: "monitor-1", + kind: "toolCall", + status: "completed", + turnId: turn.nativeId, + tool: "monitor", + background: true, + }; + yield* fake.emit("item/completed", { + turnId: turn.nativeId, + item: { ...monitor, revision: 1 }, + }); + const listed = yield* harness.takeEvent( + "provider_thread.updated", + (event) => + event.providerThread.pendingBackgroundTasks?.some( + (task) => task.taskId === "monitor-1", + ) === true, + ); + assert.deepEqual(listed.providerThread.pendingBackgroundTasks, [ + { taskId: "monitor-1", kind: "monitor", description: "monitor", awaited: true }, + ]); + + // The turn ends while Muse keeps watching; the listing keeps the thread waiting. + fake.queueResponse("task/list", { + tasks: [ + { taskId: "monitor-1", kind: "tool.monitor", status: "inProgress", tool: "monitor" }, + ], + }); + yield* fake.emit("turn/completed", { turnId: turn.nativeId, terminal: "completed" }); + yield* harness.takeEvent("turn.terminal"); + assert.isTrue(yield* harness.runtime.hasPendingBackgroundWork!); + + const stop = harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: turn.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.exit); + fake.queueResponse("task/stopAll", new Error("stop rejected")); + assert.strictEqual((yield* stop)._tag, "Failure"); + assert.isTrue(yield* harness.runtime.hasPendingBackgroundWork!); + yield* fake.takeCall("task/stopAll"); + + assert.strictEqual((yield* stop)._tag, "Success"); + assert.strictEqual((yield* fake.takeCall("task/stopAll")).method, "task/stopAll"); + yield* harness.takeEvent( + "provider_thread.updated", + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, + ); + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + + it.effect("lists a backgrounded tool call as a command and a monitor found on attach", () => + Effect.gen(function* () { + const fake = yield* makeFakeMuse(); + const harness = yield* makeHarness(fake); + const turn = yield* startConversation(harness, fake); + yield* fake.emit("item/updated", { + turnId: turn.nativeId, + item: { + itemId: "shell-1", + kind: "toolCall", + revision: 2, + status: "completed", + turnId: turn.nativeId, + tool: "shell", + background: true, + }, + }); + const listed = yield* harness.takeEvent( + "provider_thread.updated", + (event) => + event.providerThread.pendingBackgroundTasks?.some((task) => task.taskId === "shell-1") === + true, + ); + assert.deepEqual(listed.providerThread.pendingBackgroundTasks, [ + { taskId: "shell-1", kind: "command", description: "shell" }, + ]); + + // A monitor started before this client attached comes from `task/list` alone. + const resumed = yield* makeFakeMuse("resumed"); + resumed.queueResponse("task/list", { + tasks: [{ taskId: "monitor-2", kind: "tool.monitor", status: "inProgress" }], + }); + const attached = yield* makeHarness(resumed); + assert.deepEqual(attached.providerThread.pendingBackgroundTasks, [ + { taskId: "monitor-2", kind: "monitor", description: "monitor", awaited: true }, + ]); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + + it.effect("drops a task list read that predates Stop", () => + Effect.gen(function* () { + const fake = yield* makeFakeMuse(); + // A notification the adapter handles only after the held refresh returns. + const drained = yield* Deferred.make(); + const harness = yield* makeHarness( + fake, + INSTANCE_ID, + undefined, + undefined, + undefined, + runtimePolicy, + { onUsageLimits: () => Deferred.succeed(drained, undefined).pipe(Effect.asVoid) }, + ); + const turn = yield* startConversation(harness, fake); + yield* fake.emit("item/completed", { + turnId: turn.nativeId, + item: { + itemId: "monitor-1", + kind: "toolCall", + status: "completed", + turnId: turn.nativeId, + tool: "monitor", + background: true, + revision: 1, + }, + }); + yield* harness.takeEvent( + "provider_thread.updated", + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, + ); + + // The refresh that follows the terminal event is held open while Stop runs. + const gate = pendingPromise>(); + fake.queueResponse("task/list", gate.promise); + yield* fake.emit("turn/completed", { turnId: turn.nativeId, terminal: "completed" }); + yield* harness.takeEvent("turn.terminal"); + yield* fake.takeCall("task/list"); + + const stopped = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: turn.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.exit); + assert.strictEqual(stopped._tag, "Success"); + yield* harness.takeEvent( + "provider_thread.updated", + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, + ); + + // The held read predates the stop, so its rows must not come back. + gate.resolve({ + tasks: [ + { taskId: "monitor-1", kind: "tool.monitor", status: "inProgress", tool: "monitor" }, + ], + }); + // The adapter handles this only after the held refresh has returned. + yield* fake.emitHostWide("usage/changed", SUBSCRIPTION_USAGE); + yield* Deferred.await(drained); + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + + it.effect("keeps a woken turn on a failed Stop so a retry can end it", () => + Effect.gen(function* () { + const fake = yield* makeFakeMuse(); + // `turn/started` sets the held wake before it offers the continuation. + const woken = yield* Deferred.make(); + const harness = yield* makeHarness( + fake, + INSTANCE_ID, + undefined, + undefined, + undefined, + runtimePolicy, + { continuationRequests: { offer: () => Deferred.succeed(woken, undefined) } }, + ); + const turn = yield* startConversation(harness, fake); + yield* fake.emit("item/completed", { + turnId: turn.nativeId, + item: { + itemId: "monitor-1", + kind: "toolCall", + status: "completed", + turnId: turn.nativeId, + tool: "monitor", + background: true, + revision: 1, + }, + }); + yield* harness.takeEvent( + "provider_thread.updated", + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, + ); + fake.queueResponse("task/list", { + tasks: [ + { taskId: "monitor-1", kind: "tool.monitor", status: "inProgress", tool: "monitor" }, + ], + }); + yield* fake.emit("turn/completed", { turnId: turn.nativeId, terminal: "completed" }); + yield* harness.takeEvent("turn.terminal"); + + // The monitor's report already woke a new Muse turn. + yield* fake.emit("turn/started", { turnId: "wake-1" }); + yield* Deferred.await(woken); + + fake.queueResponse("turn/interrupt", new Error("interrupt rejected")); + const failed = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: turn.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.exit); + assert.strictEqual(failed._tag, "Failure"); + assert.strictEqual((yield* fake.takeCall("task/stopAll")).method, "task/stopAll"); + assert.isTrue(yield* harness.runtime.hasPendingBackgroundWork!); + + const retried = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: turn.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.exit); + assert.strictEqual(retried._tag, "Success"); + assert.strictEqual((yield* fake.takeCall("turn/interrupt")).params.turnId, "wake-1"); + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + + it.effect("clears a stopped monitor when the turn ends before Stop's reply", () => + Effect.gen(function* () { + const fake = yield* makeFakeMuse(); + const harness = yield* makeHarness(fake); + const turn = yield* startConversation(harness, fake); + yield* fake.emit("item/completed", { + turnId: turn.nativeId, + item: { + itemId: "monitor-1", + kind: "toolCall", + status: "completed", + turnId: turn.nativeId, + tool: "monitor", + background: true, + revision: 1, + }, + }); + yield* harness.takeEvent( + "provider_thread.updated", + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, + ); + + // Muse reports the turn as ended before it answers the interrupt. + const gate = pendingPromise>(); + fake.queueResponse("turn/interrupt", gate.promise); + const stopping = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: turn.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.exit, Effect.forkScoped); + yield* fake.takeCall("turn/interrupt"); + yield* fake.emit("turn/completed", { turnId: turn.nativeId, terminal: "cancelled" }); + yield* harness.takeEvent("turn.terminal"); + gate.resolve({}); + + const stopped = yield* Fiber.join(stopping); + assert.strictEqual(stopped._tag, "Success"); + // The clear happens inside Stop, so it is settled as soon as the call returns. + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!); + yield* harness.takeEvent( + "provider_thread.updated", + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, + ); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + it.effect("ends a compaction whose item names the held wake as its run", () => Effect.gen(function* () { const fake = yield* makeFakeMuse(); diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 0b5835e0bad12..722bd5a0c66ff 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -6,6 +6,7 @@ import { type OrchestrationV2AppThread, type OrchestrationV2ConversationMessage, type OrchestrationV2ExecutionNode, + type OrchestrationV2PendingBackgroundTask, type OrchestrationV2ProviderCapabilities, type OrchestrationV2ProviderRetry, type OrchestrationV2ProviderSession, @@ -33,6 +34,7 @@ import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; @@ -52,6 +54,7 @@ import { MuseItemEvent, MuseSessionResult, MuseSubscriptionUsage, + MuseTaskList, MuseTokenUsageEvent, MuseTodoList, MuseRetryScheduled, @@ -275,6 +278,33 @@ const nativeRef = (nativeId: string) => ({ /** The roster lists a child under its turn item's native id, so readers can pair the two. */ const backgroundTaskId = (item: MuseItem) => item.kind === "subagent" ? item.childSessionId || item.subagentId || item.itemId : item.itemId; + +/** One live row of `task/list`, kept until a later listing or Stop clears it. */ +interface LiveBackgroundTask { + readonly kind: "monitor" | "command"; + readonly description?: string; + readonly awaited?: true; +} +const isMonitorTask = (task: { readonly kind: string; readonly tool?: string | undefined }) => + task.tool?.toLowerCase() === "monitor" || task.kind.toLowerCase().includes("monitor"); +const liveBackgroundTask = ( + task: { + readonly kind: string; + readonly tool?: string | undefined; + }, + label?: string, +): LiveBackgroundTask => { + const monitor = isMonitorTask(task); + // Registry-only rows carry a `tool.` kind instead of a tool name. + const description = + label ?? task.tool ?? (monitor ? "monitor" : task.kind.replace(/^tool\./, "")); + return { + kind: monitor ? "monitor" : "command", + ...(description ? { description } : {}), + // A monitor wakes the session when it reports, so the thread waits on it like a subagent. + ...(monitor ? { awaited: true as const } : {}), + }; +}; const recordSchema = Schema.Record(Schema.String, Schema.Unknown); const INFORMATIONAL_NOTIFICATIONS = new Set([ "session/contextUsage", @@ -368,6 +398,9 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( const pending = new Map(); const seenTerminals = new Set(); const observedChildren = new Map(); + const liveTasks = new Map(); + // Stop invalidates a `task/list` read already in flight; its rows predate the stop. + let taskListGeneration = 0; const childrenByItemId = new Map(); const agentTitles = new Map(); const finishedBackground: Array = []; @@ -752,20 +785,45 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( } }); const syncBackground = Effect.fnUntraced(function* () { - yield* updateThread({ - pendingBackgroundTasks: [...observedChildren].flatMap(([itemId, owner]) => { - const item = owner.items.get(itemId); - const description = item?.objective ?? item?.entryId ?? item?.fallbackText; - return [ - { - taskId: item ? backgroundTaskId(item) : itemId, - kind: - item?.kind === "subagent" ? ("subagent" as const) : ("background_task" as const), - ...(description ? { description } : {}), - }, - ]; - }), - }); + const tasks: OrchestrationV2PendingBackgroundTask[] = []; + const listed = new Set(); + for (const [itemId, owner] of observedChildren) { + const item = owner.items.get(itemId); + const taskId = item ? backgroundTaskId(item) : itemId; + if (listed.has(taskId)) continue; + listed.add(taskId); + const description = item?.objective ?? item?.entryId ?? item?.fallbackText; + tasks.push({ + taskId, + kind: item?.kind === "subagent" ? "subagent" : "background_task", + ...(description ? { description } : {}), + }); + } + // A monitor has no running turn item, so `task/list` is the only place it shows up. + for (const [taskId, task] of liveTasks) { + if (listed.has(taskId)) continue; + listed.add(taskId); + tasks.push({ taskId, ...task }); + } + yield* updateThread({ pendingBackgroundTasks: tasks }); + }); + // The item stream says a tool was backgrounded; only `task/list` says whether it still runs. + const refreshBackgroundTasks = Effect.fnUntraced(function* () { + const generation = taskListGeneration; + const listed = yield* request("task/list", {}, false).pipe( + Effect.flatMap((value) => decode(MuseTaskList, value)), + // Never hold the event stream long on a host that will not answer. + Effect.timeoutOption(5_000), + Effect.option, + ); + // Stop cleared the work while this read was in flight; the rows are already stale. + if (generation !== taskListGeneration) return; + // A host that cannot list tasks keeps what the items told us. + if (Option.isNone(listed) || Option.isNone(listed.value)) return; + liveTasks.clear(); + for (const task of listed.value.value.tasks) + if (task.status === "inProgress") liveTasks.set(task.taskId, liveBackgroundTask(task)); + yield* syncBackground(); }); const publishItem = Effect.fnUntraced(function* ( turn: ActiveTurn, @@ -806,6 +864,17 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( if (wasRunning !== running || (running && !listed)) yield* syncBackground(); } const streaming = status === "running"; + // A backgrounded tool call completes as a call but keeps running as work. + if (item.kind === "toolCall" && item.background === true) { + const task = liveBackgroundTask( + { kind: item.kind, tool: item.tool }, + item.tool ?? item.entryId, + ); + if (liveTasks.get(item.itemId)?.description !== task.description) { + liveTasks.set(item.itemId, task); + yield* syncBackground(); + } + } const base = { ...baseItem(turn, item.itemId, time), status, @@ -984,6 +1053,12 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( if (item) yield* publishItem(owner, item, status); } observedChildren.clear(); + // The process owns its background work, so stopping or losing the turn ends it too. + if (liveTasks.size > 0) { + // Discard a `task/list` read that started before these rows were dropped. + taskListGeneration++; + liveTasks.clear(); + } if (thread?.pendingBackgroundTasks?.length) yield* syncBackground(); for (const entry of pending.values()) yield* resolvePending(entry, "cancelled"); }); @@ -1575,6 +1650,9 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( "reusable", result.error?.quota, ); + // Background work outlives the turn that started it; re-read what Muse still runs. + // Stop already cleared the listing, and a read now can predate `task/stopAll`. + if (status !== "interrupted") yield* refreshBackgroundTasks(); break; } case "approval/requested": @@ -2022,6 +2100,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( driver: MUSE_PROVIDER, providerThread: thread, }); + // A monitor started before this client attached still keeps the thread waiting. + yield* refreshBackgroundTasks(); return thread; }).pipe( Effect.onError((cause) => @@ -2279,9 +2359,9 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( providerSession: session, events: Stream.fromQueue(events), backgroundTasksEndWithProcess: true, - // A running workflow or a held Muse turn keeps the host: idle release must wait. + // A running workflow, a live monitor, or a held Muse turn keeps the host: idle release must wait. hasPendingBackgroundWork: Effect.sync( - () => observedChildren.size > 0 || wake !== undefined, + () => observedChildren.size > 0 || liveTasks.size > 0 || wake !== undefined, ), ensureThread: (args) => register(args).pipe( @@ -2363,14 +2443,24 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( interruptTurn: Effect.fn("MuseAdapter.interruptTurn")( function* (args) { const turn = active; - // Recovering an ended turn is done unless Muse still runs work Stop cannot end. - if ( - !turn && - args.requestRuntimeRestart === true && - observedChildren.size === 0 && - wake === undefined - ) - return; + // Recovering an ended turn is done unless Muse still runs work Stop can end. + if (!turn && args.requestRuntimeRestart === true) { + if (liveTasks.size === 0) { + // A child or a held wake is not this call's to end; an idle turn is done. + if (observedChildren.size === 0 && wake === undefined) return; + } else { + // A monitor outlives its turn, so Stop must reach Muse's own task registry. + // Without a live turn this is the only stop attempt, so a failed stop surfaces + // and keeps the listing for the caller to retry. + yield* request("task/stopAll", {}); + // A monitor that already woke the session left a turn this call must end too. + // Keep the wake and the listing if that fails, so a retry can finish the job. + if (wake) yield* request("turn/interrupt", { turnId: wake.nativeId }); + yield* settleObservedChildren("interrupted"); + wake = undefined; + return; + } + } if ( !turn || turn.providerTurn.id !== args.providerTurnId || @@ -2401,6 +2491,18 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( for (const joined of turn.joined) yield* request("turn/interrupt", { turnId: joined }).pipe(Effect.ignore); yield* request("turn/interrupt", { turnId: turn.nativeId }); + // Monitors and backgrounded tools are Muse-side work; the turn ending does not stop them. + // Keep the rows if the stop fails: those tasks can still be running. + const stopped = yield* request("task/stopAll", {}).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + if (stopped) { + // A `task/list` read started before this stop must not put the rows back. + taskListGeneration++; + liveTasks.clear(); + yield* syncBackground(); + } yield* Deferred.await(turn.done).pipe( Effect.timeout(options.requestTimeoutMs ?? 30_000), Effect.mapError((cause) => protocolError("Muse did not confirm interruption", cause)), diff --git a/packages/provider-muse/src/server/protocol.ts b/packages/provider-muse/src/server/protocol.ts index 87c9c922ef592..4705761165625 100644 --- a/packages/provider-muse/src/server/protocol.ts +++ b/packages/provider-muse/src/server/protocol.ts @@ -14,6 +14,8 @@ const MuseUsage = Schema.Struct({ export const MuseItem = Schema.Struct({ entryId: Schema.optional(Schema.String), + /** `toolCall`: `true` once Muse durably backgrounded the task; the work outlives the call. */ + background: Schema.optional(Schema.Boolean), children: Schema.optional( Schema.Array( Schema.Struct({ @@ -161,6 +163,17 @@ export const MuseTurnCompleted = Schema.Struct({ ), usage: Schema.optional(MuseUsage), }); +/** `task/list`: one row per live background workload, monitors and backgrounded tool calls alike. */ +export const MuseTaskList = Schema.Struct({ + tasks: Schema.Array( + Schema.Struct({ + taskId: NonEmptyString, + kind: Schema.String, + status: Schema.String, + tool: Schema.optional(Schema.String), + }), + ), +}); /** The latest instant a JavaScript Date holds; formatting a later one throws. */ export const LATEST_DATE_MS = 8.64e15; const DateMillis = Schema.Finite.check(