From 417b3c47c5e52ff9b6380449bae925d8f6ca715b Mon Sep 17 00:00:00 2001 From: Kameron Smith Date: Tue, 24 Nov 2026 11:46:41 -0500 Subject: [PATCH 1/4] fix(ci): restore the release commit and push hook baseline On release/native-0.1.10 the pre-commit hook fails on eight unused exports and the pre-push check fails on a scenario typecheck error and a stale agent context budget, so no code change can land without bypassing the hooks. Seven unused exports are used only inside their own module and lose their export. The client setThreadDelegationNudge wrapper has no caller and goes; the server command and its MCP tool stay. The upstream ACP refresh scenario imports rpcClient from scenarios/t3.ts, so the fork's identical helper moves there as upstream has it. The MCP tool list budget takes the measured size after the event subscription and delegation nudge tools landed. Model: claude-opus-5-5 Task: CLO-1066 Agent: claude-code Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/McpHttpServer.ts | 2 +- .../src/orchestration-v2/contextBoundary.ts | 2 +- .../src/orchestration-v2/eventSubscription.ts | 13 +++--- .../src/provider/agentContextBudget.json | 2 +- .../client-runtime/src/operations/commands.ts | 16 -------- .../mention-finds-older-linked-thread.e2e.ts | 41 +------------------ scripts/scenarios/t3.ts | 34 ++++++++++++++- 7 files changed, 43 insertions(+), 67 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 9cf2d604dbc8d..ce2c87d5d12bc 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -1350,7 +1350,7 @@ export const layerPullRequestsToolkit = toolkitRegistration( PullRequestsHandlers.layer, ).pipe(Layer.provide(PullRequestWatchService.layer)); -export const layerEventsToolkit = toolkitRegistration(EventsToolkit, EventsHandlers.layer).pipe( +const layerEventsToolkit = toolkitRegistration(EventsToolkit, EventsHandlers.layer).pipe( Layer.provide(PullRequestWatchService.layer), ); diff --git a/apps/server/src/orchestration-v2/contextBoundary.ts b/apps/server/src/orchestration-v2/contextBoundary.ts index 1d9ca8d552fa2..ff918a0126554 100644 --- a/apps/server/src/orchestration-v2/contextBoundary.ts +++ b/apps/server/src/orchestration-v2/contextBoundary.ts @@ -3,7 +3,7 @@ import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3too import { cancelledBeforeStart } from "./RestartBackgroundNote.ts"; /** A fresh-session schedule run starts a side conversation; the thread's own one continues past it. */ -export function isScheduledFreshRun( +function isScheduledFreshRun( run: Pick, turnItems: OrchestrationV2ThreadProjection["turnItems"], ): boolean { diff --git a/apps/server/src/orchestration-v2/eventSubscription.ts b/apps/server/src/orchestration-v2/eventSubscription.ts index fcb871fe5643d..be2ba0a0cc4f9 100644 --- a/apps/server/src/orchestration-v2/eventSubscription.ts +++ b/apps/server/src/orchestration-v2/eventSubscription.ts @@ -40,23 +40,20 @@ export const emptyCursor = (): SubscriptionCursor => ({ deliveredSignatures: {}, }); -export function canonicalAuthor(login: string): string { +function canonicalAuthor(login: string): string { return login .trim() .toLowerCase() .replace(/\[bot\]$/i, ""); } -export function authorIgnored( - login: string | null | undefined, - ignore: readonly string[], -): boolean { +function authorIgnored(login: string | null | undefined, ignore: readonly string[]): boolean { if (login == null || login.trim() === "") return false; const key = canonicalAuthor(login); return ignore.some((entry) => canonicalAuthor(entry) === key); } -export function normalizePullRequestUrl(raw: string): string { +function normalizePullRequestUrl(raw: string): string { const url = new URL(raw); url.hash = ""; url.search = ""; @@ -95,7 +92,7 @@ export interface DeliveryInput { readonly maxWakesPerHour?: number | null | undefined; } -export function normalizeDelivery( +function normalizeDelivery( input: DeliveryInput | undefined, ): | { readonly ok: true; readonly delivery: EventDeliveryPolicy } @@ -159,7 +156,7 @@ function validateQuietHours(hours: QuietHours): string | null { } /** Minutes from midnight in the zone. Throws when the zone is invalid. */ -export function minutesInZone(nowMs: number, timeZone: string): number { +function minutesInZone(nowMs: number, timeZone: string): number { const parts = new Intl.DateTimeFormat("en-US", { timeZone, hour: "2-digit", diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index a071e682881e3..385996c985c17 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5930, "codexAdditionalContextBytes": 7324, - "mcpToolListJsonBytes": 61564 + "mcpToolListJsonBytes": 61917 } diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index addd7e3752bda..7bbd46edef0e2 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -630,22 +630,6 @@ export const setThreadStanding = Effect.fn("EnvironmentCommands.setThreadStandin }); }); -export interface SetThreadDelegationNudgeInput extends ThreadCommandInput { - readonly enabled: boolean; - readonly thresholds?: ReadonlyArray; -} -export const setThreadDelegationNudge = Effect.fn("EnvironmentCommands.setThreadDelegationNudge")( - function* (input: SetThreadDelegationNudgeInput) { - return yield* dispatch({ - type: "thread.delegation-nudge.set", - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - enabled: input.enabled, - ...(input.thresholds === undefined ? {} : { thresholds: [...input.thresholds] }), - }); - }, -); - export interface SetThreadAutoSettleInput extends ThreadCommandInput { readonly enabled: boolean; } diff --git a/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts b/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts index 064f04fb92924..e6e59dd00b720 100644 --- a/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts +++ b/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts @@ -1,54 +1,17 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import * as NodeWS from "@effect/platform-node/NodeWS"; -import { - CommandId, - ORCHESTRATION_PROTOCOL_VERSION, - ThreadId, - WsRpcGroup, -} from "@t3tools/contracts"; +import { CommandId, ThreadId } from "@t3tools/contracts"; import { expect } from "e2e"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; -import { RpcClient, RpcSerialization } from "effect/rpc"; -import { Socket } from "effect/socket"; import { T3_HOME } from "../e2e.config.ts"; import { SECOND_HOME, startSecondServer } from "./second-server.ts"; -import { makeState, runPromise, test, WEB } from "./t3.ts"; +import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; // A shell keeps an environment's 25 newest settled threads; older ones come from search. const NEWER_SETTLED = 25; -/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */ -const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) { - const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]); - const { ticket } = yield* HttpClient.execute( - HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( - HttpClientRequest.bearerToken(issued.stdout.trim()), - ), - ).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), - Effect.provide(FetchHttpClient.layer), - ); - // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns. - const protocol = yield* Layer.build( - RpcClient.layerProtocolSocket().pipe( - Layer.provide( - Socket.layerWebSocket( - `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, - ), - ), - Layer.provide(RpcSerialization.layerJson), - Layer.provide(NodeWS.layerWebSocketConstructor), - ), - ); - return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); -}); - const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4()); const decodePairing = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), diff --git a/scripts/scenarios/t3.ts b/scripts/scenarios/t3.ts index 113916cf94081..c3800c74ad321 100644 --- a/scripts/scenarios/t3.ts +++ b/scripts/scenarios/t3.ts @@ -1,14 +1,19 @@ // `test` for web scenarios: e2e's web test plus `t3`, which seeds state and opens the signed-in // app. `t3-mobile.ts` is the same for the iOS app. import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeWS from "@effect/platform-node/NodeWS"; import { test as base } from "@e2e-dev/web"; +import { ORCHESTRATION_PROTOCOL_VERSION, WsRpcGroup } from "@t3tools/contracts"; import { expect } from "e2e"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { RpcClient, RpcSerialization } from "effect/rpc"; +import { Socket } from "effect/socket"; import { APP_DIR, T3_HOME } from "../e2e.config.ts"; import { run } from "./shell.ts"; @@ -149,6 +154,33 @@ const environmentId = (baseUrl: string) => Effect.provide(FetchHttpClient.layer), ); +/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */ +export const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) { + const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]); + const { ticket } = yield* HttpClient.execute( + HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), + Effect.provide(FetchHttpClient.layer), + ); + // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns. + const protocol = yield* Layer.build( + RpcClient.layerProtocolSocket().pipe( + Layer.provide( + Socket.layerWebSocket( + `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, + ), + ), + Layer.provide(RpcSerialization.layerJson), + Layer.provide(NodeWS.layerWebSocketConstructor), + ), + ); + return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); +}); + export const test = base.extend<{ t3: T3 }>({ t3: async ({ app, browser }, use) => { const { state, cleanup } = makeState(T3_HOME); From 7941765bfe7733d502567e421a4e230b60fd22fc Mon Sep 17 00:00:00 2001 From: Kameron Smith Date: Tue, 24 Nov 2026 12:19:11 -0500 Subject: [PATCH 2/4] fix(test): keep replay fixtures out of the hook's repository Git exports GIT_DIR to hooks. Under pre-push, the replay workspace fixture inherited it, so its git init, config, add and commit ran against the pushing worktree: it committed "initial" onto the branch being pushed and wrote the test identity into the shared repository config. Unset the inherited repository selectors, as the server's VcsProcess already does for its own git calls. Model: claude-opus-5-5 Task: CLO-1066 Agent: claude-code Co-Authored-By: Claude Opus 5.5 --- packages/provider-testing/src/replayWorkspace.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/provider-testing/src/replayWorkspace.ts b/packages/provider-testing/src/replayWorkspace.ts index 4216ebaedc53f..adf69bcb50aae 100644 --- a/packages/provider-testing/src/replayWorkspace.ts +++ b/packages/provider-testing/src/replayWorkspace.ts @@ -19,6 +19,15 @@ class ReplayFixtureGitCommandError extends Schema.TaggedError, @@ -29,7 +38,9 @@ function runGit( > { return Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const exitCode = yield* spawner.exitCode(ChildProcess.make("git", args, { cwd })); + const exitCode = yield* spawner.exitCode( + ChildProcess.make("git", args, { cwd, env: INHERITED_REPOSITORY_ENV, extendEnv: true }), + ); if (Number(exitCode) !== 0) { return yield* new ReplayFixtureGitCommandError({ command: `git ${args.join(" ")}`, From 016b15eaaf9c9cbd68fede1ac3bdf30eabe15b4d Mon Sep 17 00:00:00 2001 From: Kameron Smith Date: Tue, 24 Nov 2026 12:05:19 -0500 Subject: [PATCH 3/4] feat(server): wake the watcher when an unsettled top-level thread fails A failed top-level thread with no launching thread, including one a person created, told nobody, so a 15-minute fleet watchdog had to find it. A new thread-failed event starts a watcher turn through the existing model alert delivery path. It fires once per failed run, only for an unsettled, unarchived, top-level thread that is not a delegated or side-chat thread and has no live run. Delivery uses next_turn so an idle watcher wakes, keys on the run so a replay is not a second wake, waits five minutes per thread after a delivered wake, and never wakes the watcher about itself. Lane events keep going to the launching thread. Launch and delegation also refuse a provider that is not ready, has discovered no models or is signed out, before any thread or run is created, using one readiness check shared with placement and capabilities. Model: claude-opus-5-5 Task: CLO-1066 Agent: claude-code Co-Authored-By: Claude Opus 5.5 --- .../src/mcp/OrchestratorMcpService.test.ts | 200 ++++++++++-------- apps/server/src/mcp/OrchestratorMcpService.ts | 42 ++-- .../src/mcp/toolkits/project/handlers.test.ts | 54 ++++- .../src/mcp/toolkits/project/handlers.ts | 26 ++- .../ModelAlertReactor.test.ts | 42 ++++ .../src/orchestration-v2/ModelAlertReactor.ts | 112 +++++++--- .../ThreadEventAlerts.test.ts | 26 ++- .../src/orchestration-v2/ThreadEventAlerts.ts | 36 +++- apps/server/src/peer/placementEvidence.ts | 6 +- apps/server/src/provider/servedModel.ts | 33 ++- docs/operations/watcher-thread.md | 7 +- packages/contracts/src/settings.ts | 5 +- 12 files changed, 415 insertions(+), 174 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index f1fea0ef040f7..ecac81328b3ab 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -2011,6 +2011,19 @@ describe("OrchestratorMcpService provider resolution", () => { assert.deepEqual(entry!.constraints, []); } + providers = providers.map((provider) => + provider.instanceId === antigravityInstanceId + ? { ...provider, models: [], auth: { status: "unauthenticated" } } + : provider, + ); + const signedOut = (yield* service.capabilities(scope)).providers.find( + (provider) => provider.providerInstanceId === antigravityInstanceId, + ); + assert.isFalse(signedOut?.canRunChildTask); + assert.isFalse(signedOut?.canRunCrossProviderChildTask); + assert.include(signedOut?.constraints ?? [], "No models available."); + assert.include(signedOut?.constraints ?? [], "Provider is not authenticated."); + const disabled = byId.get(disabledAntigravityInstanceId); assert.isDefined(disabled); assert.isFalse(disabled!.canRunChildTask); @@ -2239,94 +2252,111 @@ describe("OrchestratorMcpService provider resolution", () => { ); }); - it.effect.each(["already advertised", "newly advertised", "still unavailable"] as const)( - "rechecks a delegated model that is %s", - (availability) => - Effect.gen(function* () { - const museInstanceId = ProviderInstanceId.make("muse"); - const model = "muse-wonder-1.0"; - const provider = (advertisedModel: string) => - providerSnapshot({ + it.effect.each([ + "already advertised", + "newly advertised", + "still unavailable", + "empty catalog", + "unauthenticated", + ] as const)("rechecks a delegated model that is %s", (availability) => + Effect.gen(function* () { + const museInstanceId = ProviderInstanceId.make("muse"); + const model = "muse-wonder-1.0"; + const provider = (advertisedModel: string): ServerProvider => { + const snapshot = providerSnapshot({ + instanceId: museInstanceId, + driver: ProviderDriverKind.make("muse"), + model: advertisedModel, + }); + if (availability === "empty catalog") return { ...snapshot, models: [] }; + if (availability === "unauthenticated") + return { ...snapshot, auth: { status: "unauthenticated" } }; + return snapshot; + }; + const commands: Array = []; + const refreshedInstances: Array = []; + const task = { + id: taskId, + threadId: parentThreadId, + origin: "app_owned", + childThreadId, + providerInstanceId: museInstanceId, + model, + status: "running", + result: null, + }; + const dependencies = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + hasReceipt: () => Effect.succeed(false), + getThreadRecords: (threadId) => + Effect.succeed( + threadId === parentThreadId + ? parentProjection(commands.length > 0 ? [task] : []) + : childProjection, + ), + dispatch: (command) => + Effect.sync(() => { + commands.push(command); + return { + sequence: 1, + storedEvents: [{ event: { type: "subagent.updated", payload: task } }], + } as never; + }), + }), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([ + provider(availability === "already advertised" ? model : "muse-spark-1.3"), + ]), + refreshInstance: (instanceId) => + Effect.sync(() => { + refreshedInstances.push(instanceId); + return [provider(availability === "still unavailable" ? "muse-spark-1.3" : model)]; + }), + }), + adapterRegistryLayer([museInstanceId]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const delegation = service.delegateTask(scope, { + task: "Review the change.", + target: { providerInstanceId: museInstanceId, model }, + mode: "async", + clientRequestId: availability, + }); + if (availability === "empty catalog" || availability === "unauthenticated") { + const error = yield* delegation.pipe(Effect.flip); + assert.equal(error.code, "provider_unavailable"); + assert.include( + error.message, + availability === "empty catalog" ? "No models available" : "not authenticated", + ); + assert.deepEqual(commands, []); + } else if (availability === "still unavailable") { + const error = yield* delegation.pipe(Effect.flip); + assert.equal(error.code, "model_unavailable"); + assert.deepEqual(commands, []); + } else { + const result = yield* delegation; + assert.equal(result.model, model); + assert.equal(commands.length, 1); + assert.deepEqual((commands[0] as { modelSelection: unknown }).modelSelection, { instanceId: museInstanceId, - driver: ProviderDriverKind.make("muse"), - model: advertisedModel, + model, }); - const commands: Array = []; - const refreshedInstances: Array = []; - const task = { - id: taskId, - threadId: parentThreadId, - origin: "app_owned", - childThreadId, - providerInstanceId: museInstanceId, - model, - status: "running", - result: null, - }; - const dependencies = Layer.mergeAll( - NodeServices.layer, - NodeCrypto.layer, - Layer.mock(ThreadManagementService.ThreadManagementService)({ - hasReceipt: () => Effect.succeed(false), - getThreadRecords: (threadId) => - Effect.succeed( - threadId === parentThreadId - ? parentProjection(commands.length > 0 ? [task] : []) - : childProjection, - ), - dispatch: (command) => - Effect.sync(() => { - commands.push(command); - return { - sequence: 1, - storedEvents: [{ event: { type: "subagent.updated", payload: task } }], - } as never; - }), - }), - ServerSettings.layerTest(), - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([ - provider(availability === "already advertised" ? model : "muse-spark-1.3"), - ]), - refreshInstance: (instanceId) => - Effect.sync(() => { - refreshedInstances.push(instanceId); - return [provider(availability === "still unavailable" ? "muse-spark-1.3" : model)]; - }), - }), - adapterRegistryLayer([museInstanceId]), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + } + assert.deepEqual( + refreshedInstances, + availability === "already advertised" ? [] : [museInstanceId], ); - yield* Effect.gen(function* () { - const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const delegation = service.delegateTask(scope, { - task: "Review the change.", - target: { providerInstanceId: museInstanceId, model }, - mode: "async", - clientRequestId: availability, - }); - if (availability === "still unavailable") { - const error = yield* delegation.pipe(Effect.flip); - assert.equal(error.code, "model_unavailable"); - assert.deepEqual(commands, []); - } else { - const result = yield* delegation; - assert.equal(result.model, model); - assert.equal(commands.length, 1); - assert.deepEqual((commands[0] as { modelSelection: unknown }).modelSelection, { - instanceId: museInstanceId, - model, - }); - } - assert.deepEqual( - refreshedInstances, - availability === "already advertised" ? [] : [museInstanceId], - ); - }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); - }), + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); + }), ); it.effect("rejects delegation to a provider without a registered adapter", () => diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index d2e27a3ba8784..8b043423150c7 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -8,7 +8,6 @@ import { CommandId, EnvironmentId, type RunId, - isProviderAvailable, MessageId, type ModelSelection, NodeId, @@ -135,7 +134,11 @@ import { isSnoozed } from "../orchestration-v2/ThreadSettlementService.ts"; import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; -import { findServedModel, unservedModelMessage } from "../provider/servedModel.ts"; +import { + findServedModel, + providerReadinessConstraints, + unservedModelMessage, +} from "../provider/servedModel.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; import * as ServerSettings from "../serverSettings.ts"; import { @@ -403,9 +406,8 @@ function antigravitySuffixedModel(provider: ServerProvider, model: string) { const withV = (version: string) => (version.startsWith("v") ? version : `v${version}`); -/** A provider that lists no models accepts any slug. */ export const requireAdvertisedModel = (provider: ServerProvider, model: string) => { - if (provider.models.length === 0 || advertisedModel(provider, model) !== undefined) { + if (advertisedModel(provider, model) !== undefined) { return Effect.void; } const updateRequired = provider.updateRequiredModels?.find( @@ -434,31 +436,11 @@ function capabilityModelOption(descriptor: ProviderOptionDescriptor): Orchestrat }; } -function providerConstraints( - provider: ServerProvider | undefined, - supportsOrchestrationV2: boolean, -): ReadonlyArray { - const constraints: Array = []; - if (!supportsOrchestrationV2) { - constraints.push("No V2 provider adapter is registered."); - } - if (provider === undefined) return constraints; - if (!isProviderAvailable(provider)) { - constraints.push(provider.unavailableReason ?? "Provider driver is unavailable."); - } - if (!provider.enabled) { - constraints.push("Provider instance is disabled."); - // Disabled snapshots contain placeholders for installation, health, and auth. - return constraints; - } - if (!provider.installed) constraints.push("Provider executable is not installed."); - if (provider.status === "error" || provider.status === "disabled") { - constraints.push(provider.message ?? `Provider status is ${provider.status}.`); - } - if (provider.auth.status === "unauthenticated") { - constraints.push("Provider is not authenticated."); - } - return constraints; +function providerConstraints(provider: ServerProvider, supportsOrchestrationV2: boolean) { + const readiness = providerReadinessConstraints(provider); + return supportsOrchestrationV2 + ? readiness + : ["No V2 provider adapter is registered.", ...readiness]; } /** t3_thread_launch keeps a selection as given, so it can hold options its model does not have. */ @@ -1677,7 +1659,7 @@ const make = Effect.gen(function* () { `Provider ${instanceId} has no model available for inheritance.`, ); } - if (requestedModel !== undefined) yield* requireAdvertisedModel(provider, model); + yield* requireAdvertisedModel(provider, model); const advertised = advertisedModel(provider, model); const descriptors = advertised?.capabilities?.optionDescriptors; const requestedOptions = withLegacyUltracodeEffort(descriptors, input.target?.options); diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index e07f0610a4212..98cd2d8d44e88 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -73,7 +73,30 @@ const clientLaunchHarness = (input: { }; const layerDependencies = Layer.mergeAll( Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed(input.providers ?? []), + getProviders: Effect.succeed( + input.providers ?? [ + { + instanceId: (input.overrideModel ?? modelSelection).instanceId, + driver: ProviderDriverKind.make((input.overrideModel ?? modelSelection).instanceId), + enabled: true, + installed: true, + status: "ready", + version: null, + auth: { status: "authenticated" }, + checkedAt: "2026-01-01T00:00:00Z", + models: [ + { + slug: (input.overrideModel ?? modelSelection).model, + name: "Default", + capabilities: null, + isCustom: false, + }, + ], + slashCommands: [], + skills: [], + }, + ], + ), }), ServerSettings.layerTest({ fallbackModelSelection: input.fallbackModel ?? null, @@ -309,7 +332,7 @@ it.effect("a launch steps an inherited mode down to the provider's, and refuses version: null, auth: { status: "authenticated" }, checkedAt: "2026-01-01T00:00:00Z", - models: [], + models: [{ slug: "pi-model", name: "Pi", capabilities: null, isCustom: false }], slashCommands: [], skills: [], supportedRuntimeModes: ["approval-required", "auto-accept-edits", "full-access"], @@ -408,6 +431,24 @@ it.effect("a launch with a model its provider does not advertise creates no thre ), }); } + providers.push( + { ...providers[0]!, instanceId: ProviderInstanceId.make("empty"), models: [] }, + { + ...providers[0]!, + instanceId: ProviderInstanceId.make("signed-out"), + auth: { status: "unauthenticated" }, + }, + ); + for (const [instance, reason] of [ + ["missing", "not registered"], + ["empty", "No models available"], + ["signed-out", "not authenticated"], + ] as const) { + expect(yield* launchWith(instance, "claude-opus")).toMatchObject({ + code: "provider_unavailable", + message: expect.stringContaining(reason), + }); + } expect(launched).toHaveLength(0); expect(yield* launchWith("claudeAgent", "Opus")).toMatchObject({ @@ -836,7 +877,14 @@ it.effect("a client launches with the fallback for an exhausted default", () => version: null, auth: { status: "authenticated" }, checkedAt: "2026-01-01T00:00:00Z", - models: [], + models: [ + { + slug: driver === "codex" ? fallbackModel.model : "claude-opus", + name: "Default", + capabilities: null, + isCustom: false, + }, + ], slashCommands: [], skills: [], ...(driver === "claudeAgent" diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 45fffd3ad2c96..1b788058a6a80 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -32,6 +32,7 @@ import { mutateProjectWithClone } from "../../../project/ProjectMutation.ts"; import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts"; import * as Repositories from "../../../sourceControl/SourceControlRepositoryService.ts"; import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts"; +import { providerReadinessConstraints } from "../../../provider/servedModel.ts"; import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts"; import * as ServerSettings from "../../../serverSettings.ts"; import * as DateTime from "effect/DateTime"; @@ -400,13 +401,6 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { } if (project !== undefined && input.workspaceStrategy?.type === "existing_worktree") yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath); - if (!replaying && input.modelSelection !== undefined) { - const { instanceId, model } = input.modelSelection; - const providers = yield* (yield* ProviderRegistry.ProviderRegistry).getProviders; - const provider = providers.find((candidate) => candidate.instanceId === instanceId); - if (provider !== undefined) - yield* OrchestrationMcp.requireAdvertisedModel(provider, model); - } // Reject unresolved base refs and blocked branch names before accepting a launch; worktree provisioning happens later. if (!replaying && strategy?.type === "worktree") yield* ThreadLaunch.ThreadLaunchService.pipe( @@ -447,11 +441,23 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { let startedRuntimeMode = defaultRuntimeMode; if (!replaying) { const providers = yield* (yield* ProviderRegistry.ProviderRegistry).getProviders; + const provider = providers.find( + (candidate) => candidate.instanceId === modelSelection.instanceId, + ); + const constraints = + provider === undefined + ? ["Provider instance is not registered."] + : providerReadinessConstraints(provider); + if (provider === undefined || constraints.length > 0) { + return yield* new OrchestratorMcpFailure({ + code: "provider_unavailable", + message: `Provider ${modelSelection.instanceId} cannot launch a thread: ${constraints.join(" ")}`, + }); + } + yield* OrchestrationMcp.requireAdvertisedModel(provider, modelSelection.model); startedRuntimeMode = yield* resolveRuntimeMode(startedRuntimeMode, input.runtimeMode, { modelSelection, - supportedRuntimeModes: providers.find( - (provider) => provider.instanceId === modelSelection.instanceId, - )?.supportedRuntimeModes, + supportedRuntimeModes: provider.supportedRuntimeModes, }); } const result = yield* ThreadMessageIntake.launchThread({ diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts index 18eeccd3b61fb..77a60fc6d4569 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts @@ -11,10 +11,12 @@ import { BUSY_WATCHER_RECHECK_MS, busyWatcherHold, deliverAlertToWatcher, + failureWakeHold, INCIDENT_GROUP_INTERVAL_MS, INCIDENT_GROUP_WAIT_MS, EMPTY_MODEL_ALERT_STATE, type ModelAlert, + type ModelAlertState, modelAlertDestinations, modelAlertFor, overdueResumes, @@ -199,6 +201,39 @@ const finding = (kind: ThreadEventKind, signature: string): ThreadFinding => ({ detail: `${kind} detail`, }); +it("rate-limits subsequent failure wakes per thread after successful delivery", () => { + const threadId = "thread:fleet"; + const { state } = recordThreadEvents( + EMPTY_MODEL_ALERT_STATE, + { + threadId, + evaluated: ["thread-failed"], + findings: [finding("thread-failed", "run:1")], + }, + eventAlert, + ["watcher"], + 0, + ); + const entry = state.outbox[0]!; + const failed = afterDeliveryAttempt(state, entry, false, 10); + assert.isNull(failureWakeHold(failed.failureWakeSentAt[threadId], 100)); + const sent = afterDeliveryAttempt(failed, entry, true, 100); + assert.equal(failureWakeHold(sent.failureWakeSentAt[threadId], 101), 300100); + assert.isNull(failureWakeHold(sent.failureWakeSentAt[threadId], 300100)); + assert.isNull(failureWakeHold(sent.failureWakeSentAt["other"], 101)); + + const rerun = (state: ModelAlertState, runId: string) => + recordThreadEvents( + state, + { threadId, evaluated: ["thread-failed"], findings: [finding("thread-failed", runId)] }, + eventAlert, + ["watcher"], + 200, + ); + assert.isFalse(rerun(sent, "run:1").enqueued); + assert.isTrue(rerun(sent, "run:2").enqueued); +}); + it("reports a thread event once per kind and signature until its state changes", () => { let state = EMPTY_MODEL_ALERT_STATE; const enqueued: Array = []; @@ -394,6 +429,8 @@ it.effect("forwards a thread event to a watcher on another environment with one assert.match(String(called[0]!.arguments?.clientRequestId), /^thread-event:/); assert.equal(called[0]!.arguments?.clientRequestId, called[1]!.arguments?.clientRequestId); + assert.equal(called[0]!.arguments?.deliveryClass, "digest"); + // The same alert on the watcher's own machine queues into the thread directly. yield* deliverAlertToWatcher(deps, alert, laptop, EnvironmentId.make("laptop")); assert.equal(called.length, 2); @@ -402,6 +439,11 @@ it.effect("forwards a thread event to a watcher on another environment with one assert.deepEqual((dispatched[0] as { dispatchMode: unknown }).dispatchMode, { type: "queue_after_active", }); + const failure = eventAlert(finding("thread-failed", "run:1")); + yield* deliverAlertToWatcher(deps, failure, laptop, EnvironmentId.make("laptop")); + yield* deliverAlertToWatcher(deps, failure, laptop, EnvironmentId.make("r720")); + assert.equal((dispatched[1] as { delivery: { class: string } }).delivery.class, "next_turn"); + assert.equal(called[2]?.arguments?.deliveryClass, "next_turn"); }), ); diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.ts index c6b092a909475..a4bab3a3b946c 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.ts @@ -166,6 +166,9 @@ export const ModelAlertState = Schema.Struct({ incidentSentAt: Schema.Record(Schema.String, Schema.Number).pipe( Schema.withDecodingDefault(Effect.succeed({})), ), + failureWakeSentAt: Schema.Record(Schema.String, Schema.Number).pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), outbox: Schema.Array(Delivery), }); export type ModelAlertState = typeof ModelAlertState.Type; @@ -176,11 +179,13 @@ export const EMPTY_MODEL_ALERT_STATE: ModelAlertState = { reported: {}, resuming: {}, incidentSentAt: {}, + failureWakeSentAt: {}, outbox: [], }; const MAX_DEGRADED_THREADS = 1_000; const MAX_REPORTED = 2_000; +const FAILURE_WAKE_INTERVAL_MS = 5 * 60 * 1000; const MAX_OUTBOX = 200; const MAX_RESUMING = 2_000; const MAX_INCIDENT_GROUPS = 200; @@ -531,6 +536,12 @@ const lateMembers = (stored: UsageLimitIncident, sent: UsageLimitIncident) => ), ); +export function failureWakeHold(sentAt: number | undefined, nowMs: number) { + if (sentAt === undefined) return null; + const until = sentAt + FAILURE_WAKE_INTERVAL_MS; + return until > nowMs ? until : null; +} + /** * The state after one delivery attempt: a delivered entry leaves, a failed one waits longer. An * incident that gained members while it was being sent keeps those for a later digest. @@ -554,6 +565,17 @@ export function afterDeliveryAttempt( return { ...state, incidentSentAt, + failureWakeSentAt: + delivered && entry.destination === "watcher" && isFailureWake(entry.alert) + ? { + ...Object.fromEntries( + Object.entries(state.failureWakeSentAt).filter( + ([, sentAt]) => sentAt + FAILURE_WAKE_INTERVAL_MS > nowMs, + ), + ), + [entry.alert.threadId]: nowMs, + } + : state.failureWakeSentAt, reported: delivered ? recordStrandedDelivery(markLinkDelivered(state.reported, entry), entry, true) : state.reported, @@ -820,6 +842,11 @@ export const watcherAlertMessage = (alert: WatcherAlert) => { } }; +const isFailureWake = ( + alert: WatcherAlert, +): alert is ThreadEventAlert & { kind: "thread-failed" } => + alert.type === "thread-event" && alert.kind === "thread-failed"; + /** Alerts ride in the watcher's next digest; a newer alert on the same subject replaces an older one. */ function alertDelivery(alert: WatcherAlert): { readonly coalesceKey: string; @@ -868,6 +895,7 @@ export const deliverAlertToWatcher = Effect.fnUntraced(function* ( const expiresAt = DateTime.makeUnsafe( expiresAtMs ?? DateTime.toEpochMillis(yield* DateTime.now) + ALERT_DIGEST_TTL_MS, ); + const deliveryClass = isFailureWake(alert) ? "next_turn" : "digest"; if (watcher.environmentId === here) { yield* deps.dispatch({ type: "message.dispatch", @@ -877,7 +905,7 @@ export const deliverAlertToWatcher = Effect.fnUntraced(function* ( text: message, attachments: [], dispatchMode: { type: "queue_after_active" }, - delivery: { class: "digest", coalesceKey, expiresAt, category }, + delivery: { class: deliveryClass, coalesceKey, expiresAt, category }, createdBy: "agent", creationSource: "server", }); @@ -891,7 +919,7 @@ export const deliverAlertToWatcher = Effect.fnUntraced(function* ( message, mode: "queue", clientRequestId: key, - deliveryClass: "digest", + deliveryClass, coalesceKey, expiresAt: DateTime.formatIso(expiresAt), digestCategory: category, @@ -1274,10 +1302,23 @@ export const make = Effect.gen(function* () { return { _tag: "sent" } satisfies DeliveryResult; } const watcher = current.modelAlertWatcher; - const target = alert.type === "thread-event" ? (alert.recipient ?? null) : watcher; + const target = + alert.type === "thread-event" && !isFailureWake(alert) ? (alert.recipient ?? null) : watcher; + if ( + isFailureWake(alert) && + (target === null || + (target.environmentId === alert.environmentId && target.threadId === alert.threadId)) + ) { + return { _tag: "dropped" } satisfies DeliveryResult; + } if (target === null) return { _tag: "sent" } satisfies DeliveryResult; const here = yield* environment.getEnvironmentId; const nowMs = yield* Clock.currentTimeMillis; + if (isFailureWake(alert)) { + const sentAt = (yield* Ref.get(state)).failureWakeSentAt[alert.threadId]; + const until = failureWakeHold(sentAt, nowMs); + if (until !== null) return { _tag: "held", until } satisfies DeliveryResult; + } const view = target.environmentId === watcher?.environmentId && target.threadId === watcher.threadId ? yield* watcherView @@ -1670,14 +1711,18 @@ export const make = Effect.gen(function* () { }); const label = (yield* environment.getDescriptor).label; const occurredAt = DateTime.formatIso(yield* DateTime.now); - const recipient = yield* launchingThread(shell, here); - const destinations = threadEventDestinations(recipient, current.modelAlertWebhookUrl); + const launcher = yield* launchingThread(shell, here); + const hasFailure = judged.findings.some((finding) => finding.kind === "thread-failed"); + const launcherIsWatcher = + launcher !== null && + launcher.environmentId === watcher?.environmentId && + launcher.threadId === watcher.threadId; if ( !selfWatch && !noGlobalDestination && - recipient === null && - destinations.length === 0 && - judged.findings.length > 0 + launcher === null && + current.modelAlertWebhookUrl.trim() === "" && + judged.findings.some((finding) => finding.kind !== "thread-failed") ) { yield* Effect.logWarning("a thread event has no launching thread and no webhook", { threadId, @@ -1687,23 +1732,40 @@ export const make = Effect.gen(function* () { const enqueued = selfWatch || noGlobalDestination ? false - : yield* update((state) => { - const result = recordThreadEvents( - state, - { threadId, ...judged, ...context }, - (finding) => - threadEventAlert({ - environmentId: here, - environmentLabel: label, - shell, - finding, - occurredAt, - recipient, - }), - destinations, - nowMs, - ); - return [result.enqueued, result.state]; + : yield* update((initial) => { + let state = initial; + let queued = false; + for (const kind of judged.evaluated) { + const overlapping = kind === "lane-ended" && hasFailure; + const recipient = + kind === "thread-failed" + ? watcher + : overlapping && launcherIsWatcher + ? null + : launcher; + const destinations = threadEventDestinations( + recipient, + kind === "thread-failed" ? "" : current.modelAlertWebhookUrl, + ); + const result = recordThreadEvents( + state, + { threadId, evaluated: [kind], findings: judged.findings, ...context }, + (finding) => + threadEventAlert({ + environmentId: here, + environmentLabel: label, + shell, + finding, + occurredAt, + recipient, + }), + destinations, + nowMs, + ); + state = result.state; + queued ||= result.enqueued; + } + return [queued, state]; }); if (enqueued) yield* Queue.offer(wake, undefined); yield* Effect.forEach( diff --git a/apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts b/apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts index 0b49669114a5c..a000404305e7a 100644 --- a/apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts +++ b/apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts @@ -105,7 +105,10 @@ it.each(["failed", "interrupted"] as const)( "a %s run on a thread a person created is not a lane event", (status) => { const { findings } = judge(shellWith({ status, createdBy: "user" } as never), "run-ended"); - assert.deepEqual(findings, []); + assert.deepEqual( + findings.map((finding) => finding.kind), + status === "failed" ? ["thread-failed"] : [], + ); const stuck = judge( shellWith({ createdBy: "user", @@ -124,7 +127,25 @@ it("lane-ended stays quiet for a failure the model alert already reported as a u const { findings } = judge(shellWith({ status: "failed" } as never), "run-ended", { usageLimitReported: true, }); - assert.deepEqual(findings, []); + assert.deepEqual( + findings.map((finding) => finding.kind), + ["thread-failed"], + ); +}); + +it.each([ + { settledOverride: "settled" }, + { archivedAt: at(1) }, + { delegatedFrom: { threadId: "remote-parent" } }, + { lineage: { parentThreadId: "parent", relationshipToParent: "fork" } }, + { lineage: { parentThreadId: null, sideChat: true } }, + { status: "interrupted" }, + { activeRunId: "next" }, +])("excludes ineligible failed threads from watcher wakes: %j", (override) => { + const shell = shellWith({ status: "failed", ...override } as never); + assert.isFalse( + judge(shell, "run-ended").findings.some((finding) => finding.kind === "thread-failed"), + ); }); it("promise-without-wake: flags the Fleet lane's real message when nothing is tracked", () => { @@ -435,6 +456,7 @@ it("a thread event still holds when delivery waited past the recent-run window", it("each trigger evaluates only the kinds it can change", () => { assert.deepEqual(judge(shellWith(), "run-ended").evaluated, [ "lane-ended", + "thread-failed", "promise-without-wake", ]); assert.deepEqual(judge(shellWith(), "sweep").evaluated, ["stuck"]); diff --git a/apps/server/src/orchestration-v2/ThreadEventAlerts.ts b/apps/server/src/orchestration-v2/ThreadEventAlerts.ts index ecf01ad685a43..f36d2fa135166 100644 --- a/apps/server/src/orchestration-v2/ThreadEventAlerts.ts +++ b/apps/server/src/orchestration-v2/ThreadEventAlerts.ts @@ -1,6 +1,7 @@ import { type EnvironmentId, isListedThreadLineage, + isDelegatedAppThread, ModelAlertWatcher, type OrchestrationV2ThreadShell, } from "@t3tools/contracts"; @@ -16,6 +17,7 @@ import * as Schema from "effect/Schema"; */ export const ThreadEventKind = Schema.Literals([ "lane-ended", + "thread-failed", "promise-without-wake", "stuck", "needs-person", @@ -46,7 +48,7 @@ export type ThreadEventAlert = typeof ThreadEventAlert.Type; export type ThreadEventTrigger = "run-ended" | "settled" | "inbox" | "request" | "sweep"; const KINDS_BY_TRIGGER: Record> = { - "run-ended": ["lane-ended", "promise-without-wake"], + "run-ended": ["lane-ended", "thread-failed", "promise-without-wake"], settled: ["promise-without-wake"], inbox: ["needs-person"], request: ["needs-person"], @@ -59,6 +61,7 @@ export type WatchedShell = Pick< | "title" | "createdBy" | "lineage" + | "delegatedFrom" | "inbox" | "status" | "activeRunId" @@ -221,6 +224,24 @@ export function judgeThread(input: { } } + if ( + evaluated.includes("thread-failed") && + shell.status === "failed" && + shell.latestRunId !== null && + !isLive(shell) && + shell.lineage.parentThreadId === null && + isListedThreadLineage(shell.lineage) && + !isDelegatedAppThread(shell) && + shell.archivedAt === null && + shell.settledOverride !== "settled" + ) { + findings.push({ + kind: "thread-failed", + detail: "its last run failed", + signature: shell.latestRunId, + }); + } + if (evaluated.includes("promise-without-wake") && watched && !isLive(shell)) { const message = shell.latestVisibleMessage; const endedMs = timeMs(shell.latestRunCompletedAt); @@ -366,7 +387,7 @@ export function threadEventAlert(input: { kind: finding.kind, // The time makes each occurrence its own message: the delivery key hashes this id, and a // recurrence of the same state must not be taken for a replay of the first. - id: `${input.environmentId}:${shell.id}:${finding.kind}:${finding.signature}:${input.occurredAt}`, + id: `${input.environmentId}:${shell.id}:${finding.kind}:${finding.signature}${finding.kind === "thread-failed" ? "" : `:${input.occurredAt}`}`, environmentId: input.environmentId, environmentLabel: input.environmentLabel, threadId: shell.id, @@ -377,7 +398,10 @@ export function threadEventAlert(input: { ), runId: shell.activeRunId ?? shell.latestRunId, detail: finding.detail, - lastAssistantLine: message?.role === "assistant" ? lastLine(message.text) : null, + lastAssistantLine: + finding.kind !== "thread-failed" && message?.role === "assistant" + ? lastLine(message.text) + : null, lastError: shell.lastError === null || shell.lastError === undefined ? null : lastLine(shell.lastError), openPullRequests: openPullRequests({ pullRequests: shell.pullRequests } as WatchedShell) @@ -390,6 +414,7 @@ export function threadEventAlert(input: { /** The trigger that judges each kind again at delivery: any trigger whose kinds include it. */ export const REJUDGE_TRIGGER: Record = { + "thread-failed": "run-ended", "lane-ended": "run-ended", "promise-without-wake": "settled", stuck: "sweep", @@ -427,11 +452,14 @@ export function threadEventStillHolds(input: { return findings.some( (finding) => finding.kind === alert.kind && - alert.id === `${prefix}${finding.signature}:${alert.occurredAt}`, + (alert.kind === "thread-failed" + ? alert.runId === finding.signature + : alert.id === `${prefix}${finding.signature}:${alert.occurredAt}`), ); } const NEXT_STEP: Record = { + "thread-failed": "Triage the failed run. Check its retry history before taking action.", "lane-ended": "Check the thread: restart, repair or replace it, or settle it if its work is done. It sends no further alert for this run.", "promise-without-wake": diff --git a/apps/server/src/peer/placementEvidence.ts b/apps/server/src/peer/placementEvidence.ts index 92fd2fd8ed0b0..7c5c994736003 100644 --- a/apps/server/src/peer/placementEvidence.ts +++ b/apps/server/src/peer/placementEvidence.ts @@ -1,5 +1,4 @@ import { - isProviderAvailable, type ModelSelection, type ProjectId, resolveProjectProviderInstanceEnabled, @@ -9,7 +8,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; -import { findServedModel } from "../provider/servedModel.ts"; +import { findServedModel, providerReadinessConstraints } from "../provider/servedModel.ts"; import * as HostResources from "../resourceTelemetry/HostResources.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -32,8 +31,7 @@ export const hereEvidence = Effect.fn("placement.hereEvidence")(function* (input resources: Option.isSome(hostResources) ? yield* hostResources.value.read : null, modelAvailable: provider !== undefined && - provider.enabled && - isProviderAvailable(provider) && + providerReadinessConstraints(provider).length === 0 && resolveProjectProviderInstanceEnabled(settings, input.projectId, provider.instanceId) && findServedModel(provider.models, input.modelSelection.model) !== undefined && (provider.supportedRuntimeModes === undefined || diff --git a/apps/server/src/provider/servedModel.ts b/apps/server/src/provider/servedModel.ts index 67beac72dea78..b27c2a40187fc 100644 --- a/apps/server/src/provider/servedModel.ts +++ b/apps/server/src/provider/servedModel.ts @@ -1,10 +1,32 @@ -import type { - ModelSelection, - OrchestrationV2ServerCommand, - ServerProvider, - ServerProviderModel, +import { + isProviderAvailable, + type ModelSelection, + type OrchestrationV2ServerCommand, + type ServerProvider, + type ServerProviderModel, } from "@t3tools/contracts"; +export function providerReadinessConstraints(provider: ServerProvider): string[] { + const constraints: string[] = []; + if (!isProviderAvailable(provider)) { + constraints.push(provider.unavailableReason ?? "Provider driver is unavailable."); + } + if (!provider.enabled) { + constraints.push("Provider instance is disabled."); + // Disabled snapshots contain placeholders for installation, health, and auth. + return constraints; + } + if (!provider.installed) constraints.push("Provider executable is not installed."); + if (provider.status === "error" || provider.status === "disabled") { + constraints.push(provider.message ?? `Provider status is ${provider.status}.`); + } + if (provider.auth.status === "unauthenticated") { + constraints.push("Provider is not authenticated."); + } + if (provider.models.length === 0) constraints.push("No models available."); + return constraints; +} + const LISTED_MODEL_LIMIT = 8; type ListedModel = Pick; @@ -46,7 +68,6 @@ export function unservedModelMessage( models: ReadonlyArray, ): string | undefined { if ( - models.length === 0 || models.every((candidate) => candidate.isCustom) || findServedModel(models, model) !== undefined ) diff --git a/docs/operations/watcher-thread.md b/docs/operations/watcher-thread.md index 9608770fa2e8c..be95371c16c8b 100644 --- a/docs/operations/watcher-thread.md +++ b/docs/operations/watcher-thread.md @@ -1,17 +1,20 @@ # Watcher thread -One thread, by default Kameron's CoS on the laptop, hears model, usage-limit and link alerts from every linked environment. The thread events below go instead to the thread that launched the lane, read from the lane's `inbox.origin`, else `inbox.requestedBy`. When that thread is archived, deleted or unknown, a thread event reaches no thread, only `modelAlertWebhookUrl` when set, so a founder-facing watcher never hears about a lane it did not launch. The server decides each event from thread state with no agent judgment, queues it durably, and retries until the receiving machine answers. +One thread, by default Kameron's CoS on the laptop, hears model, usage-limit and link alerts from every linked environment. A `thread-failed` event starts a watcher turn for a failed, unsettled top-level thread, including one a person created. Other thread events go to the thread that launched the lane, read from the lane's `inbox.origin`, else `inbox.requestedBy`. If the launcher is archived, deleted or unknown, those launcher events go only to `modelAlertWebhookUrl` when configured. The server decides each event from thread state with no agent judgment, queues it durably, and retries until the receiving machine answers. | Event | Fires when | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `model-degraded` | A run ran another model than selected, hit a provider fallback, or hit a usage limit. | +| `thread-failed` | A top-level thread’s latest run failed. The server wakes the configured watcher even when the thread has no launcher. | | `lane-ended` | A top-level lane's run ended `failed` or `interrupted`, or `completed` with open pull requests and nothing tracked to wake it. | | `promise-without-wake` | A lane went idle or settled after saying it will be woken or will continue later, with no background task, pull request watch, delegated task or armed resume. The phrase list is `PROMISE_PHRASES` in `ThreadEventAlerts.ts`. | | `stuck` | An active run has had no new activity for `watcherStuckMinutes` (default 20; 0 turns it off), or a thread waits on background work that no longer exists. A parent whose child threads are active is not stuck. | | `needs-person` | An agent-created lane raises a pending question or approval, or its inbox is assigned to a founder or set to `action`. | +After a failure wake, another failure on that thread waits five minutes from delivery. The server checks that the failed run is still current before sending it. The receiving watcher decides whether to retry or escalate. + Each event reports once per thread and kind until its state changes: a new run, a different message, or the condition clearing. Delivery judges each event again, as of when it fired, and drops one that is no longer true: the lane restarted, settled, registered a wait, merged its pull request or got its answer. A dropped event stays reported, so the same state coming back does not alert again until its run or message changes. While the watcher is busy (running, queued or waiting), every alert to it, including model and usage-limit alerts, waits up to 10 minutes instead of queueing behind that turn, so it is judged when the watcher can act. A held alert is looked at again on a later flush, about every 30 to 60 seconds. Delegated children are skipped; their parent already hears their result. The watcher thread never reports about itself. ## Moving the watcher -The watcher is the `modelAlertWatcher` server setting (`{ environmentId, threadId }`, or `null` for none). Its Closura default is in `packages/contracts/src/settings.ts` (`DEFAULT_MODEL_ALERT_WATCHER`). To move the watcher, for example to an always-on machine such as the R720, change that one default and ship a build, or set `modelAlertWatcher` in each machine's settings to override it. `modelAlertWebhookUrl` additionally POSTs every alert as JSON. +The watcher is the `modelAlertWatcher` server setting (`{ environmentId, threadId }`, or `null` for none). Its Closura default is in `packages/contracts/src/settings.ts` (`DEFAULT_MODEL_ALERT_WATCHER`). To move the watcher, for example to an always-on machine such as the R720, change that one default and ship a build, or set `modelAlertWatcher` in each machine's settings to override it. `modelAlertWebhookUrl` additionally POSTs the existing digest alerts as JSON. Failure wakes go directly to the configured watcher. diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 7a0783e93e52e..cc154177b52f1 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1657,9 +1657,8 @@ export const ServerSettings = Schema.Struct({ ), /** * The watcher thread. It hears a run that ran another model than selected, hit a provider - * safeguard fallback or a usage limit, and each lane that ended, promised to continue with - * nothing to wake it, got stuck or needs a person. Each reports once per thread until its state - * changes. Null reports to no thread. + * safeguard fallback or a usage limit. A failed unsettled top-level thread wakes it for + * triage. Other lane events go to the launching thread. Null disables watcher delivery. */ modelAlertWatcher: Schema.NullOr(ModelAlertWatcher).pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_MODEL_ALERT_WATCHER)), From 7c1cfb7201c413256dcaa4e98c437ac613394a47 Mon Sep 17 00:00:00 2001 From: Kameron Smith Date: Tue, 24 Nov 2026 14:38:05 -0500 Subject: [PATCH 4/4] fix(server): wake the watcher only for failed threads with no launcher The failure wake fired for every failed top-level lane, so the watcher also heard about lanes another thread launched, and the "never Lead" lane-routing test saw five wakes instead of one. A failure wake now needs a thread with no recorded launcher, such as one a person created. Lanes with a launcher keep the lane-ended route to that launcher. A failure the model alert already reports as a usage limit gets no failure wake; it goes only into that limit's one grouped alert or the auto-resume path. A failure wake also waits while the watcher itself is stopped at its own usage limit, through the existing hold, now the exported watcherLimitHold. Drop the bundled provider-readiness change (servedModel, placement evidence, project launch and the orchestrator capabilities report). It was unrelated to the wake and rejected launches on an unregistered provider, which failed the remote delegation tests. Tests cover one usage limit failing several threads (one grouped alert, no per-thread wake), the watcher's own failure (no wake), launcher exclusions and the watcher usage-limit hold. Model: claude-opus-5-5 Task: CLO-1066 Agent: claude-code Co-Authored-By: Claude Opus 5.5 --- .../src/mcp/OrchestratorMcpService.test.ts | 200 ++++++++---------- apps/server/src/mcp/OrchestratorMcpService.ts | 42 ++-- .../src/mcp/toolkits/project/handlers.test.ts | 54 +---- .../src/mcp/toolkits/project/handlers.ts | 26 +-- .../DelegatedCompletionDelivery.test.ts | 104 +++++++++ .../ModelAlertReactor.test.ts | 21 ++ .../src/orchestration-v2/ModelAlertReactor.ts | 80 ++++--- .../ThreadEventAlerts.test.ts | 7 +- .../src/orchestration-v2/ThreadEventAlerts.ts | 2 + apps/server/src/peer/placementEvidence.ts | 6 +- apps/server/src/provider/servedModel.ts | 33 +-- docs/operations/watcher-thread.md | 6 +- packages/contracts/src/settings.ts | 5 +- 13 files changed, 310 insertions(+), 276 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index ecac81328b3ab..f1fea0ef040f7 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -2011,19 +2011,6 @@ describe("OrchestratorMcpService provider resolution", () => { assert.deepEqual(entry!.constraints, []); } - providers = providers.map((provider) => - provider.instanceId === antigravityInstanceId - ? { ...provider, models: [], auth: { status: "unauthenticated" } } - : provider, - ); - const signedOut = (yield* service.capabilities(scope)).providers.find( - (provider) => provider.providerInstanceId === antigravityInstanceId, - ); - assert.isFalse(signedOut?.canRunChildTask); - assert.isFalse(signedOut?.canRunCrossProviderChildTask); - assert.include(signedOut?.constraints ?? [], "No models available."); - assert.include(signedOut?.constraints ?? [], "Provider is not authenticated."); - const disabled = byId.get(disabledAntigravityInstanceId); assert.isDefined(disabled); assert.isFalse(disabled!.canRunChildTask); @@ -2252,111 +2239,94 @@ describe("OrchestratorMcpService provider resolution", () => { ); }); - it.effect.each([ - "already advertised", - "newly advertised", - "still unavailable", - "empty catalog", - "unauthenticated", - ] as const)("rechecks a delegated model that is %s", (availability) => - Effect.gen(function* () { - const museInstanceId = ProviderInstanceId.make("muse"); - const model = "muse-wonder-1.0"; - const provider = (advertisedModel: string): ServerProvider => { - const snapshot = providerSnapshot({ - instanceId: museInstanceId, - driver: ProviderDriverKind.make("muse"), - model: advertisedModel, - }); - if (availability === "empty catalog") return { ...snapshot, models: [] }; - if (availability === "unauthenticated") - return { ...snapshot, auth: { status: "unauthenticated" } }; - return snapshot; - }; - const commands: Array = []; - const refreshedInstances: Array = []; - const task = { - id: taskId, - threadId: parentThreadId, - origin: "app_owned", - childThreadId, - providerInstanceId: museInstanceId, - model, - status: "running", - result: null, - }; - const dependencies = Layer.mergeAll( - NodeServices.layer, - NodeCrypto.layer, - Layer.mock(ThreadManagementService.ThreadManagementService)({ - hasReceipt: () => Effect.succeed(false), - getThreadRecords: (threadId) => - Effect.succeed( - threadId === parentThreadId - ? parentProjection(commands.length > 0 ? [task] : []) - : childProjection, - ), - dispatch: (command) => - Effect.sync(() => { - commands.push(command); - return { - sequence: 1, - storedEvents: [{ event: { type: "subagent.updated", payload: task } }], - } as never; - }), - }), - ServerSettings.layerTest(), - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([ - provider(availability === "already advertised" ? model : "muse-spark-1.3"), - ]), - refreshInstance: (instanceId) => - Effect.sync(() => { - refreshedInstances.push(instanceId); - return [provider(availability === "still unavailable" ? "muse-spark-1.3" : model)]; - }), - }), - adapterRegistryLayer([museInstanceId]), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), - ); - yield* Effect.gen(function* () { - const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const delegation = service.delegateTask(scope, { - task: "Review the change.", - target: { providerInstanceId: museInstanceId, model }, - mode: "async", - clientRequestId: availability, - }); - if (availability === "empty catalog" || availability === "unauthenticated") { - const error = yield* delegation.pipe(Effect.flip); - assert.equal(error.code, "provider_unavailable"); - assert.include( - error.message, - availability === "empty catalog" ? "No models available" : "not authenticated", - ); - assert.deepEqual(commands, []); - } else if (availability === "still unavailable") { - const error = yield* delegation.pipe(Effect.flip); - assert.equal(error.code, "model_unavailable"); - assert.deepEqual(commands, []); - } else { - const result = yield* delegation; - assert.equal(result.model, model); - assert.equal(commands.length, 1); - assert.deepEqual((commands[0] as { modelSelection: unknown }).modelSelection, { + it.effect.each(["already advertised", "newly advertised", "still unavailable"] as const)( + "rechecks a delegated model that is %s", + (availability) => + Effect.gen(function* () { + const museInstanceId = ProviderInstanceId.make("muse"); + const model = "muse-wonder-1.0"; + const provider = (advertisedModel: string) => + providerSnapshot({ instanceId: museInstanceId, - model, + driver: ProviderDriverKind.make("muse"), + model: advertisedModel, }); - } - assert.deepEqual( - refreshedInstances, - availability === "already advertised" ? [] : [museInstanceId], + const commands: Array = []; + const refreshedInstances: Array = []; + const task = { + id: taskId, + threadId: parentThreadId, + origin: "app_owned", + childThreadId, + providerInstanceId: museInstanceId, + model, + status: "running", + result: null, + }; + const dependencies = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + hasReceipt: () => Effect.succeed(false), + getThreadRecords: (threadId) => + Effect.succeed( + threadId === parentThreadId + ? parentProjection(commands.length > 0 ? [task] : []) + : childProjection, + ), + dispatch: (command) => + Effect.sync(() => { + commands.push(command); + return { + sequence: 1, + storedEvents: [{ event: { type: "subagent.updated", payload: task } }], + } as never; + }), + }), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([ + provider(availability === "already advertised" ? model : "muse-spark-1.3"), + ]), + refreshInstance: (instanceId) => + Effect.sync(() => { + refreshedInstances.push(instanceId); + return [provider(availability === "still unavailable" ? "muse-spark-1.3" : model)]; + }), + }), + adapterRegistryLayer([museInstanceId]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); - }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); - }), + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const delegation = service.delegateTask(scope, { + task: "Review the change.", + target: { providerInstanceId: museInstanceId, model }, + mode: "async", + clientRequestId: availability, + }); + if (availability === "still unavailable") { + const error = yield* delegation.pipe(Effect.flip); + assert.equal(error.code, "model_unavailable"); + assert.deepEqual(commands, []); + } else { + const result = yield* delegation; + assert.equal(result.model, model); + assert.equal(commands.length, 1); + assert.deepEqual((commands[0] as { modelSelection: unknown }).modelSelection, { + instanceId: museInstanceId, + model, + }); + } + assert.deepEqual( + refreshedInstances, + availability === "already advertised" ? [] : [museInstanceId], + ); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); + }), ); it.effect("rejects delegation to a provider without a registered adapter", () => diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 8b043423150c7..d2e27a3ba8784 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -8,6 +8,7 @@ import { CommandId, EnvironmentId, type RunId, + isProviderAvailable, MessageId, type ModelSelection, NodeId, @@ -134,11 +135,7 @@ import { isSnoozed } from "../orchestration-v2/ThreadSettlementService.ts"; import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; -import { - findServedModel, - providerReadinessConstraints, - unservedModelMessage, -} from "../provider/servedModel.ts"; +import { findServedModel, unservedModelMessage } from "../provider/servedModel.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; import * as ServerSettings from "../serverSettings.ts"; import { @@ -406,8 +403,9 @@ function antigravitySuffixedModel(provider: ServerProvider, model: string) { const withV = (version: string) => (version.startsWith("v") ? version : `v${version}`); +/** A provider that lists no models accepts any slug. */ export const requireAdvertisedModel = (provider: ServerProvider, model: string) => { - if (advertisedModel(provider, model) !== undefined) { + if (provider.models.length === 0 || advertisedModel(provider, model) !== undefined) { return Effect.void; } const updateRequired = provider.updateRequiredModels?.find( @@ -436,11 +434,31 @@ function capabilityModelOption(descriptor: ProviderOptionDescriptor): Orchestrat }; } -function providerConstraints(provider: ServerProvider, supportsOrchestrationV2: boolean) { - const readiness = providerReadinessConstraints(provider); - return supportsOrchestrationV2 - ? readiness - : ["No V2 provider adapter is registered.", ...readiness]; +function providerConstraints( + provider: ServerProvider | undefined, + supportsOrchestrationV2: boolean, +): ReadonlyArray { + const constraints: Array = []; + if (!supportsOrchestrationV2) { + constraints.push("No V2 provider adapter is registered."); + } + if (provider === undefined) return constraints; + if (!isProviderAvailable(provider)) { + constraints.push(provider.unavailableReason ?? "Provider driver is unavailable."); + } + if (!provider.enabled) { + constraints.push("Provider instance is disabled."); + // Disabled snapshots contain placeholders for installation, health, and auth. + return constraints; + } + if (!provider.installed) constraints.push("Provider executable is not installed."); + if (provider.status === "error" || provider.status === "disabled") { + constraints.push(provider.message ?? `Provider status is ${provider.status}.`); + } + if (provider.auth.status === "unauthenticated") { + constraints.push("Provider is not authenticated."); + } + return constraints; } /** t3_thread_launch keeps a selection as given, so it can hold options its model does not have. */ @@ -1659,7 +1677,7 @@ const make = Effect.gen(function* () { `Provider ${instanceId} has no model available for inheritance.`, ); } - yield* requireAdvertisedModel(provider, model); + if (requestedModel !== undefined) yield* requireAdvertisedModel(provider, model); const advertised = advertisedModel(provider, model); const descriptors = advertised?.capabilities?.optionDescriptors; const requestedOptions = withLegacyUltracodeEffort(descriptors, input.target?.options); diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index 98cd2d8d44e88..e07f0610a4212 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -73,30 +73,7 @@ const clientLaunchHarness = (input: { }; const layerDependencies = Layer.mergeAll( Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed( - input.providers ?? [ - { - instanceId: (input.overrideModel ?? modelSelection).instanceId, - driver: ProviderDriverKind.make((input.overrideModel ?? modelSelection).instanceId), - enabled: true, - installed: true, - status: "ready", - version: null, - auth: { status: "authenticated" }, - checkedAt: "2026-01-01T00:00:00Z", - models: [ - { - slug: (input.overrideModel ?? modelSelection).model, - name: "Default", - capabilities: null, - isCustom: false, - }, - ], - slashCommands: [], - skills: [], - }, - ], - ), + getProviders: Effect.succeed(input.providers ?? []), }), ServerSettings.layerTest({ fallbackModelSelection: input.fallbackModel ?? null, @@ -332,7 +309,7 @@ it.effect("a launch steps an inherited mode down to the provider's, and refuses version: null, auth: { status: "authenticated" }, checkedAt: "2026-01-01T00:00:00Z", - models: [{ slug: "pi-model", name: "Pi", capabilities: null, isCustom: false }], + models: [], slashCommands: [], skills: [], supportedRuntimeModes: ["approval-required", "auto-accept-edits", "full-access"], @@ -431,24 +408,6 @@ it.effect("a launch with a model its provider does not advertise creates no thre ), }); } - providers.push( - { ...providers[0]!, instanceId: ProviderInstanceId.make("empty"), models: [] }, - { - ...providers[0]!, - instanceId: ProviderInstanceId.make("signed-out"), - auth: { status: "unauthenticated" }, - }, - ); - for (const [instance, reason] of [ - ["missing", "not registered"], - ["empty", "No models available"], - ["signed-out", "not authenticated"], - ] as const) { - expect(yield* launchWith(instance, "claude-opus")).toMatchObject({ - code: "provider_unavailable", - message: expect.stringContaining(reason), - }); - } expect(launched).toHaveLength(0); expect(yield* launchWith("claudeAgent", "Opus")).toMatchObject({ @@ -877,14 +836,7 @@ it.effect("a client launches with the fallback for an exhausted default", () => version: null, auth: { status: "authenticated" }, checkedAt: "2026-01-01T00:00:00Z", - models: [ - { - slug: driver === "codex" ? fallbackModel.model : "claude-opus", - name: "Default", - capabilities: null, - isCustom: false, - }, - ], + models: [], slashCommands: [], skills: [], ...(driver === "claudeAgent" diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 1b788058a6a80..45fffd3ad2c96 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -32,7 +32,6 @@ import { mutateProjectWithClone } from "../../../project/ProjectMutation.ts"; import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts"; import * as Repositories from "../../../sourceControl/SourceControlRepositoryService.ts"; import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts"; -import { providerReadinessConstraints } from "../../../provider/servedModel.ts"; import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts"; import * as ServerSettings from "../../../serverSettings.ts"; import * as DateTime from "effect/DateTime"; @@ -401,6 +400,13 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { } if (project !== undefined && input.workspaceStrategy?.type === "existing_worktree") yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath); + if (!replaying && input.modelSelection !== undefined) { + const { instanceId, model } = input.modelSelection; + const providers = yield* (yield* ProviderRegistry.ProviderRegistry).getProviders; + const provider = providers.find((candidate) => candidate.instanceId === instanceId); + if (provider !== undefined) + yield* OrchestrationMcp.requireAdvertisedModel(provider, model); + } // Reject unresolved base refs and blocked branch names before accepting a launch; worktree provisioning happens later. if (!replaying && strategy?.type === "worktree") yield* ThreadLaunch.ThreadLaunchService.pipe( @@ -441,23 +447,11 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { let startedRuntimeMode = defaultRuntimeMode; if (!replaying) { const providers = yield* (yield* ProviderRegistry.ProviderRegistry).getProviders; - const provider = providers.find( - (candidate) => candidate.instanceId === modelSelection.instanceId, - ); - const constraints = - provider === undefined - ? ["Provider instance is not registered."] - : providerReadinessConstraints(provider); - if (provider === undefined || constraints.length > 0) { - return yield* new OrchestratorMcpFailure({ - code: "provider_unavailable", - message: `Provider ${modelSelection.instanceId} cannot launch a thread: ${constraints.join(" ")}`, - }); - } - yield* OrchestrationMcp.requireAdvertisedModel(provider, modelSelection.model); startedRuntimeMode = yield* resolveRuntimeMode(startedRuntimeMode, input.runtimeMode, { modelSelection, - supportedRuntimeModes: provider.supportedRuntimeModes, + supportedRuntimeModes: providers.find( + (provider) => provider.instanceId === modelSelection.instanceId, + )?.supportedRuntimeModes, }); } const result = yield* ThreadMessageIntake.launchThread({ diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 2476d2b834ac1..27fe5657d1d7d 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -5211,6 +5211,110 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { }), ); + it.effect.each(["usage limit", "self"] as const)( + "a failed thread with no launcher wakes the watcher once, except for its %s", + (exception) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const key = exception === "self" ? "failure-self" : "failure-limit"; + const projectId = ProjectId.make(`project:${key}`); + yield* ProjectService.ProjectService.pipe( + Effect.flatMap((projects) => + projects.create({ + commandId: CommandId.make(`command:${key}-project`), + projectId, + title: key, + workspaceRoot: `/workspace/${key}`, + }), + ), + ); + const createThread = (name: string) => + orchestrator + .dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:${key}:${name}`), + threadId: ThreadId.make(`thread:${key}:${name}`), + projectId, + title: name, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }) + .pipe(Effect.as(ThreadId.make(`thread:${key}:${name}`))); + const lead = yield* createThread("lead"); + const failing = exception === "self" ? [lead] : []; + const limited = + exception === "usage limit" + ? [ + yield* createThread("lane-1"), + yield* createThread("lane-2"), + yield* createThread("lane-3"), + ] + : []; + const plain = yield* createThread("plain"); + const { reactor } = yield* makeModelAlertReactor({ + watcher: { environmentId: hereEnvironmentId, threadId: lead }, + }); + for (const threadId of [...failing, ...limited, plain]) { + const runId = RunId.make(`run:${threadId}`); + const failed = runEvent({ threadId, runId, ordinal: 1, status: "failed", now }); + const limitError = { + id: EventId.make(`event:${threadId}:limit`), + type: "turn-item.updated" as const, + threadId, + occurredAt: now, + payload: { + id: TurnItemId.make(`turn-item:${threadId}:limit`), + type: "error" as const, + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "failed" as const, + title: "Usage limit reached", + startedAt: now, + completedAt: now, + updatedAt: now, + failure: { + class: "usage_limit" as const, + message: "Plan limit reached.", + code: "usageLimitExceeded", + retryable: null, + resetAt: null, + }, + }, + }; + yield* eventSink.write({ + commandId: CommandId.make(`command:${threadId}:failed`), + events: limited.includes(threadId) ? [failed, limitError] : [failed], + }); + yield* reactor.handle(failed); + } + yield* reactor.flush; + yield* TestClock.adjust("11 minutes"); + yield* reactor.flush; + const messages = (yield* orchestrator.getThreadProjection(lead)).messages; + const wakes = messages.filter((message) => message.text.startsWith("Thread event from")); + assert.equal(wakes.length, 1); + assert.include(wakes[0]?.text, `/${plain})`); + const incidents = messages.filter((message) => + message.text.includes("Usage limit incident"), + ); + assert.equal(incidents.length, limited.length === 0 ? 0 : 1); + for (const lane of limited) assert.include(incidents[0]?.text, `/${lane})`); + }), + ); + it.effect("sends a model alert over the link to the watcher's machine and retries it", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts index 77a60fc6d4569..9a2dd0bb7f6b8 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts @@ -28,6 +28,7 @@ import { recordThreadEvents, threadEventDestinations, watcherAlertMessage, + watcherLimitHold, } from "./ModelAlertReactor.ts"; import { ProviderExhaustion } from "./ProviderExhaustion.ts"; import { alertIsStale, expectsAutoResume, replacedBySibling } from "./UsageLimitIncidents.ts"; @@ -234,6 +235,26 @@ it("rate-limits subsequent failure wakes per thread after successful delivery", assert.isTrue(rerun(sent, "run:2").enqueued); }); +it("holds a failure wake while the watcher is stopped at its own usage limit", () => { + const wake = eventAlert(finding("thread-failed", "run:1")); + const nowMs = Date.parse("2026-11-19T04:00:00.000Z"); + const limited = { + status: "failed", + providerInstanceId: "codex", + usageLimited: true, + resetAt: "2026-11-19T04:02:00.000Z", + }; + assert.equal(watcherLimitHold(limited, wake, nowMs), Date.parse(limited.resetAt)); + assert.isNull(watcherLimitHold(limited, wake, Date.parse(limited.resetAt))); + assert.isNull(watcherLimitHold({ ...limited, usageLimited: false }, wake, nowMs)); + assert.isNull(watcherLimitHold({ ...limited, status: "idle" }, wake, nowMs)); + assert.isNull(watcherLimitHold({ ...limited, usageLimited: null, resetAt: null }, wake, nowMs)); + assert.isNull(watcherLimitHold(null, wake, nowMs)); + assert.isNull( + watcherLimitHold(limited, eventAlert(finding("promise-without-wake", "message:1")), nowMs), + ); +}); + it("reports a thread event once per kind and signature until its state changes", () => { let state = EMPTY_MODEL_ALERT_STATE; const enqueued: Array = []; diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.ts index a4bab3a3b946c..c9178a719fc9b 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.ts @@ -699,6 +699,40 @@ export function busyWatcherHold( return Math.min(nowMs + BUSY_WATCHER_RECHECK_MS, deadline); } +export type WatcherView = { + readonly status: string; + readonly providerInstanceId: string | null; + /** Null when unknown, as for a remote watcher. */ + readonly usageLimited: boolean | null; + readonly resetAt: string | null; +}; + +/** + * When the watcher's own thread is stopped at the same account limit, the time to look again. + * Anything sent now would only queue a turn that fails the same way. + */ +export function watcherLimitHold(view: WatcherView | null, alert: WatcherAlert, nowMs: number) { + const providerInstanceId = + alert.type === "usage-limit-incident" || + (alert.type === "model-degraded" && alert.reasons.includes("usage_limit")) + ? alert.providerInstanceId + : isFailureWake(alert) + ? (view?.providerInstanceId ?? null) + : null; + if (providerInstanceId === null || view === null) return null; + // A remote watcher counts as down only while the reset this alert reports is still ahead. + const down = + view.status === "failed" && + view.providerInstanceId === providerInstanceId && + view.usageLimited !== false; + const resetAt = view.resetAt ?? (alert.type === "usage-limit-incident" ? alert.resetAt : null); + if (!down) return null; + // Past the reset the limit is over: whatever keeps the watcher down, a message may restart it. + const resetMs = resetAt === null ? Number.NaN : Date.parse(resetAt); + if (!Number.isFinite(resetMs) || resetMs <= nowMs) return null; + return Math.min(resetMs, nowMs + HOLD_RECHECK_MS); +} + /** * Records a thread that stopped at a usage limit. The server resumes it at the reset, so Lead * hears nothing unless it does not come back; otherwise every thread of one provider account @@ -1021,13 +1055,6 @@ export const make = Effect.gen(function* () { expiresAtMs, ); - type WatcherView = { - readonly status: string; - readonly providerInstanceId: string | null; - /** Null when unknown, as for a remote watcher. */ - readonly usageLimited: boolean | null; - readonly resetAt: string | null; - }; const WatcherThreadStatus = Schema.Struct({ thread: Schema.Struct({ status: Schema.String, providerInstanceId: Schema.String }), }); @@ -1243,30 +1270,6 @@ export const make = Effect.gen(function* () { ); }); - /** - * When the watcher's own thread is stopped at the same account limit, the time to look again. - * Anything sent now would only queue a turn that fails the same way. - */ - const holdUntil = (view: WatcherView | null, alert: WatcherAlert, nowMs: number) => { - const providerInstanceId = - alert.type === "usage-limit-incident" || - (alert.type === "model-degraded" && alert.reasons.includes("usage_limit")) - ? alert.providerInstanceId - : null; - if (providerInstanceId === null || view === null) return null; - // A remote watcher counts as down only while the reset this alert reports is still ahead. - const down = - view.status === "failed" && - view.providerInstanceId === providerInstanceId && - view.usageLimited !== false; - const resetAt = view.resetAt ?? (alert.type === "usage-limit-incident" ? alert.resetAt : null); - if (!down) return null; - // Past the reset the limit is over: whatever keeps the watcher down, a message may restart it. - const resetMs = resetAt === null ? Number.NaN : Date.parse(resetAt); - if (!Number.isFinite(resetMs) || resetMs <= nowMs) return null; - return Math.min(resetMs, nowMs + HOLD_RECHECK_MS); - }; - type DeliveryResult = | { readonly _tag: "sent" } | { readonly _tag: "dropped" } @@ -1324,7 +1327,7 @@ export const make = Effect.gen(function* () { ? yield* watcherView : yield* readWatcher(target, here).pipe(Effect.catchCause(() => Effect.succeed(null))); const until = - holdUntil(view, alert, nowMs) ?? + watcherLimitHold(view, alert, nowMs) ?? busyWatcherHold(view?.status ?? null, entry.createdAt, nowMs); if (until !== null) return { _tag: "held", until } satisfies DeliveryResult; yield* deliverToWatcher( @@ -1712,11 +1715,6 @@ export const make = Effect.gen(function* () { const label = (yield* environment.getDescriptor).label; const occurredAt = DateTime.formatIso(yield* DateTime.now); const launcher = yield* launchingThread(shell, here); - const hasFailure = judged.findings.some((finding) => finding.kind === "thread-failed"); - const launcherIsWatcher = - launcher !== null && - launcher.environmentId === watcher?.environmentId && - launcher.threadId === watcher.threadId; if ( !selfWatch && !noGlobalDestination && @@ -1736,13 +1734,7 @@ export const make = Effect.gen(function* () { let state = initial; let queued = false; for (const kind of judged.evaluated) { - const overlapping = kind === "lane-ended" && hasFailure; - const recipient = - kind === "thread-failed" - ? watcher - : overlapping && launcherIsWatcher - ? null - : launcher; + const recipient = kind === "thread-failed" ? watcher : launcher; const destinations = threadEventDestinations( recipient, kind === "thread-failed" ? "" : current.modelAlertWebhookUrl, diff --git a/apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts b/apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts index a000404305e7a..92860800a53af 100644 --- a/apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts +++ b/apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts @@ -127,10 +127,7 @@ it("lane-ended stays quiet for a failure the model alert already reported as a u const { findings } = judge(shellWith({ status: "failed" } as never), "run-ended", { usageLimitReported: true, }); - assert.deepEqual( - findings.map((finding) => finding.kind), - ["thread-failed"], - ); + assert.deepEqual(findings, []); }); it.each([ @@ -141,6 +138,8 @@ it.each([ { lineage: { parentThreadId: null, sideChat: true } }, { status: "interrupted" }, { activeRunId: "next" }, + { inbox: { origin: { kind: "agent", id: "thread:launcher" } } }, + { inbox: { requestedBy: { kind: "agent", id: "thread:archived-launcher" } } }, ])("excludes ineligible failed threads from watcher wakes: %j", (override) => { const shell = shellWith({ status: "failed", ...override } as never); assert.isFalse( diff --git a/apps/server/src/orchestration-v2/ThreadEventAlerts.ts b/apps/server/src/orchestration-v2/ThreadEventAlerts.ts index f36d2fa135166..ed160d2dacfb5 100644 --- a/apps/server/src/orchestration-v2/ThreadEventAlerts.ts +++ b/apps/server/src/orchestration-v2/ThreadEventAlerts.ts @@ -227,6 +227,8 @@ export function judgeThread(input: { if ( evaluated.includes("thread-failed") && shell.status === "failed" && + input.usageLimitReported !== true && + launchingThreadId(shell.inbox) === null && shell.latestRunId !== null && !isLive(shell) && shell.lineage.parentThreadId === null && diff --git a/apps/server/src/peer/placementEvidence.ts b/apps/server/src/peer/placementEvidence.ts index 7c5c994736003..92fd2fd8ed0b0 100644 --- a/apps/server/src/peer/placementEvidence.ts +++ b/apps/server/src/peer/placementEvidence.ts @@ -1,4 +1,5 @@ import { + isProviderAvailable, type ModelSelection, type ProjectId, resolveProjectProviderInstanceEnabled, @@ -8,7 +9,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; -import { findServedModel, providerReadinessConstraints } from "../provider/servedModel.ts"; +import { findServedModel } from "../provider/servedModel.ts"; import * as HostResources from "../resourceTelemetry/HostResources.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -31,7 +32,8 @@ export const hereEvidence = Effect.fn("placement.hereEvidence")(function* (input resources: Option.isSome(hostResources) ? yield* hostResources.value.read : null, modelAvailable: provider !== undefined && - providerReadinessConstraints(provider).length === 0 && + provider.enabled && + isProviderAvailable(provider) && resolveProjectProviderInstanceEnabled(settings, input.projectId, provider.instanceId) && findServedModel(provider.models, input.modelSelection.model) !== undefined && (provider.supportedRuntimeModes === undefined || diff --git a/apps/server/src/provider/servedModel.ts b/apps/server/src/provider/servedModel.ts index b27c2a40187fc..67beac72dea78 100644 --- a/apps/server/src/provider/servedModel.ts +++ b/apps/server/src/provider/servedModel.ts @@ -1,32 +1,10 @@ -import { - isProviderAvailable, - type ModelSelection, - type OrchestrationV2ServerCommand, - type ServerProvider, - type ServerProviderModel, +import type { + ModelSelection, + OrchestrationV2ServerCommand, + ServerProvider, + ServerProviderModel, } from "@t3tools/contracts"; -export function providerReadinessConstraints(provider: ServerProvider): string[] { - const constraints: string[] = []; - if (!isProviderAvailable(provider)) { - constraints.push(provider.unavailableReason ?? "Provider driver is unavailable."); - } - if (!provider.enabled) { - constraints.push("Provider instance is disabled."); - // Disabled snapshots contain placeholders for installation, health, and auth. - return constraints; - } - if (!provider.installed) constraints.push("Provider executable is not installed."); - if (provider.status === "error" || provider.status === "disabled") { - constraints.push(provider.message ?? `Provider status is ${provider.status}.`); - } - if (provider.auth.status === "unauthenticated") { - constraints.push("Provider is not authenticated."); - } - if (provider.models.length === 0) constraints.push("No models available."); - return constraints; -} - const LISTED_MODEL_LIMIT = 8; type ListedModel = Pick; @@ -68,6 +46,7 @@ export function unservedModelMessage( models: ReadonlyArray, ): string | undefined { if ( + models.length === 0 || models.every((candidate) => candidate.isCustom) || findServedModel(models, model) !== undefined ) diff --git a/docs/operations/watcher-thread.md b/docs/operations/watcher-thread.md index be95371c16c8b..d0ce34e672cd7 100644 --- a/docs/operations/watcher-thread.md +++ b/docs/operations/watcher-thread.md @@ -1,17 +1,17 @@ # Watcher thread -One thread, by default Kameron's CoS on the laptop, hears model, usage-limit and link alerts from every linked environment. A `thread-failed` event starts a watcher turn for a failed, unsettled top-level thread, including one a person created. Other thread events go to the thread that launched the lane, read from the lane's `inbox.origin`, else `inbox.requestedBy`. If the launcher is archived, deleted or unknown, those launcher events go only to `modelAlertWebhookUrl` when configured. The server decides each event from thread state with no agent judgment, queues it durably, and retries until the receiving machine answers. +One thread, by default Kameron's CoS on the laptop, hears model, usage-limit and link alerts from every linked environment. A `thread-failed` event starts a watcher turn for a failed, unsettled top-level thread with no recorded launcher, such as one a person created. Other thread events go to the thread that launched the lane, read from the lane's `inbox.origin`, else `inbox.requestedBy`. If the launcher is archived, deleted or unknown, those launcher events go only to `modelAlertWebhookUrl` when configured. The server decides each event from thread state with no agent judgment, queues it durably, and retries until the receiving machine answers. | Event | Fires when | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `model-degraded` | A run ran another model than selected, hit a provider fallback, or hit a usage limit. | -| `thread-failed` | A top-level thread’s latest run failed. The server wakes the configured watcher even when the thread has no launcher. | +| `thread-failed` | A top-level thread with no recorded launcher failed, other than at a usage limit. The server wakes the configured watcher. | | `lane-ended` | A top-level lane's run ended `failed` or `interrupted`, or `completed` with open pull requests and nothing tracked to wake it. | | `promise-without-wake` | A lane went idle or settled after saying it will be woken or will continue later, with no background task, pull request watch, delegated task or armed resume. The phrase list is `PROMISE_PHRASES` in `ThreadEventAlerts.ts`. | | `stuck` | An active run has had no new activity for `watcherStuckMinutes` (default 20; 0 turns it off), or a thread waits on background work that no longer exists. A parent whose child threads are active is not stuck. | | `needs-person` | An agent-created lane raises a pending question or approval, or its inbox is assigned to a founder or set to `action`. | -After a failure wake, another failure on that thread waits five minutes from delivery. The server checks that the failed run is still current before sending it. The receiving watcher decides whether to retry or escalate. +A failure at a usage limit is reported only in that limit's one grouped alert, and a failure wake waits while the watcher itself is stopped at its usage limit. After a failure wake, another failure on that thread waits five minutes from delivery. The server checks that the failed run is still current before sending it. The receiving watcher decides whether to retry or escalate. Each event reports once per thread and kind until its state changes: a new run, a different message, or the condition clearing. Delivery judges each event again, as of when it fired, and drops one that is no longer true: the lane restarted, settled, registered a wait, merged its pull request or got its answer. A dropped event stays reported, so the same state coming back does not alert again until its run or message changes. While the watcher is busy (running, queued or waiting), every alert to it, including model and usage-limit alerts, waits up to 10 minutes instead of queueing behind that turn, so it is judged when the watcher can act. A held alert is looked at again on a later flush, about every 30 to 60 seconds. Delegated children are skipped; their parent already hears their result. The watcher thread never reports about itself. diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index cc154177b52f1..d835a995e8bbf 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1657,8 +1657,9 @@ export const ServerSettings = Schema.Struct({ ), /** * The watcher thread. It hears a run that ran another model than selected, hit a provider - * safeguard fallback or a usage limit. A failed unsettled top-level thread wakes it for - * triage. Other lane events go to the launching thread. Null disables watcher delivery. + * safeguard fallback or a usage limit. A failed unsettled top-level thread with no launcher + * wakes it for triage. Other lane events go to the launching thread. Null disables watcher + * delivery. */ modelAlertWatcher: Schema.NullOr(ModelAlertWatcher).pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_MODEL_ALERT_WATCHER)),