diff --git a/apps/cli/package.json b/apps/cli/package.json index 6a8b905..64ed1cc 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,6 +1,6 @@ { "name": "@nettee/beacon", - "version": "0.8.15", + "version": "0.8.16", "description": "A single-host bridge from messaging and schedules to isolated agent runs", "license": "Apache-2.0", "repository": { diff --git a/services/daemon/src/run/model-fallback.test.ts b/services/daemon/src/run/model-fallback.test.ts new file mode 100644 index 0000000..639fe7f --- /dev/null +++ b/services/daemon/src/run/model-fallback.test.ts @@ -0,0 +1,102 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + HARDCODED_MODEL_FALLBACK, + isHardcodedFallbackModel, + isRetryableProviderFailure, + modelFallbackSessionId, +} from "./model-fallback.js"; + +test("HARDCODED_MODEL_FALLBACK is xai / grok-4.7 / high", () => { + assert.deepEqual(HARDCODED_MODEL_FALLBACK, { + provider: "xai", + id: "grok-4.7", + thinking: "high", + }); +}); + +test("isHardcodedFallbackModel matches provider+id+thinking", () => { + assert.equal( + isHardcodedFallbackModel({ + provider: "xai", + model: "grok-4.7", + thinking: "high", + }), + true, + ); + assert.equal( + isHardcodedFallbackModel({ + provider: "xai", + model: "grok-4.7", + }), + false, + ); + assert.equal( + isHardcodedFallbackModel({ + provider: "opencode-go", + model: "deepseek-v4.1-flash", + }), + false, + ); +}); + +test("isRetryableProviderFailure accepts supplier/API outages", () => { + const cases = [ + "Pi ended with stopReason=error: 429 Upstream Endpoint unavailable", + "Pi ended with stopReason=error: 503 Endpoint is unavailable", + "Codex error: Unable to verify model access right now. Please retry.", + "Request timed out", + "provider failed", + "rate limit exceeded", + "401 unauthorized", + "authentication failed for api key", + ]; + for (const message of cases) { + assert.equal( + isRetryableProviderFailure("runtime_exit_failed", message), + true, + message, + ); + } + assert.equal( + isRetryableProviderFailure( + "runtime_spawn_failed", + "spawn failed: 503 upstream unavailable", + ), + true, + ); +}); + +test("isRetryableProviderFailure rejects non-supplier failures", () => { + assert.equal( + isRetryableProviderFailure( + "runtime_timeout", + "Beacon Run hard timeout after 30min", + ), + false, + ); + assert.equal( + isRetryableProviderFailure("outcome_missing", "No Final Outcome"), + false, + ); + assert.equal( + isRetryableProviderFailure( + "runtime_exit_failed", + "Pi ended with stopReason=error: tool blew up", + ), + false, + ); + assert.equal( + isRetryableProviderFailure("capacity_exceeded", "queue full"), + false, + ); + assert.equal( + isRetryableProviderFailure("service_interrupted", "restarted"), + false, + ); +}); + +test("modelFallbackSessionId suffixes the run id", () => { + assert.equal(modelFallbackSessionId("run_abc"), "run_abc-fallback"); +}); diff --git a/services/daemon/src/run/model-fallback.ts b/services/daemon/src/run/model-fallback.ts new file mode 100644 index 0000000..1d9ec26 --- /dev/null +++ b/services/daemon/src/run/model-fallback.ts @@ -0,0 +1,70 @@ +import type { ProfileModelChoice } from "../config/model-pool.js"; +import type { FailureCode } from "../domain/types.js"; + +/** + * Hardcoded provider/model fallback when the Profile's selected model hits a + * retryable supplier/API error. Temporary fixed chain (BCN-37) — not config. + */ +export const HARDCODED_MODEL_FALLBACK = { + provider: "xai", + id: "grok-4.7", + thinking: "high", +} as const satisfies ProfileModelChoice; + +export type ModelFallbackChoice = typeof HARDCODED_MODEL_FALLBACK; + +/** True when the Run is already on the hardcoded fallback model. */ +export function isHardcodedFallbackModel(run: { + provider: string; + model: string; + thinking?: string | undefined; +}): boolean { + return ( + run.provider === HARDCODED_MODEL_FALLBACK.provider && + run.model === HARDCODED_MODEL_FALLBACK.id && + (run.thinking ?? undefined) === HARDCODED_MODEL_FALLBACK.thinking + ); +} + +/** + * Supplier / model errors that warrant a one-shot Grok retry. + * + * Only `runtime_exit_failed` and `runtime_spawn_failed` are candidates; + * timeouts, outcome contract misses, and local protocol errors are not. + */ +export function isRetryableProviderFailure( + code: FailureCode | string, + message: string, +): boolean { + if (code !== "runtime_exit_failed" && code !== "runtime_spawn_failed") { + return false; + } + const text = message.toLowerCase(); + return ( + /\b429\b/.test(text) || + /\b503\b/.test(text) || + /\b502\b/.test(text) || + /\b500\b/.test(text) || + /\b401\b/.test(text) || + /\b403\b/.test(text) || + /rate[\s_-]?limit/.test(text) || + /endpoint[\s\S]{0,40}(unavailable|overloaded)/.test(text) || + /upstream[\s\S]{0,40}(unavailable|error|timeout|overloaded)/.test(text) || + /unable to verify model access/.test(text) || + /request timed out/.test(text) || + /overloaded/.test(text) || + /authentication/.test(text) || + /unauthorized/.test(text) || + /forbidden/.test(text) || + /model[\s\S]{0,40}(not available|unavailable|access)/.test(text) || + /provider[\s\S]{0,20}(error|failed|unavailable)/.test(text) || + /codex error/.test(text) + ); +} + +/** Session id / path suffix for the fallback attempt within the same Run. */ +export const MODEL_FALLBACK_SESSION_SUFFIX = "-fallback"; + +export function modelFallbackSessionId(runId: string): string { + return `${runId}${MODEL_FALLBACK_SESSION_SUFFIX}`; +} diff --git a/services/daemon/src/run/orchestrator.test.ts b/services/daemon/src/run/orchestrator.test.ts index 866597e..2124636 100644 --- a/services/daemon/src/run/orchestrator.test.ts +++ b/services/daemon/src/run/orchestrator.test.ts @@ -2212,6 +2212,193 @@ test("recover still delivers missing reply among settled siblings", async () => } }); +test("retries retryable provider failure on hardcoded Grok without Feishu failure notify", async () => { + const directory = await mkdtemp(join(tmpdir(), "beacon-model-fallback-ok-")); + const store = new TriggerStore(directory, profile.id); + const claim = await store.claim({ + sourceKey: ["feishu", "fallback-ok"], + target: { kind: "reply", messageId: "message" }, + }); + const outcomes = await startOutcomeServer(); + const deliveries: FinalOutcomeContent["reply"][] = []; + const models: string[] = []; + let cascaded = 0; + let attempts = 0; + const orchestrator = new RunOrchestrator({ + profile, + store, + queue: new RunQueue({ maxConcurrent: 1, maxQueued: 1 }), + outcomes, + beaconCliPath: "/beacon", + sessionDirectory: "/beacon-sessions", + runAgent: async (request) => { + attempts += 1; + models.push( + `${request.provider}/${request.model}/${request.thinkingLevel ?? ""}`, + ); + if (attempts === 1) { + throw new PiRuntimeError( + "runtime_exit_failed", + "Pi ended with stopReason=error: 429 Upstream Endpoint unavailable", + ); + } + const { submitOutcome } = await import("../outcome/submit.js"); + if (!request.outcome) throw new Error("missing outcome binding"); + await submitOutcome( + request.outcome.socketPath, + request.outcome.runToken, + { + reply: { kind: "text", text: "grok recovered" }, + }, + ); + return { + text: "ignored", + provider: "xai", + model: "grok-4.7", + }; + }, + delivery: { + async deliver(_target, outcome) { + deliveries.push(outcome); + return {}; + }, + }, + onFailureCascade: { + profileId: "beacon-triage", + async enqueue() { + cascaded += 1; + }, + }, + }); + try { + await orchestrator.process(claim.record.triggerKey, async () => input); + const [record] = await store.list(); + assert.equal(attempts, 2); + assert.deepEqual(models, ["test/model/", "xai/grok-4.7/high"]); + assert.equal(record?.run?.state, "succeeded"); + assert.equal(record?.run?.provider, "xai"); + assert.equal(record?.run?.model, "grok-4.7"); + assert.equal(record?.run?.thinking, "high"); + assert.equal(record?.run?.sessionId, `${record?.run?.runId}-fallback`); + assert.equal(record?.finalOutcome?.origin, "agent"); + assert.deepEqual(deliveries, [{ kind: "text", text: "grok recovered" }]); + assert.equal(cascaded, 0); + assert.equal(record?.run?.failure, undefined); + } finally { + await outcomes.close(); + } +}); + +test("notifies Feishu only when primary and Grok fallback both fail", async () => { + const directory = await mkdtemp( + join(tmpdir(), "beacon-model-fallback-fail-"), + ); + const store = new TriggerStore(directory, profile.id); + const claim = await store.claim({ + sourceKey: ["feishu", "fallback-fail"], + target: { kind: "reply", messageId: "message" }, + }); + const outcomes = await startOutcomeServer(); + const deliveries: FinalOutcomeContent["reply"][] = []; + let cascaded = 0; + let attempts = 0; + const orchestrator = new RunOrchestrator({ + profile, + store, + queue: new RunQueue({ maxConcurrent: 1, maxQueued: 1 }), + outcomes, + beaconCliPath: "/beacon", + sessionDirectory: "/beacon-sessions", + runAgent: async () => { + attempts += 1; + throw new PiRuntimeError( + "runtime_exit_failed", + attempts === 1 + ? "Pi ended with stopReason=error: 503 Endpoint is unavailable" + : "Pi ended with stopReason=error: Codex error: Unable to verify model access right now. Please retry.", + ); + }, + delivery: { + async deliver(_target, outcome) { + deliveries.push(outcome); + return {}; + }, + }, + onFailureCascade: { + profileId: "beacon-triage", + async enqueue() { + cascaded += 1; + }, + }, + }); + try { + await orchestrator.process(claim.record.triggerKey, async () => input); + const [record] = await store.list(); + assert.equal(attempts, 2); + assert.equal(record?.run?.state, "failed"); + assert.equal(record?.run?.provider, "xai"); + assert.equal(record?.run?.model, "grok-4.7"); + assert.equal(record?.run?.thinking, "high"); + assert.equal(record?.finalOutcome?.origin, "beacon_failure"); + assert.equal(deliveries.length, 1); + assert.equal(cascaded, 1); + assert.match( + record?.run?.failure?.summary ?? "", + /Primary model failed; fallback xai\/grok-4\.7\/high also failed/, + ); + assert.match( + record?.run?.failure?.summary ?? "", + /Unable to verify model access/, + ); + } finally { + await outcomes.close(); + } +}); + +test("does not fallback for non-retryable runtime failures", async () => { + const directory = await mkdtemp( + join(tmpdir(), "beacon-model-fallback-skip-"), + ); + const store = new TriggerStore(directory, profile.id); + const claim = await store.claim({ + sourceKey: ["feishu", "fallback-skip"], + target: { kind: "reply", messageId: "message" }, + }); + const outcomes = await startOutcomeServer(); + let attempts = 0; + const orchestrator = new RunOrchestrator({ + profile, + store, + queue: new RunQueue({ maxConcurrent: 1, maxQueued: 1 }), + outcomes, + beaconCliPath: "/beacon", + sessionDirectory: "/beacon-sessions", + runAgent: async () => { + attempts += 1; + throw new PiRuntimeError( + "runtime_exit_failed", + "Pi ended with stopReason=error: tool blew up", + ); + }, + delivery: { + async deliver() { + return {}; + }, + }, + }); + try { + await orchestrator.process(claim.record.triggerKey, async () => input); + const [record] = await store.list(); + assert.equal(attempts, 1); + assert.equal(record?.run?.state, "failed"); + assert.equal(record?.run?.provider, "test"); + assert.equal(record?.run?.model, "model"); + assert.equal(record?.finalOutcome?.origin, "beacon_failure"); + } finally { + await outcomes.close(); + } +}); + for (const recoverQueued of [false, true]) { test(`event ${recoverQueued ? "recovery" : "processing"} waits for capacity without failing accepted work`, async () => { let reachedQueue!: () => void; diff --git a/services/daemon/src/run/orchestrator.ts b/services/daemon/src/run/orchestrator.ts index 5e8554a..5b4140b 100644 --- a/services/daemon/src/run/orchestrator.ts +++ b/services/daemon/src/run/orchestrator.ts @@ -50,6 +50,12 @@ import { profilePromptDigest, } from "../runtime/system-prompt.js"; import type { TriggerStore } from "../state/trigger-store.js"; +import { + HARDCODED_MODEL_FALLBACK, + isHardcodedFallbackModel, + isRetryableProviderFailure, + modelFallbackSessionId, +} from "./model-fallback.js"; import type { AgentRuntimeRunner } from "./profile-runner.js"; import type { RunQueue } from "./queue.js"; @@ -586,6 +592,62 @@ export class RunOrchestrator { }); } + /** + * On a retryable supplier/model error, patch this Run onto the hardcoded + * Grok fallback and re-execute once. Returns true when a fallback attempt + * was started (caller must not call `fail` — the re-execute settles). + * Feishu failure notify stays deferred until the fallback also fails. + */ + private async tryProviderModelFallback( + triggerKey: string, + input: TriggerInput, + runId: string, + code: FailureCode, + error: unknown, + ): Promise { + const detail = summary(error); + if (!isRetryableProviderFailure(code, detail)) return false; + const current = await this.record(triggerKey); + const run = current.run; + if (!run || run.runId !== runId) return false; + if (isHardcodedFallbackModel(run)) return false; + if (current.finalOutcome?.origin === "agent") return false; + + const from = `${run.provider}/${run.model}${ + run.thinking ? `/${run.thinking}` : "" + }`; + const to = `${HARDCODED_MODEL_FALLBACK.provider}/${HARDCODED_MODEL_FALLBACK.id}/${HARDCODED_MODEL_FALLBACK.thinking}`; + console.log( + `[beacon] model fallback run_id=${runId} from=${from} to=${to} code=${code} reason=${detail.slice(0, 240)}`, + ); + + const sessionId = modelFallbackSessionId(runId); + const sessionPath = join( + this.options.sessionDirectory, + this.options.profile.id, + sessionId, + ); + await this.options.store.update(triggerKey, (record) => ({ + ...record, + run: { + ...record.run!, + state: "queued", + provider: HARDCODED_MODEL_FALLBACK.provider, + model: HARDCODED_MODEL_FALLBACK.id, + thinking: HARDCODED_MODEL_FALLBACK.thinking, + sessionId, + sessionPath, + agent: undefined, + failure: undefined, + finishedAt: undefined, + usage: undefined, + }, + finalOutcome: undefined, + })); + await this.execute(triggerKey, input, runId); + return true; + } + private async fail( triggerKey: string, runId: string, @@ -608,6 +670,14 @@ export class RunOrchestrator { const hint = formatSettleFailureHint(settle ?? {}); if (hint) detail = `${detail}. ${hint}`; } + const priorForFallback = await this.record(triggerKey); + if ( + priorForFallback.run && + isHardcodedFallbackModel(priorForFallback.run) && + !detail.startsWith("Primary model failed;") + ) { + detail = `Primary model failed; fallback ${HARDCODED_MODEL_FALLBACK.provider}/${HARDCODED_MODEL_FALLBACK.id}/${HARDCODED_MODEL_FALLBACK.thinking} also failed: ${detail}`; + } const failure = { code, summary: detail }; const finishedAt = this.timestamp(); const prior = await this.record(triggerKey); @@ -745,6 +815,17 @@ export class RunOrchestrator { completion.error.message, ); } + if ( + await this.tryProviderModelFallback( + triggerKey, + input, + runId, + code, + failError, + ) + ) { + return; + } await this.fail( triggerKey, runId, @@ -989,6 +1070,17 @@ export class RunOrchestrator { : isMissingReplyOutcomeError(failError) ? "outcome_missing" : "runtime_exit_failed"; + if ( + await this.tryProviderModelFallback( + triggerKey, + input, + runId, + code, + failError, + ) + ) { + return; + } await this.fail( triggerKey, runId,