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/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 18eeccd3b61fb..9a2dd0bb7f6b8 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, @@ -26,6 +28,7 @@ import { recordThreadEvents, threadEventDestinations, watcherAlertMessage, + watcherLimitHold, } from "./ModelAlertReactor.ts"; import { ProviderExhaustion } from "./ProviderExhaustion.ts"; import { alertIsStale, expectsAutoResume, replacedBySibling } from "./UsageLimitIncidents.ts"; @@ -199,6 +202,59 @@ 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("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 = []; @@ -394,6 +450,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 +460,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..c9178a719fc9b 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, @@ -677,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 @@ -820,6 +876,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 +929,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 +939,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 +953,7 @@ export const deliverAlertToWatcher = Effect.fnUntraced(function* ( message, mode: "queue", clientRequestId: key, - deliveryClass: "digest", + deliveryClass, coalesceKey, expiresAt: DateTime.formatIso(expiresAt), digestCategory: category, @@ -993,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 }), }); @@ -1215,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" } @@ -1274,16 +1305,29 @@ 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 : 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( @@ -1670,14 +1714,13 @@ 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); 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 +1730,34 @@ 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 recipient = kind === "thread-failed" ? watcher : 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..92860800a53af 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", @@ -127,6 +130,23 @@ it("lane-ended stays quiet for a failure the model alert already reported as a u assert.deepEqual(findings, []); }); +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" }, + { 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( + 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", () => { const { findings } = judge( shellWith({ latestVisibleMessage: assistantSays(FLEET_PROMISE) } as never), @@ -435,6 +455,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..ed160d2dacfb5 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,26 @@ 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 && + 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 +389,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 +400,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 +416,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 +454,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/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/docs/operations/watcher-thread.md b/docs/operations/watcher-thread.md index 9608770fa2e8c..d0ce34e672cd7 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 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 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`. | +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. ## 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/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/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 7a0783e93e52e..d835a995e8bbf 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1657,9 +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, 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 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)), 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(" ")}`, 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);